问题
The data from the cloud_firestore database is in the form of JSON. However, how to transform the data from JSON in a List of Map? The dummy data in my firestore
回答1:
Data to List of Map:
final CollectionReference ref = Firestore.instance.collection('food');
List<Map<String, dynamic>> listOfMaps = [];
await ref.getDocuments().then((QuerySnapshot snapshot) {
listOfMaps =
snapshot.documents.map((DocumentSnapshot documentSnapshot) {
return documentSnapshot.data;
}).toList();
});
print(listOfMaps);
Just in case if You want to use better way. Parse data to List of Objects:
1) create a model class:
class Food {
String affordability;
String title;
Food.fromJson(Map<String, dynamic> jsonData) {
this.affordability = jsonData['affordability'];
this.title = jsonData['title'];
}
}
2) convert to list of Food:
final CollectionReference ref = Firestore.instance.collection('food');
List<Food> list = [];
await ref.getDocuments().then((QuerySnapshot snapshot) {
list = snapshot.documents.map((DocumentSnapshot documentSnapshot) {
return Food.fromJson(documentSnapshot.data);
}).toList();
});
print(list);
来源:https://stackoverflow.com/questions/59042915/how-to-transform-the-data-received-from-cloud-firestore-into-a-map