代码之家  ›  专栏  ›  技术社区  ›  Cyrus the Great

颤振:列表上的贴图方法无效

  •  0
  • Cyrus the Great  · 技术社区  · 2 年前

    我创建了一个模型类 json_serializer :

    @JsonSerializable()
    class DataBaseModel {
      String? word;
      String? explain;
      List<Phonetics>? phonetics;
      List<Meanings>? meanings;
      String? uid;
      String? path;
      Configs? configs;
      String? phonetic;
      DataBaseModel({
        String? word,
        String? explain,
        List<Phonetics>? phonetics,
        List<Meanings>? meanings,
        String? uid,
        String? path,
        Configs? configs,
        String? phonetic,
      });
    
      factory DataBaseModel.fromJson(Map<String, dynamic> json) =>
          _$DataBaseModelFromJson(json);
    
      Map<String, dynamic> toJson() => _$DataBaseModelToJson(this);
    }
    

    现在我想创建一个实例作为此类,因此在我的一个列表上,我使用Map方法返回此类的列表:

    final vocabs = dbclient.bularyBox.values
        .toList()
        .map((e) => DataBaseModel(
              uid: "e.uid ?? " "",
              word: "e.word",
              path: "e.path",
              explain: "e.explain",
              phonetic: "e.phonetic",
         
            ))
        .toList();
    
    final newjson = vocabs.map((e) => e.toJson()).toList();
    

    但是 vocabs 属性为 null ?

    enter image description here

    1 回复  |  直到 2 年前
        1
  •  2
  •   mmcdon20    2 年前

    问题是,您从未在模型类的构造函数中指定属性:

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