Flutter - Sembast Database insert List of Objects Flutter - Sembast Database insert List of Objects dart dart

Flutter - Sembast Database insert List of Objects


As pointed at, Instance of 'Leaves' is not a valid type so each Leave must be converted as well. Hard to guess what you are doing without seeing your toJson() but something like this should work (could be largely optimized):

class Fruit {  final String id;  final String name;  final bool isSweet;  final List<Leaves> leaves;  Fruit({this.id, this.name, this.isSweet, this.leaves});  Map<String, dynamic> toJson() => <String, dynamic>{        'id': id,        'name': name,        'isSweet': isSweet,        'leaves': leaves?.map((leave) => leave.toJson())?.toList(growable: false)      };}class Leaves {  final String id;  final String name;  Leaves({this.id, this.name});  Map<String, dynamic> toJson() => <String, dynamic>{'id': id, 'name': name};}

and your json should look like something this this:

{  "id": "1",  "name": "Apple",  "isSweet": true,  "leaves": [    {      "id": "1",      "name": "leaveOne"    },    {      "id": "2",      "name": "leaveTwo"    },    {      "id": "3",      "name": "leaveThree"    }  ]}


Here is an example in addition to @alextk answer with converting to and from without any code generation or library's.

class Fruit {  final String id;  final String name;  final bool isSweet;  final List<Leaves> leaves;  Fruit({this.id, this.name, this.isSweet, this.leaves});  Map<String, dynamic> toMap() {    return {      'id': id,      'name': name,      'isSweet': isSweet,      'leaves': leaves.map((leave) => leave.toMap()).toList(growable: false)    };  }  static Fruit fromMap(Map<String, dynamic> map) {    return Fruit(      id: map['id'],      name: map['name'],      isSweet: map['isSweet'],      leaves: map['leaves'].map((mapping) => Leaves.fromMap(mapping)).toList().cast<Leaves>(),    );  }}class Leaves {  final String id;  final String name;  Leaves({this.id, this.name});  Map<String, dynamic> toMap() {    return {      'id': id,      'name': name,    };  }  static Leaves fromMap(Map<String, dynamic> map) {    return Leaves(      id: map['id'],      name: map['name'],    );  }}