Bad state snapshot has neither data nor error

Issue i am trying to get from the table Products, the specific products that the P_ID is added to cart...

Issue

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

Solution

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.');
        }

Answered By – adamcapjones

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Question:

I’m adding data from Firestore to a Stream from StreamBuilder, but I’m getting the following error:

Exception has occurred. StateError (Bad state: Snapshot has neither data nor error

My code.

class Home extends StatefulWidget {
  const Home({Key? key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  AppState? estado;

  static String? userID = FirebaseAuth.instance.currentUser?.uid;
  static final userColeccion = FirebaseFirestore.instance.collection("users");

  var groupfav = ' ';
  Stream<QuerySnapshot>? taskGroup;

  @override
  void initState() {
    super.initState();
    getGroupFavData();
  }

  void getGroupFavData() async {
    var groupFavData = await userColeccion.doc("$userID").get();
    var groupfav = groupFavData.data()!['groupfav'];

    taskGroup = FirebaseFirestore.instance
        .collection("groups")
        .doc(groupfav) // pass the obtained value
        .collection("task")
        .snapshots();
  }

  @override
  Widget build(BuildContext context) {
    estado = Provider.of<AppState>(context, listen: true);
    return Scaffold(
      appBar: AppBar(
        title: const Text("Home"),
        automaticallyImplyLeading: false,
      ),
      body: StreamBuilder(
        stream: taskGroup,
        builder: (
          BuildContext context,
          AsyncSnapshot<QuerySnapshot> snapshot,
        ) {
          if (snapshot.hasError) {
            return const Text("error");
          }
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Text("Loading");
          }
          var data = snapshot.requireData;

          return ListView.builder(
            itemCount: data.size,
            itemBuilder: (context, index) {
              return Card(
                child: ListTile(
                  title: Text("${data.docs[index]['titulo']}"),
                  subtitle: Text("${data.docs[index]['contenido']}"),
                  onTap: () {},
                  trailing: IconButton(
                    icon: const Icon(Icons.delete),
                    color: Colors.red[200],
                    onPressed: () {},
                  ),
                ),
              );
            },
          );
        },
      ),
    );
  }
}

Answer:

Ok, looking at your issue, I see that 1) you need to get the data of the document BEFORE you start listening on that document, which is normal, so you want to do a call first to the collection, get the document, then listen on the document’s collection called task, which makes sense. Your issue is still an asynchronous issue. The app is rebuilding on a stream that still hasn’t arrived; you have to fix the sequence of things.

You then need to switch things up a bit and do the following:

Option #1:
a) Use a FutureBuilder: this will allow you to make the async call to get the document name based on the user Id
b) After you get the document associated to that user, you want to listen on the stream produced by the collection called tasks in that document. There is where then you can hook up the StreamBuilder.

Option #2:
a) Keep things the way you have, but do a listen on the taskGroup snapshots; but keep rebuilding the list as the values arrive on that collection.

Those are my suggestions.

Here’s some brief code on option 1:

// .. in your Scaffold's body:

Scaffold(
 body: FutureBuilder( // the future builder fetches the initial data
   future: userColeccion.doc("$userID").get(),
   builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {

     if (snapshot.hasData) {
       var groupfav = snapshot.data()!['groupfav'];

       // then once the 'groupfav' has arrived, 
       // start listening on the taskGroup

       taskGroup = FirebaseFirestore.instance
        .collection("groups")
        .doc(groupfav) // pass the obtained value
        .collection("task")
        .snapshots();

       return StreamBuilder(
           stream: taskGroup,
           builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
          // the rest of your code

       });
     }

     return CircularProgressIndicator();
   }
)

)

Option 2 would be something like:

List<Task> userTasks = [];

void getGroupFavData() async {
    var groupFavData = await userColeccion.doc("$userID").get();
    var groupfav = groupFavData.data()!['groupfav'];

    taskGroup = FirebaseFirestore.instance
        .collection("groups")
        .doc(groupfav) // pass the obtained value
        .collection("task")
        .snapshots().listen((snapshot) {
          // here populate a list of your tasks
          // and trigger a widget rebuild once you've grabbed the values
          // and display it as a list on the UI

          setState(() {

            userTasks = snapshot.docs.map((d) => Task.fromJson(d.data())).toList();
          });
 
       });
  }

And in your Scaffold, you can have a ListView just rendering the items on that task list, like:

ListView.builder(
  itemCount: userTasks.length,
  itemBuilder: (context, index) {
     // render your tasks here
  })

Here’s a Gist with some working code to illustrate my point. Run it on DartPad and you’ll see how using a FutureBuilder wrapping a StreamBuilder will accomplish what you want.

If you run the above code on DartPad, you’ll get the following output:

enter image description here

Hope those pointers take you somewhere.

If you have better answer, please add a comment about this, thank you!

Hi,
Every time I load the picker I receive the following error:

> I/flutter (19377): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
> I/flutter (19377): The following StateError was thrown building FutureBuilder<Uint8List>(dirty, state:
> I/flutter (19377): _FutureBuilderState<Uint8List>#8dd85):
> I/flutter (19377): Bad state: Snapshot has neither data nor error
> I/flutter (19377): 
> I/flutter (19377): User-created ancestor of the error-causing widget was:
> I/flutter (19377):   ImageItem
> I/flutter (19377):   file:///Users/leonardorignanese/Progetti/Flutter/MyGrandKids/my_grand_kids/photo-0.3.4+1_custom/lib/src/ui/page/photo_main_page.dart:300:13
> I/flutter (19377): 
> I/flutter (19377): When the exception was thrown, this was the stack:
> I/flutter (19377): #0      AsyncSnapshot.data (package:flutter/src/widgets/async.dart:263:5)
> I/flutter (19377): #1      ImageItem.build.<anonymous closure> (package:photo/src/ui/page/main/image_item.dart:33:35)
> I/flutter (19377): #2      _FutureBuilderState.build (package:flutter/src/widgets/async.dart)
> I/flutter (19377): #3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4039:27)
> I/flutter (19377): #4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3933:15)
> I/flutter (19377): #5      Element.rebuild (package:flutter/src/widgets/framework.dart:3730:5)
> I/flutter (19377): #6      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3916:5)
> I/flutter (19377): #7      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4080:11)
> I/flutter (19377): #8      ComponentElement.mount (package:flutter/src/widgets/framework.dart:3911:5)
> I/flutter (19377): #9      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3093:14)
> I/flutter (19377): #10     Element.updateChild (package:flutter/src/widgets/framework.dart:2896:12)
> I/flutter (19377): #11     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3953:16)
> I/flutter (19377): #12     Element.rebuild (package:flutter/src/widgets/framework.dart:3730:5)
> I/flutter (19377): #13     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3916:5)
> I/flutter (19377): #14     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3911:5)
> I/flutter (19377): #15     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3093:14)
> I/flutter (19377): #16     MultiChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5225:32)
> I/flutter (19377): #17     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3093:14)
> I/flutter (19377): #18     Element.updateChild (package:flutter/src/widgets/framework.dart:2896:12)
> I/flutter (19377): #19     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5119:14)
> I/flutter (19377): #20     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3093:14)
> I/flutter (19377): #21     Element.updateChild (package:flutter/src/widgets/framework.dart:2896:12)
> I/flutter (19377): #22     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5119:14)
> I/flutter (19377): #23     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3093:14)
> I/flutter (19377): #24     Element.updateChild (package:flutter/src/widgets/framework.dart:2896:12)
> I/flutter (19377): #25     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3953:16)
> I/flutter (19377): #26     Element.rebuild (package:flutter/src/widgets/framework.dart:3730:5)
> I/flutter (19377): #27     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3916:5)
> I/flutter (19377): #28     StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4080:11)
> I/flutter (19377): #29     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3911:5)
> I/flutter (19377): #30     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3093:14)
> I/flutter (19377): #31     Element.updateChild (package:flutter/src/widgets/framework.dart:2896:12)
> I/flutter (19377): #32     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3953:16)
> I/flutter (19377): #33     Element.rebuild (package:flutter/src/widgets/framework.dart:3730:5)
> I/flutter (19377): #34     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3916:5)
> I/flutter (19377): #35     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3911:5)
> I/flutter (19377): #36     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3093:14)
> I/flutter (19377): #37     Element.updateChild (package:flutter/src/widgets/framework.dart:2896:12)
> I/flutter (19377): #38     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5119:14)
> I/flutter (19377): #39     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3093:14)
> I/flutter (19377): #40     Element.updateChild (package:flutter/src/widgets/framework.dart:2896:12)
> I/flutter (19377): #41     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5119:14)
> I/flutter (19377): #42     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3093:14)
> I/flutter (19377): #43     Element.updateChild (package:flutter/src/widgets/framework.dart:2896:12)
> I/flutter (19377): #44     SingleChildRenderObjectElement.mount (package:flutter/src/widgets/framework.dart:5119:14)
> I/flutter (19377): #45     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3093:14)
> I/flutter (19377): #46     Element.updateChild (package:flutter/src/widgets/framework.dart:2896:12)
> I/flutter (19377): #47     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3953:16)
> I/flutter (19377): #48     Element.rebuild (package:flutter/src/widgets/framework.dart:3730:5)
> I/flutter (19377): #49     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3916:5)
> I/flutter (19377): #50     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3911:5)
> I/flutter (19377): #51     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3093:14)
> I/flutter (19377): #52     Element.updateChild (package:flutter/src/widgets/framework.dart:2896:12)
> I/flutter (19377): #53     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3953:16)
> I/flutter (19377): #54     Element.rebuild (package:flutter/src/widgets/framework.dart:3730:5)
> I/flutter (19377): #55     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3916:5)
> I/flutter (19377): #56     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3911:5)
> I/flutter (19377): #57     ParentDataElement.mount (package:flutter/src/widgets/framework.dart:4306:11)
> I/flutter (19377): #58     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3093:14)
> I/flutter (19377): #59     Element.updateChild (package:flutter/src/widgets/framework.dart:2896:12)
> I/flutter (19377): #60     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3953:16)
> I/flutter (19377): #61     Element.rebuild (package:flutter/src/widgets/framework.dart:3730:5)
> I/flutter (19377): #62     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3916:5)
> I/flutter (19377): #63     StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4080:11)
> I/flutter (19377): #64     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3911:5)
> I/flutter (19377): #65     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3093:14)
> I/flutter (19377): #66     Element.updateChild (package:flutter/src/widgets/framework.dart:2896:12)
> I/flutter (19377): #67     ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3953:16)
> I/flutter (19377): #68     Element.rebuild (package:flutter/src/widgets/framework.dart:3730:5)
> I/flutter (19377): #69     ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3916:5)
> I/flutter (19377): #70     ComponentElement.mount (package:flutter/src/widgets/framework.dart:3911:5)
> I/flutter (19377): #71     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3093:14)
> I/flutter (19377): #72     Element.updateChild (package:flutter/src/widgets/framework.dart:2896:12)
> I/flutter (19377): #73     SliverMultiBoxAdaptorElement.updateChild (package:flutter/src/widgets/sliver.dart:1181:36)
> I/flutter (19377): #74     SliverMultiBoxAdaptorElement.createChild.<anonymous closure> (package:flutter/src/widgets/sliver.dart:1166:20)
> I/flutter (19377): #75     BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2320:19)
> I/flutter (19377): #76     SliverMultiBoxAdaptorElement.createChild (package:flutter/src/widgets/sliver.dart:1159:11)
> I/flutter (19377): #77     RenderSliverMultiBoxAdaptor._createOrObtainChild.<anonymous closure> (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:354:23)
> I/flutter (19377): #78     RenderObject.invokeLayoutCallback.<anonymous closure> (package:flutter/src/rendering/object.dart:1735:58)
> I/flutter (19377): #79     PipelineOwner._enableMutationsToDirtySubtrees (package:flutter/src/rendering/object.dart:814:15)
> I/flutter (19377): #80     RenderObject.invokeLayoutCallback (package:flutter/src/rendering/object.dart:1735:13)
> I/flutter (19377): #81     RenderSliverMultiBoxAdaptor._createOrObtainChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:343:5)
> I/flutter (19377): #82     RenderSliverMultiBoxAdaptor.addInitialChild (package:flutter/src/rendering/sliver_multi_box_adaptor.dart:427:5)
> I/flutter (19377): #83     RenderSliverGrid.performLayout (package:flutter/src/rendering/sliver_grid.dart:543:12)
> I/flutter (19377): #84     RenderObject.layout (package:flutter/src/rendering/object.dart:1639:7)
> I/flutter (19377): #85     RenderSliverPadding.performLayout (package:flutter/src/rendering/sliver_padding.dart:181:11)
> I/flutter (19377): #86     RenderObject.layout (package:flutter/src/rendering/object.dart:1639:7)
> I/flutter (19377): #87     RenderViewportBase.layoutChildSequence (package:flutter/src/rendering/viewport.dart:406:13)
> I/flutter (19377): #88     RenderViewport._attemptLayout (package:flutter/src/rendering/viewport.dart:1334:12)
> I/flutter (19377): #89     RenderViewport.performLayout (package:flutter/src/rendering/viewport.dart:1252:20)
> I/flutter (19377): #90     RenderObject.layout (package:flutter/src/rendering/object.dart:1639:7)
> I/flutter (19377): #91     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
> I/flutter (19377): #92     RenderObject.layout (package:flutter/src/rendering/object.dart:1639:7)
> I/flutter (19377): #93     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
> I/flutter (19377): #94     RenderObject.layout (package:flutter/src/rendering/object.dart:1639:7)
> I/flutter (19377): #95     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
> I/flutter (19377): #96     RenderObject.layout (package:flutter/src/rendering/object.dart:1639:7)
> I/flutter (19377): #97     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
> I/flutter (19377): #98     RenderObject.layout (package:flutter/src/rendering/object.dart:1639:7)
> I/flutter (19377): #99     _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
> I/flutter (19377): #100    RenderObject.layout (package:flutter/src/rendering/object.dart:1639:7)
> I/flutter (19377): #101    _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
> I/flutter (19377): #102    RenderObject.layout (package:flutter/src/rendering/object.dart:1639:7)
> I/flutter (19377): #103    _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
> I/flutter (19377): #104    RenderObject.layout (package:flutter/src/rendering/object.dart:1639:7)
> I/flutter (19377): #105    _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
> I/flutter (19377): #106    RenderObject.layout (package:flutter/src/rendering/object.dart:1639:7)
> I/flutter (19377): #107    _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
> I/flutter (19377): #108    RenderObject.layout (package:flutter/src/rendering/object.dart:1639:7)
> I/flutter (19377): #109    _RenderProxyBox&RenderBox&RenderObjectWithChildMixin&RenderProxyBoxMixin.performLayout (package:flutter/src/rendering/proxy_box.dart:105:13)
> I/flutter (19377): #110    RenderObject.layout (package:flutter/src/rendering/object.dart:1639:7)
> I/flutter (19377): #111    MultiChildLayoutDelegate.layoutChild (package:flutter/src/rendering/custom_layout.dart:142:11)
> I/flutter (19377): #112    _ScaffoldLayout.performLayout (package:flutter/src/material/scaffold.dart:443:7)
> I/flutter (19377): #113    MultiChildLayoutDelegate._callPerformLayout (package:flutter/src/rendering/custom_layout.dart:212:7)
> I/flutter (19377): #114    RenderCustomMultiChildLayoutBox.performLayout (package:flutter/src/rendering/custom_layout.dart:356:14)
> I/flutter (19377): #115    RenderObject._layoutWithoutResize (package:flutter/src/rendering/object.dart:1516:7)
> I/flutter (19377): #116    PipelineOwner.flushLayout (package:flutter/src/rendering/object.dart:783:18)
> I/flutter (19377): #117    _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding.drawFrame (package:flutter/src/rendering/binding.dart:346:19)
> I/flutter (19377): #118    _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:702:13)
> I/flutter (19377): #119    _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:285:5)
> I/flutter (19377): #120    _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1033:15)
> I/flutter (19377): #121    _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:975:9)
> I/flutter (19377): #122    _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:891:5)
> W/ExifInterface(19377): Skip the tag entry since tag number is not defined: 2
> I/flutter (19377): #126    _invoke (dart:ui/hooks.dart:236:10)
> I/flutter (19377): #127    _drawFrame (dart:ui/hooks.dart:194:3)
> I/flutter (19377): (elided 3 frames from package dart:async)
> I/flutter (19377): 
> I/flutter (19377): ════════════════════════════════════════════════════════════════════════════════════════════════════

I’ve fully imported your library inside my project (copying all the files) because I needed to make some customizations in the UI. I don’t think this error is related to my small modifications (just added a translation and a button in the bottombar).

It just in the log and I don’t see any big malfunction apart the fact that if I scroll down fast, the pictures before are red showing an error, but then quickly refresh to show the picture:
IMAGE 2019-07-22 09:56:02

What does this error come from? I can’t really understand it. I checked if the data is null or empty before execute it but I get the anyway so I suppose it is caused by another error inside data.

Thanks

i am trying to get the product ID’s from Cart table, then getting the products from Products table from those ID’s
and its shows me this Error

Bad state: Snapshot has neither data nor error

and this error occured after making «cart» local variable here

Stream<QuerySnapshot>? cart;

=========

class _CartScreenState extends State<CartScreen> { 
final databseRefrence = FirebaseDatabase.instance.reference();
  String? Id;
  final cartitems = [];
  Stream<QuerySnapshot>? cart;

  void initState() {
    getProductsFromCart();
    super.initState();
  }

and the main idea is here

  getProductsFromCart() async {
    try {
      var collectionRef = await databseRefrence.child("Cart").get();
      Map<dynamic, dynamic> values = collectionRef.value;
      values.forEach((key, values) {
        if (values['userId'] == Id) {
          // cartitems.add(values['productId']);
          cart = FirebaseFirestore.instance
              .collection('products')
              .where('pid', isEqualTo: values['productId'])
              .snapshots();
        }
      });
    } catch (e) {
      throw e;
    }
  }

=============

  String SubString(String? s) {
    if (s!.length > 40) {
      return s.substring(0, 40);
    } else {
      return s;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: BMainColor,
        elevation: 0,
        title: Text('Cart'),
        automaticallyImplyLeading: false,
      ),
  body: SingleChildScrollView(
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          height: 800,
          child: StreamBuilder<QuerySnapshot>(
              stream: cart,
              builder: (BuildContext context,
                  AsyncSnapshot<QuerySnapshot> snapshot) {
                if (snapshot.hasError) {
                  return Text('something went wrong');
                }
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Center(
                    child: Text('Loading..',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontSize: 32,
                          fontWeight: FontWeight.bold,
                        )),
                  );
                }
                final data = snapshot.requireData;

                return ListView.builder(
                  itemCount: data.size,
                  itemBuilder: (context, index) {
                    return GestureDetector(
                      onTap: () {},
                      child: Card(
                        child: Row(children: [
                          Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Image.network(data.docs[index]['image'],
                                width:
                                    MediaQuery.of(context).size.width * 0.3,
                                height: MediaQuery.of(context).size.height *
                                    0.15,
                                fit: BoxFit.cover),
                          ),
                          Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Container(
                              width:
                                  MediaQuery.of(context).size.width * 0.57,
                              child: Column(
                                crossAxisAlignment:
                                    CrossAxisAlignment.start,
                                children: [
                                  Text(
                                    data.docs[index]['name'],
                                    style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        fontSize: 20),
                                  ),
                                  SizedBox(
                                    height: 10,
                                  ),
                                  Container(
                                    child: Text(
                                      SubString(data.docs[index]
                                              ['description']) +
                                          "...",
                                    ),
                                  ),
                                  SizedBox(
                                    height: 5,
                                  ),
                                  Text(
                                    data.docs[index]['price'] + " AED",
                                    style: TextStyle(
                                        fontWeight: FontWeight.bold,
                                        fontSize: 16),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ]),
                      ),
                    );
                  },
                );
              }),
        ),
      ],
    ),
  ),
);

}
}

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

Понравилась статья? Поделить с друзьями:
  • Bad request error parsing headers limit request headers fields size
  • Bad request 400 there was a problem with your request роблокс как исправить ошибку
  • Bad ragdoll for error mdl
  • Bad pool caller windows 10 как исправить ошибку
  • Bad object header windows 10 как исправить