You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中json_serializable为何对setter抛出忽略警告?

问题:json_serializable为何抛出“Setters are ignored: Location.newName”警告?

我在Flutter中编写了一个表示地点的JSON可序列化类Location,仅包含ID和名称属性,代码如下:

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;
}

编译locations_data.g.dart文件时,出现如下警告:

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

除了一则GitHub issue外找不到更多相关信息,想知道这个警告的原因。


解答

这个警告的核心原因是json_serializable库只会处理类中带有@JsonKey注解的成员,而你的newName setter既没有被注解标记,也不属于库默认会处理的成员类型。

具体来说:

  • json_serializable在生成序列化/反序列化代码时,只会识别类中的实例字段,或者带有@JsonKey注解的getter方法(比如你用getter映射了JSON字段)。
  • 单独的setter方法(没有对应的、被注解的getter)不在库的处理范围内,它既不会参与JSON的序列化(toJson),也不会参与反序列化(fromJson),所以库会提示你这个setter被忽略了,避免你误以为它会和JSON处理逻辑关联。

如果你想消除这个警告,有两种常见方式:

  1. 调整现有属性的访问器,让setter和对应getter绑定并被注解识别:
    直接修改现有name的getter和setter,替代单独的newName setter:

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

这样既符合json_serializable的处理逻辑,也能正常修改名称,不会出现警告。
2. 明确标记忽略该setter:
如果你不需要这个setter参与JSON处理,可以给它加上`@JsonKey(ignore: true)`注解,告诉库主动忽略这个成员:
```dart
@JsonKey(ignore: true)
set newName(String name) => _name = name;

内容的提问来源于stack exchange,提问作者MisterMirko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 13:42:28