1

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?

2
  • 1
    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. Having a setter with no getter (or in this case, a setter with a different name from its getter) is a bad idea anyway. Commented Nov 27, 2023 at 17:41
  • The different names were the problem. Got it. Thanks a lot! If you post your comment as an answer, I can mark it as the solution to my question :) Commented Nov 27, 2023 at 18:56

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.