Prince Singh
Prince Singh

Reputation: 165

How to display the firebase array in the list view in flutter

enter image description here

Future<List<DocumentSnapshot>> getData() async {
    var firestore = Firestore.instance;
    QuerySnapshot qn = await firestore
        .collection("UserTransactions")
        .where("AuthUserId", isEqualTo: userId)
        .getDocuments();
    return qn.documents;
}

Here I am getting all the documents according to the id, I want to display the transactions which is an array in the List View

FutureBuilder(
    future: getData(),
    builder: (_, AsyncSnapshot<List<DocumentSnapshot>> snapshot) {
        return ListView.builder(
            itemCount: snapshot.data.length,
            itemBuilder: (_, index) {
                return Text(snapshot.data[index].data["transactions"][index]["Mode"])
            })
    }
); 

I am getting the error:

The getter 'length' was called on null.
Receiver: null
Tried calling: length

How to display those values and also display nothing if the array is blank?

Upvotes: 0

Views: 1618

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80934

You need to check if data is retrieved all not:

 FutureBuilder(
    future: getData(),
    builder: (_, AsyncSnapshot<List<DocumentSnapshot>> snapshot) {
             if(snapshot.hasData){
             return ListView.builder(
                       itemCount: snapshot.data.length,
                       itemBuilder: (_, index) {
                       return Text(snapshot.data[index].data["transactions"][index]["Mode"])  
                       }
           return CircularProgressIndicator();
        }
  )

Use snapshot.hasData to check if the data is retrieved and CircularProgressIndicator which will display a loading icon until data is fully retrieved.

Upvotes: 1

Related Questions