Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use querySnapshot in a listview builder? (flutter)

I’m trying to fetch documents from my firebase DB and use them to create a social media feed. Here I’m trying to get the length of the fetched collection but I cannot manage to call the variable. Any help would be appreciated. Example code

class LoadDataFromFirestore extends StatefulWidget {
  @override
  _LoadDataFromFirestoreState createState() => _LoadDataFromFirestoreState();
}

class _LoadDataFromFirestoreState extends State<LoadDataFromFirestore> {
  @override
  void initState() {
    super.initState();
    CollectionReference _collectionRef =
        FirebaseFirestore.instance.collection('fish');

    Future<void> getData() async {
      // Get docs from collection reference
      QuerySnapshot querySnapshot = await _collectionRef.get();

      // Get data from docs and convert map to List
      final allData = querySnapshot.docs.map((doc) => doc.data()).toList();

      print(allData);
    }
  }

  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView.builder(
        itemCount: querySnapshot.docs.length,
        itemBuilder: (BuildContext context, int index) {
          return _postView();
        },
      ),
    );
  }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

First of all it is not ok to call future function in initstate, you need to use FutureBuilder like this:

class LoadDataFromFirestore extends StatefulWidget {
  @override
  _LoadDataFromFirestoreState createState() => _LoadDataFromFirestoreState();
}

class _LoadDataFromFirestoreState extends State<LoadDataFromFirestore> {
  late CollectionReference _collectionRef;
  @override
  void initState() {
    super.initState();
    _collectionRef = FirebaseFirestore.instance.collection('fish');
  }

  Widget build(BuildContext context) {
    return Scaffold(
      body: FutureBuilder<QuerySnapshot>(
        future: _collectionRef.get(),
        builder: (context, snapshot) {
          switch (snapshot.connectionState) {
            case ConnectionState.waiting:
              return Text('Loading....');
            default:
              if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              } else {
                QuerySnapshot? querySnapshot = snapshot.data;

                return ListView.builder(
                  itemCount: querySnapshot?.docs?.length ?? 0,
                  itemBuilder: (BuildContext context, int index) {
                    var data = querySnapshot?.docs?[index].data();
                    print("data = $data");
                    return _postView();
                  },
                );
              }
          }
        },
      ),
    );
  }
}

inside listview’s builder you can use data to parse your data and use it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading