AzSumToshko
AzSumToshko

Reputation: 9

Flutter: getting Null check operator used on a null value error after navigating from widget to widget with BottomNavigationBar

I am currently building Flutter mobile shop application. I just did the home page where i store 4 pages in a list and call them depending on which bottom navigation bar item i chose. When i start the application all the widgets and stuff work fine, but when i go to another page from the bottom navigation bar and go back to the MainPage i get the null check operator used on a null value error and i dont know why. Just to note i am using GetX for state managment and firebase for database.

Here is the expanded error :

======== Exception caught by widgets library 
=======================================================
The following _CastError was thrown building PageBody(state: _PageBodyState#e8ed4):
Null check operator used on a null value

The relevant error-causing widget was: 
 PageBody 

PageBody:file:///C:/Users/s_dob/StudioProjects/
auto_point_mobile/lib/pages/home/main_page.dart:62:20

When the exception was thrown, this was the stack: 
#0      GetBuilderState.initState 
(package:get/get_state_manager/src/simple/get_state.dart:134:40)
#1      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:5101:55)
#2      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4944:5)
#3      Element.inflateWidget (package:flutter/src/widgets/framework.dart:3953:16)
#4      Element.updateChild (package:flutter/src/widgets/framework.dart:3676:20)
#5      ComponentElement.performRebuild 
(package:flutter/src/widgets/framework.dart:4993:16)
#6      StatefulElement.performRebuild 
(package:flutter/src/widgets/framework.dart:5133:11)
#7      Element.rebuild (package:flutter/src/widgets/framework.dart:4690:5)
#8      BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2743:19)
#9      WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:863:21)
#10     RendererBinding._handlePersistentFrameCallback 
(package:flutter/src/rendering/binding.dart:381:5)
#11     SchedulerBinding._invokeFrameCallback 
(package:flutter/src/scheduler/binding.dart:1289:15)
#12     SchedulerBinding.handleDrawFrame 
(package:flutter/src/scheduler/binding.dart:1218:9)
#13     SchedulerBinding._handleDrawFrame 
(package:flutter/src/scheduler/binding.dart:1076:5)
#14     _invoke (dart:ui/hooks.dart:145:13)
#15     PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:338:5)
#16     _drawFrame (dart:ui/hooks.dart:112:31)
========================================
============================================================

Line 62 in the MainPage widget is child: PageBody()

Here is the MainPage widget :

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

  @override
  State<MainPage> createState() => _State();
}

class _State extends State<MainPage> {
  @override
  Widget build(BuildContext context) {



return Scaffold(
  body: Column(
    children: [
      //header
      Container(
        child: Container(
          margin: EdgeInsets.only(top: Dimensions.height30,bottom: Dimensions.height15),
          padding: EdgeInsets.only(left: Dimensions.width20,right: Dimensions.width20),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                children: [
                  BigText(text: "AutoPoint", color: AppColors.mainColor,size: 30),
                  Row(
                    children: [
                      SmallText(text: "AutoPoint", color: Colors.black),
                      const Icon(Icons.arrow_drop_down_rounded),
                    ],
                  )

                ],
              ),
              Center(
                child: Container(
                  width: Dimensions.width45,
                  height: Dimensions.height45,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(Dimensions.radius15),
                    color: Colors.orange,
                  ),
                  child: Icon(Icons.search, color:Colors.white,size: Dimensions.icon24),
                ),
              )
            ],
          ),
        ),
      ),
      //body
      Expanded(child: SingleChildScrollView(
        child: PageBody(),
      )),
    ],
  ),
);
  }
}

and this is the PageBody :

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

@override
State<PageBody> createState() => _PageBodyState();
}

class _PageBodyState extends State<PageBody> {

PageController pageController = PageController(viewportFraction: 0.85);
var _currentPageValue = 0.0;
double _scaleFactor = 0.8;
double _height = Dimensions.pageViewContainer;
late final directory;

Future<void> _initAppDir() async {
  directory = await getApplicationDocumentsDirectory();
  setState(() {});
}

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

  _initAppDir();

 pageController.addListener(() {
  setState(() {
    _currentPageValue = pageController.page ?? _currentPageValue;
  });
});
  }

  @override
  void dispose(){
  pageController.dispose();
  super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ProductController>(builder: (products){
     return products.isLoaded ? Column(
     children: [
      //slider
      Container(
        height: Dimensions.pageView,
        child: PageView.builder(
            controller: pageController,
            itemCount: products.productList.length >= 7 ? 7 : products.productList.length,
            itemBuilder: (context, position){

              return _buildPageItem(position, products.productList[position]);
            }),
      ),

      //dots
      DotsIndicator(
        dotsCount: products.productList.length <= 0 ? 1 : products.productList.length >= 7 ? 7 : products.productList.length,
        position: _currentPageValue,
        decorator: DotsDecorator(
          activeColor: AppColors.mainColor,
          size: const Size.square(9.0),
          activeSize: const Size(18.0, 9.0),
          activeShape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
        ),
      ),

      //populat text
      SizedBox(height: Dimensions.height30,),
      Container(
        margin: EdgeInsets.only(left: Dimensions.width30),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            BigText(text: "All"),
            SizedBox(width: Dimensions.width20,),
            Container(
              margin: const EdgeInsets.only(bottom: 3),
              child:  BigText(text: ".",color: Colors.black26,),
            ),
            SizedBox(width: Dimensions.width20,),
            Container(
              child: SmallText(text: "products",),
            ),
          ],
        ),
      ),
      //list of food and images
      ListView.builder(
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          itemCount: products.productList.length,
          itemBuilder: (context, index){
            return GestureDetector(
              onTap: (){
                Get.toNamed(RouteHelper.getRecommended(index, directory.path, "main"));
              },
              child: Container(
                margin: EdgeInsets.only(left: Dimensions.width20, right: Dimensions.width20, bottom: Dimensions.height10),
                child: Row(
                  children: [
                    //image section
                    Container(
                      width: Dimensions.listViewImgSize,
                      height: Dimensions.listViewImgSize,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(Dimensions.radius20),
                          color: AppColors.mainColor,
                          image: DecorationImage(
                            image: FileImage(File(directory.path+ "/image/" + products.productList[index].product.id + '.png')),
                            fit: BoxFit.cover,
                          ),
                      ),
                    ),
                    //text container
                    Expanded(
                      child: Container(
                        height: Dimensions.listViewTextContSize,
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.only(
                            topRight: Radius.circular(Dimensions.radius20),
                            bottomRight: Radius.circular(Dimensions.radius20),
                          ),
                          color: Colors.white,
                        ),
                        child: Padding(
                          padding: EdgeInsets.only(left: Dimensions.width10, right: Dimensions.width10),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              BigText(text: products.productList[index].product.name),
                              SizedBox(height: Dimensions.height10,),
                              Center(child: SmallText(text: "цена: ${products.productList[index].product.price}BGN.")),
                              SizedBox(height: Dimensions.height10,),
                              Row(
                                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                  children: [
                                    IconAndTextWidget(icon: Icons.card_membership_outlined,
                                        text: products.productList[index].product.typeOfProduct,
                                        iconColor: AppColors.mainColor),
                                    SizedBox(width: Dimensions.width3,),
                                    IconAndTextWidget(icon: Icons.inventory,
                                        text: "In Stock",
                                        iconColor: AppColors.mainColor),
                                  ]
                              ),
                            ],
                          ),
                        ),
                      ),

                    ),
                  ],
                ),
              ),
            );
          }),
    ],
  ): Column(
    children: [

      SizedBox(
        width: Dimensions.width45 * 6.3,
        height: Dimensions.height45 * 6.3,
      ),

      //The loading animation
      SizedBox(
        width: Dimensions.width45 * 2,
        height: Dimensions.height45 * 2,
        child: CircularProgressIndicator(
          color: AppColors.mainColor,
        ),
      )
    ],
  );
});
  }

Widget _buildPageItem(int index, ProductModel product){
Matrix4 matrix = new Matrix4.identity();
if(index == _currentPageValue.floor()){
  var currScale = 1 - (_currentPageValue - index) * (1 - _scaleFactor);
  var currTrans = _height * (1 - currScale) /2;
  matrix = Matrix4.diagonal3Values(1, currScale ,1);
  matrix = Matrix4.diagonal3Values(1, currScale ,1)..setTranslationRaw(0, currTrans, 0);

}else if(index == _currentPageValue.floor() + 1){
  var currScale = _scaleFactor + (_currentPageValue-index+1) * (1 - _scaleFactor);
  var currTrans = _height * (1 - currScale) /2;
  matrix = Matrix4.diagonal3Values(1, currScale ,1);
  matrix = Matrix4.diagonal3Values(1, currScale ,1)..setTranslationRaw(0, currTrans, 0);

}else if(index == _currentPageValue.floor() - 1){
  var currScale = 1 - (_currentPageValue - index) * (1 - _scaleFactor);
  var currTrans = _height * (1 - currScale) /2;
  matrix = Matrix4.diagonal3Values(1, currScale ,1);
  matrix = Matrix4.diagonal3Values(1, currScale ,1)..setTranslationRaw(0, currTrans, 0);

}else{
  var currScale = 0.8;
  matrix = Matrix4.diagonal3Values(1, currScale ,1)..setTranslationRaw(0, _height * (1 - _scaleFactor)/2, 1);
}

return Transform(
  transform: matrix,
  child: Stack(
    children: [

      GestureDetector(
        onTap: (){
          Get.toNamed(RouteHelper.getDetails(index, directory.path, "main"));
        },
        child: Container(
          height: _height,
          margin: EdgeInsets.only(left: Dimensions.width5, right: Dimensions.width5),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(Dimensions.radius20),
            color: AppColors.mainColor,
            image: DecorationImage(
                image: FileImage(File(directory.path+ "/image/" + product.product.id + '.png')),
                fit: BoxFit.cover,
            ),
          ),
        ),
      ),

      Align(
        alignment: Alignment.bottomCenter,
        child: Container(
          height: Dimensions.pageViewTextContainer,
          margin: EdgeInsets.only(left: Dimensions.width25, right: Dimensions.width25, bottom: Dimensions.height30),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(Dimensions.radius30),
            color: Colors.white,
            boxShadow: [
              BoxShadow(
                color: Color(0xFFe8e8e8),
                blurRadius: 5.0,
                offset: Offset(0, 5),
              ),
              BoxShadow(
                color: Colors.white,
                offset: Offset(-5, 0),
              ),
              BoxShadow(
                color: Colors.white,
                offset: Offset(5, 0),
              ),
            ]

          ),
          child: Container(
            padding: EdgeInsets.only(top: Dimensions.height15,left: Dimensions.width15,right: Dimensions.width15),
            child: AppColumn(productModel: product),
          ),
        ),
      ),
    ],
  ),
);
}
}

Upvotes: 0

Views: 390

Answers (1)

AzSumToshko
AzSumToshko

Reputation: 9

So i fixed it. The thing was that in the GetBuilder of the PageBody when i do another initialization i had to put init:Get.find() and now it works perfectly.

Upvotes: 0

Related Questions