Home > Software design >  Null check operator used on a null value in StreamBuilder Widget
Null check operator used on a null value in StreamBuilder Widget

Time:09-14

class HomePage extends StatefulWidget {
  @override
  State<HomePage> createState() => _HomePageState();
}


class _HomePageState extends State<HomePage> {

  Product? menData; 

Widget _buildFeatured(){
    return Column(
      children: [
        StreamBuilder<QuerySnapshot>(
          stream: _firestore.collection('products').doc('46f7G3Zzi0XcwJsIsUwc').collection('featuredproducts').snapshots(),
          builder: (context, snapshot) {

            if(!snapshot.hasData){return Center(child: Text('No Available Data'),);}
              final documents = snapshot.data!.docs;
              menData = Product(image: documents[1]['image'], name: documents[1]['name'], price: documents[1]['price']);
              print(documents[1]['name']);

            return Container(
              height: 50,
              padding: EdgeInsets.symmetric(vertical: 10),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        'Featured',
                        style: TextStyle(
                          fontSize: 17,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (ctx) => ListProduct('Featured'),
                            ),
                          );
                        },
                        child: Text(
                          'View more',
                          style: TextStyle(
                            fontSize: 17,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            );
          }
        ),
        Row(
          children: [
            GestureDetector(
                onTap: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (ctx) => DetailScreen(
                            title: menData!.name,
                            price: menData!.price,
                            image: menData!.image,
                          )));
                },
                child: SingleProduct(menData!.image, menData!.name, menData!.price)),
          ],
        ),
      ],
    );
  }

This code was running well until I started to add extra widgets in the Row above. I don't know what is the issue exactly if it is from the firebase or something else.

======== Exception caught by widgets library =======================================================
The following _CastError was thrown building HomePage(dirty, state: _HomePageState#45e35):
Null check operator used on a null value

The relevant error-causing widget was: 
  HomePage HomePage:file:///C:/Users/Dell/Desktop/Mhmd/ecommerce/lib/main.dart:37:22
When the exception was thrown, this was the stack: 
#0      _HomePageState._buildFeatured (package:ecommerce/screens/homepage.dart:272:45)
#1      _HomePageState.build (package:ecommerce/screens/homepage.dart:441:21)
#2      StatefulElement.build (package:flutter/src/widgets/framework.dart:4992:27)
#3      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4878:15)
#4      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:5050:11)
#5      Element.rebuild (package:flutter/src/widgets/framework.dart:4604:5)
#6      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4859:5)
#7      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:5041:11)

CodePudding user response:

The problem is that menData doesn't exist at the beginning. It's null by default. And using the null check operator ! on it will throw this exception.

To fix it just check if menData is null before the Row(...) like the following:

class HomePage extends StatefulWidget {
  @override
  State<HomePage> createState() => _HomePageState();
}


class _HomePageState extends State<HomePage> {

  Product? menData; 

Widget _buildFeatured(){
    return Column(
      children: [
        StreamBuilder<QuerySnapshot>(
          stream: _firestore.collection('products').doc('46f7G3Zzi0XcwJsIsUwc').collection('featuredproducts').snapshots(),
          builder: (context, snapshot) {

            if(!snapshot.hasData){return Center(child: Text('No Available Data'),);}
              final documents = snapshot.data!.docs;
              menData = Product(image: documents[1]['image'], name: documents[1]['name'], price: documents[1]['price']);
              print(documents[1]['name']);

            return Container(
              height: 50,
              padding: EdgeInsets.symmetric(vertical: 10),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        'Featured',
                        style: TextStyle(
                          fontSize: 17,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                              builder: (ctx) => ListProduct('Featured'),
                            ),
                          );
                        },
                        child: Text(
                          'View more',
                          style: TextStyle(
                            fontSize: 17,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            );
          }
        ),
        if (menData != null)
          Row(
            children: [
              GestureDetector(
                  onTap: () {
                    Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (ctx) => DetailScreen(
                              title: menData!.name,
                              price: menData!.price,
                              image: menData!.image,
                            )));
                  },
                  child: SingleProduct(menData!.image, menData!.name, menData!.price)),
            ],
          ),
      ],
    );
  }

CodePudding user response:

:Write it Like this

builder: (ctx) => DetailScreen(
title: menData!.name!,
price: menData!.price!,
image: menData!.image!,
)));

  • Related