0
votes

I have a flutter app where a list is generated with ListView.Builder, and where the itemCount is the number of documents in a firestore collection. This works fine until a new document is added. When that happens I get the error (17 and 18 are just examples).

Invalid value: Not in range 0..17, inclusive: 18

I assume I would need to update the state when a new document is created, but I have no idea how i can call setState when that happens

Here is the relevant part of the code:

child: StreamBuilder(
                stream: Firestore.instance.collection('contact').orderBy(sortby, descending: decending).snapshots(),
                builder: (context, snapshot) {
                  if (!snapshot.hasData) return Container();
                  return ListView.builder(
                    itemCount: snapshot.data.documents.length,
                    itemBuilder: (context, index) =>
                        _personer(context, snapshot.data.documents[index], index),
                  );
                },
              ),
2

2 Answers

1
votes

use setState?

 StreamBuilder(builder: (context, snapshot) {
   return snapshot.hasData == null ? Container() : _getListView(snapshot);
 } , )

_getListView(snapshot) {
setState(() {
  return ListView.builder(
    itemCount: snapshot.data.documents.length,
    itemBuilder: (context, index) =>
        _personer(context, snapshot.data.documents[index], index),
  );
});

}

0
votes

StreamBuilder use QuerySnapshot so list data can change

example code :

 StreamBuilder<QuerySnapshot>(
          builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
            if (snapshot.hasError)
              return new Text('Error: ${snapshot.error}');
            switch (snapshot.connectionState) {
              case ConnectionState.waiting: return new Text('Loading...');
              default:
                return new ListView(
                  children: snapshot.data.documents.map((DocumentSnapshot document) {
                    return ;
                  }).toList(),
                );
            }
          },
        )