Lan Au
Lan Au

Reputation: 31

How to transform the data received from cloud_firestore into a Map

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

Upvotes: 1

Views: 77

Answers (1)

Viktor K.
Viktor K.

Reputation: 393

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

Upvotes: 1

Related Questions