Search code examples
flutterwidgetstream-builderflutter-android

How to fix null check operator on a null value in StreamBuilder


I'm facing an Null check operator used on a null value issue when trying to fetch data from FireStore Database using StreamBuilder. I can't find any extra null check operator in the whole code. Please check the code.

Below is the output trace

======== Exception caught by widgets library =======================================================
The following _CastError was thrown building StreamBuilder<QuerySnapshot<Object?>>(dirty, dependencies: [MediaQuery], state: _StreamBuilderBaseState<QuerySnapshot<Object?>, AsyncSnapshot<QuerySnapshot<Object?>>>#9d300):
Null check operator used on a null value

The relevant error-causing widget was: 
  StreamBuilder<QuerySnapshot<Object?>> StreamBuilder:file:///Users/milansmac/Desktop/chaudhary_chicken_users_app/lib/widgets/category_widget.dart:20:14
When the exception was thrown, this was the stack: 
#0      _CategoryWidgetState.build.<anonymous closure> (package:chaudhary_chicken_users_app/widgets/category_widget.dart:53:49)
#1      StreamBuilder.build (package:flutter/src/widgets/async.dart:444:81)
#2      _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:124:48)
#3      StatefulElement.build (package:flutter/src/widgets/framework.dart:4992:27)
#4      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4878:15)
#5      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:5050:11)
#6      Element.rebuild (package:flutter/src/widgets/framework.dart:4604:5)
#7      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4859:5)
#8      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:5041:11)
#9      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4853:5)
...     Normal element mounting (12 frames)
#21     Element.inflateWidget (package:flutter/src/widgets/framework.dart:3863:16)
#22     MultiChildRenderObjectElement.inflateWidget (package:flutter/src/widgets/framework.dart:6435:36)
====================================================================================================

Below is my code

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

  @override
  State<CategoryWidget> createState() => _CategoryWidgetState();
}

class _CategoryWidgetState extends State<CategoryWidget> {
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance
            .collection("sellers")
            .doc("5wzmKHapUiMGAtQHozRAsqYCZDk2")
            .collection("menus")
            .snapshots(),
        builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
          if (snapshot.hasError) {
            return Center(child: circularProgress(),);
          } else {
            return SizedBox(
              height: 170,
              width: MediaQuery.of(context).size.width,
              child: Column(
                children: [
                  Row(
                    children: const [
                      Text('Categories', style: TextStyle(
                          color: Colors.black,
                          fontWeight: FontWeight.bold,
                          fontSize: 24
                        ),
                      ),
                    ],
                  ),
                  Expanded(
                    child: InkWell(
                      onTap: (){

                      },
                      splashColor: const Color(0xfffb9e5a),
                      child: ListView.builder(
                        scrollDirection: Axis.horizontal,
                        itemCount: snapshot.data!.docs.length,
                        itemBuilder: (BuildContext context, int index) {

                          Menus model = Menus.fromJson(snapshot.data!.docs[index].data()! as Map<String, dynamic>,);

                          return CategoriesDesign(
                            model: model,
                            context: context,
                          );
                          },
                      ),
                    ),
                  ),
                ],
              ),
            );
          }
          },
      ),
    );
  }
}

This widget is used as a reference which will be used in another screen to show the categories.


Solution

  • You have to check 3 condition

      if (snapshot.hasError) {
                return Container(child:Text("error"),);
              }  
       else if(snapshot.hasData){
                     
     return 
                       .....
                         your widget listview
                         .....
    
    
                }  else{
                return Center(child: circularProgress(),);
    
                }