Home > OS >  How to make a list view widget out of a firestore array
How to make a list view widget out of a firestore array

Time:02-15

I am trying to display my Cart data from firestore into a listview widget but to do so, I need the 'Cart' array's length.

Firestore Database Structure

How do I build a listview on my app based on the data from the 'Cart' collection?

child: StreamBuilder(
    stream: FirebaseFirestore.instance
        .collection('Users')
        .doc(user.uid)
        .collection('Cart')
        .snapshots(),
    builder: (context, AsyncSnapshot snapshot) {
      if (!snapshot.hasData)
        return Center(child: CircularProgressIndicator());
      else
        return Column(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              ListView.separated(
                  shrinkWrap: true,
                  itemBuilder: (context, index) => Cartproductcard(
                        cartItem: snapshot.data[index],
                      ),
                  separatorBuilder: (context, _) =>
                      SizedBox(width: 12),
                  itemCount: snapshot.data
                      .length() 
              ),

This is what I am am left with so far, when I tried to run it I got the error:

"NoSuchMethodError (NoSuchMethodError: Class '_JsonQuerySnapshot' has no instance method 'length'. Receiver: Instance of '_JsonQuerySnapshot' Tried calling: length())"

CodePudding user response:

As far as I can tell from your screenshots Carts is not a subcollection under the user's document, but an array field inside the user's document.

So this code doesn't find any documents (since the Carts collection doesn't exist):

stream: FirebaseFirestore.instance
    .collection('Users')
    .doc(user.uid)
    .collection('Cart')

You'll instead need to:

  1. Read the FirebaseFirestore.instance.collection('Users').doc(user.uid).snapshots()
  2. Get the Cart array from that document.
  3. Loop over the items in that array.
  4. Construct the widget(s) for each item from the array.
  • Related