How to transform the data received from cloud_firestore into a Map

谁说我不能喝 提交于 2020-01-24 19:26:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!