4

i am trying to get from the table Products, the specific products that the P_ID is added to cart now the code beneath work well but only retrieve one element

final Stream<QuerySnapshot> cart = FirebaseFirestore.instance
        .collection('products')
        .where('pid', isEqualTo: cartitems[0])
        .snapshots();

however it doesn't work when I do it like this

Stream<QuerySnapshot>? cart;
for (var i = 0; i < cartitems.length; i++) {
  cart = FirebaseFirestore.instance
      .collection('products')
      .where('pid', isEqualTo: cartitems[i])
      .snapshots();
}

it gives me this error

The following StateError was thrown building StreamBuilder<QuerySnapshot<Object?>>(dirty, state: _StreamBuilderBaseState<QuerySnapshot<Object?>, AsyncSnapshot<QuerySnapshot<Object?>>>#9ea5d): Bad state: Snapshot has neither data nor error

The relevant error-causing widget was: StreamBuilder<QuerySnapshot<Object?>> StreamBuilder

1 Answers1

2

You can try using a Stream Builder instead to achieve the same effect without a for loop. Stream Builder will automatically take out all of the cart items you have stored in firebase. To get rid of the snapshot error, implement the if statements below.

final CollectionReference cart = FirebaseFirestore.instance.collection('products');
child: StreamBuilder(
        stream: cart
            .where('pid', isEqualTo: cartitems)
            .snapshots();
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { 
        if (!snapshot.hasData) {
            return const Text('Loading...');
        } 
        if (snapshot.hasError) {
            return const Text('Something went wrong.');
        }
adamcapjones
  • 185
  • 1
  • 17