Listview builder using with future builder with data from firestore

Issue

I am trying to use FutureBuilder to build some LisTiles with ListView.builder. The data is from Firestore.
It looks like the FutureBuilder dont access the ConnectionState.done, because I have this whole time CircularProgressIndicator() showing.

 var qn;
  Future<QuerySnapshot> getChargingHistory() async {
    await users
        .doc('$currentUser')
        .collection('chargingHistory')
        .get()
        .then((QuerySnapshot querySnapshot) {
      qn = querySnapshot;
      qn.docs.forEach((doc) {
        print(doc['Endzeit']);
      });
    });
    setState(() {

    });
    return qn;
  }
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        appBar: AppBar(
          title: Hero(
            tag: 'logo',
            child: Image.asset(
              'assets/images/rz_bildmarke_meyer-technik_rgb.png',
              height: MediaQuery.of(context).size.height * 0.05,
              fit: BoxFit.cover,
            ),
          ),
          actions: [],
          centerTitle: true,
          elevation: 4,
        ),
        body: BackgroundContainer(
          child: Column(
            children: [
              Expanded(
                child: FutureBuilder(
                    future: getChargingHistory(),
                    builder: (context, querySnapshot) {
                      if (querySnapshot.connectionState ==
                          ConnectionState.done) {
                        return ListView.builder(
                            itemCount: qn.docs.length,
                            itemBuilder: (BuildContext context, index) {
                              return ListTile(
                                  title: Text('${qn.docs.data['Endzeit'].toString()}'));
                              //Text(doc['Endzeit']);
                            }
                        );
                      } else {
                        return Center(
                          child: CircularProgressIndicator(),
                        );
                      }
                    }),
              ),

Solution

First, you are mixing async/await with .then. You don’t need var qn;, simply return the result of await from your getChargingHistory, like:

Future<QuerySnapshot> getChargingHistory() async {
    return await users
        .doc('$currentUser')
        .collection('chargingHistory')
        .get();
  }

Second, you have to use index in itemBuilder to get the data for the current ListTile. Try:

return ListView.builder(
    itemCount: querySnapshot.docs.length,
    itemBuilder: (BuildContext context, index) {
        return ListTile(title:
            Text('${querySnapshot
                .docs[index]['Endzeit'].toString()}'));

Answered By – Peter Koltai

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *