Home > Software engineering >  flutter: Map method on list not works
flutter: Map method on list not works

Time:06-19

I have created a model class with 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);
}

Now I want to make a instance as this class , So on one of my lists I used Map method to return list of this class :

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();

But vocabs properties are null?

enter image description here

CodePudding user response:

The issue is you never assign to the properties within the constructor of your model class:

DataBaseModel({
  String? word,
  String? explain,
  List<Phonetics>? phonetics,
  List<Meanings>? meanings,
  String? uid,
  String? path,
  Configs? configs,
  String? phonetic,
});

should be:

DataBaseModel({
  this.word,
  this.explain,
  this.phonetics,
  this.meanings,
  this.uid,
  this.path,
  this.configs,
  this.phonetic,
});
  • Related