Home > Software design >  How to fetch data from Firebase Firestore and store it in a List to use in flutter Widgets?
How to fetch data from Firebase Firestore and store it in a List to use in flutter Widgets?

Time:12-10

I am working on an app where I need to store and read data from firestore. Currently I am using a list of Maps to generate widgets. My list is

List<Map> subjects = [
  {"name": "WAK", "time": 13.30, "day": 'Mon'},
  {"name": "RAD", "time": 10.30, "day": 'Tue'},
  {"name": "PQR", "time": 15.15, "day": 'Fri'}
];

From the above list I am generating widgets that the app will show using column widget. My flutter screen is as shown here:

enter image description here

Now, I want to achieve same thing, but instead of a predefined list I want to fetch data from firestore. For which I have written the following code:

 FirebaseFirestore.instance
    .collection('classes')
    .get()
    .then((QuerySnapshot querySnapshot) {
  querySnapshot.docs.forEach((doc) {
    print(doc.data());
  });
});

From the above code I get the output in terminal as:

I/flutter ( 5012): {subject: SE, fromTime: 1115, days: [Mon, Wed]}
I/flutter ( 5012): {subject: OSSS, fromTime: 1430, days: [Tue, Wed, Fri]}

As you can see, the structure of each document is almost same as of the map which I defined above, but I could not figure out how to take the data from this and store it in a list of maps so that I could generate the widgets in the same way I generated before. Also, is there any better or efficient way to fetch data from firestore and use it in my widgets.

CodePudding user response:

Use FutureBuilder:

FutureBuilder<QuerySnapshot>(
  future: FirebaseFirestore.instance.collection('classes').get(),
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
    if (snapshot.hasData) {
      return Column(
        children: snapshot.data?.docs?.map((doc) {
          // your widget here(use doc data)
          return YourWidget();
        })?.toList() ?? [],
      );
    } else {
      // or your loading widget here
      return Container();
    }
  },
);

Hope you get the idea :)

  • Related