Flutter JSON serialization and Setters

171 views Asked by At

In flutter I have a simple JSON serializable class for a location with just an ID and a name like this:

import 'package:json_annotation/json_annotation.dart';

part 'locations_data.g.dart';

@JsonSerializable()
class Location {
  final int _id;
  String _name;

  Location({
    required int id,
    required String name,
  })  : _id = id,
        _name = name;

  @JsonKey(name: 'LocationId', required: true)
  int get id => _id;

  @JsonKey(name: 'LocationName', required: true)
  String get name => _name;

  factory Location.fromJson(Map<String, dynamic> json) =>
      _$LocationFromJson(json);

  Map<String, dynamic> toJson() => _$LocationToJson(this);

  // Why does json_serializable throw a warning?
  set newName(String name) => _name = name;
}

when I compile the locations_data.g.dart file it says:

[...]
[WARNING] json_serializable on lib/src/locations/locations_data.dart:
Setters are ignored: Location.newName
[...]

I can not find much about this except this GitHub issue

Why does json_serializable throw a warning?

1

There are 1 answers

0
jamesdlin On BEST ANSWER

json_serializable doesn't know what it's supposed to do with a setter that has no getter. How is it supposed to represent that in the generated JSON? It can't, so it ignores it and generates a warning.

Having a setter with no getter (or in this case, a setter with a different name from its getter) is a bad idea anyway, and the Dart analyzer would generate a warning during static analysis if you have the avoid_setters_without_getters lint enabled.