Flutter List调用map生成DataBaseModel实例属性全为null如何解决
问题原因
两个核心错误导致所有属性为null:
- 构造函数未绑定类成员:你定义的
DataBaseModel构造函数仅声明了同名参数,但没有通过this.属性名的方式将传入参数赋值给类的成员变量,即使参数传了正确的值,类属性也不会被赋值,默认保持null。 - 传参时错误添加引号:map遍历生成实例时,你给所有属性值都包裹了双引号,把Dart变量引用写成了固定字符串字面量,甚至
uid字段的引号嵌套存在语法错误,完全没有读取遍历对象e的实际属性值。
修复步骤
- 修改模型类构造函数,给所有参数添加
this.前缀,让传入参数直接绑定到类成员:
@JsonSerializable() class DataBaseModel { String? word; String? explain; List<Phonetics>? phonetics; List<Meanings>? meanings; String? uid; String? path; Configs? configs; String? phonetic; DataBaseModel({ this.word, this.explain, this.phonetics, this.meanings, this.uid, this.path, this.configs, this.phonetic, }); factory DataBaseModel.fromJson(Map<String, dynamic> json) => _$DataBaseModelFromJson(json); Map<String, dynamic> toJson() => _$DataBaseModelToJson(this); }
- 修正遍历逻辑,去掉属性值外层多余的双引号,正确引用遍历对象的属性,修正空值判断语法:
final vocabs = dbclient.bularyBox.values .toList() .map((e) => DataBaseModel( uid: e.uid ?? "", word: e.word, path: e.path, explain: e.explain, phonetic: e.phonetic, // 需要赋值phonetics、meanings、configs字段时,补充对应e的属性引用即可 )) .toList(); final newjson = vocabs.map((e) => e.toJson()).toList();
补充:如果
dbclient.bularyBox.values存储的本身就是DataBaseModel类型的对象,不需要手动逐字段传参重建实例,直接调用现有实例的toJson()方法即可完成序列化,减少冗余代码。
内容的提问来源于stack exchange,提问作者Cyrus the Great
相关产品推荐
相关产品推荐

