Flutter Json Encode List
Add on class:
Map<String,dynamic> toJson(){
return {
"name": this.name,
"imagePath": this.imagePath,
"totalGames": this.totalGames,
"points": this.points
};
}
and call
String json = jsonEncode(players.map((i) => i.toJson()).toList()).toString();
List jsonList = players.map((player) => player.toJson()).toList();
print("jsonList: ${jsonList}");
Add toJson
method to your Player
class:
Map<String, dynamic> toJson(){
return {
"name": this.name,
"imagePath": this.imagePath,
"totalGames": this.totalGames,
"points": this.points
};
}
Then you can call jsonEncode
on the list of players:
String encoded = jsonEncode(players) // this will automatically call toJson on each player