Home > Software design >  How do I get all the data in a collection in flutter firestore and display it on the screen?
How do I get all the data in a collection in flutter firestore and display it on the screen?

Time:06-12

I wrote the following code

class MyHomePage extends StatelessWidget {
 @override
 Widget build(BuildContext context) {
dynamic books = getData();
return Scaffold(
  body: Column(
    children: <Widget>[
      Text(books.toString()),
    ],
  ),
);
 }
}

getData() async {
QuerySnapshot querySnapshot =
  await FirebaseFirestore.instance.collection('books').get();

return querySnapshot;
}

But the screen shows Instance of 'Future' How can I use the data in the firestore?

CodePudding user response:

This way:

dynamic books = await getData();

Also this will open up other problems, as the build method is not async.

Use a Controller-Model-View Pattern to avoid these: The controller fetches model (data) and the view displays the model.

Or you use a StreamBuilder inside the Widget to show live data from Firebase.

CodePudding user response:

Since the data is loaded from Firestore, it won't be available immediately and in fact your getData function returns a Future<QuerySnapshot>. You'll need to use a FutureBuilder object in the UI to handle the asynchronous nature of the data.

Something like this:

FutureBuilder(
  future: getData(),
  builder: (BuildContext context, snapshot) {
    if (snapshot.hasData) {
      if (snapshot.connectionState == ConnectionState.waiting) {
        return CircularProgressIndicator(),
      }else{
        return ListView(
          children: snapshot.data!.docs
              .map((DocumentSnapshot document) {
                Map<String, dynamic> data = document.data()! as Map<String, dynamic>;
                return Text(data['full_name']), //            
  • Related