简体   繁体   中英

Error calling a widget from one Screen while no erro calling the same widget from another

Getting the following error:

The method '[]' was called on null.
Receiver: null
Tried calling: []("uid")

The relevant error-causing widget was:    Container file:///C:/Users/dkasa/Downloads/MICS%20Download/grocery_app/lib/screens/homeScreen.dart:28:14 When the exception was thrown, this was the stack: 
#0      Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1      _VendorCategoriesState.didChangeDependencies (package:grocery_app/widgets/categories_widget.dart:29:88)
#2      StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4653:11)
#3      ComponentElement.mount (package:flutter/src/widgets/framework.dart:4469:5)

The widget below, categories_widget.dart, works when called from vendor_home_screen but gets the error when called from HomeScreen. I am not seeing a difference between the vendor_screen and the HomeScreen as to why the error appears.

categories_widget

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:grocery_app/providers/store_provider.dart';
import 'package:grocery_app/services/product_services.dart';
import 'package:persistent_bottom_nav_bar/persistent-tab-view.dart';
import 'package:grocery_app/screens/product_list_screen.dart';
import 'package:provider/provider.dart';


class VendorCategories extends StatefulWidget {
  @override
  _VendorCategoriesState createState() => _VendorCategoriesState();
}

class _VendorCategoriesState extends State<VendorCategories> {

  ProductServices _services = ProductServices();

  List _catList = [];

  @override
  void didChangeDependencies() {
    var _store = Provider.of<StoreProvider>(context);



    FirebaseFirestore.instance
        .collection('products').where('seller.sellerUid',isEqualTo: _store.storedetails['uid'])
        .get()
        .then((QuerySnapshot querySnapshot) => {
    querySnapshot.docs.forEach((doc) {
      //add all this in a list
      setState(() {
        _catList.add(doc['category']['mainCategory']);
      });
    }),
    });

    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {

    var _storeProvider = Provider.of<StoreProvider>(context);


    return FutureBuilder(

        future: _services.category.get(),
        builder: (BuildContext context,AsyncSnapshot<QuerySnapshot>snapshot){
          if(snapshot.hasError){
            return Center(child: Text('Something went wrong..'));
          }
          if(_catList.length==0){
            return Center(child: CircularProgressIndicator(),);
          }
          if(!snapshot.hasData){
            return Container();
          }
          return SingleChildScrollView(
            child: Column(
              children: [
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Material(
                    elevation: 4,
                    borderRadius: BorderRadius.circular(6),
                    child: Container(
                      height: 60,
                      width: MediaQuery.of(context).size.width,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(6),
                        image: DecorationImage(
                          fit: BoxFit.cover,
                          image: AssetImage('images/background.JPG')
                        )
                      ),
                      child: Center(
                        child: Text('Shop by Category',style: TextStyle(
                          shadows: <Shadow>[
                            Shadow(
                              offset: Offset(2.0,2.0),
                              blurRadius: 3.0,
                              color: Colors.black
                            )
                          ],
                          color: Colors.white,
                          fontWeight: FontWeight.bold,
                          fontSize: 30
                        ),),
                      ),
                    ),
                  ),
                ),
                Wrap(
                  direction: Axis.horizontal,
                  children: snapshot.data.docs.map((DocumentSnapshot document){
                    return _catList.contains(document.data()['name']) ? //only if _catlList contain the category name from selected vendor
                        InkWell(
                          onTap: (){
                            _storeProvider.selectedCategory(document.data()['name']);
                            _storeProvider.selectedCategorySub(null);
                            pushNewScreenWithRouteSettings(
                              context,
                              settings: RouteSettings(name: ProductListScreen.id),
                              screen: ProductListScreen(),
                              withNavBar: true,
                              pageTransitionAnimation: PageTransitionAnimation.cupertino,
                            );
                          },
                          child: Container(
                            width: 120,height: 150,
                            child: Container(
                              decoration: BoxDecoration(
                                color: Colors.white,
                                border: Border.all(
                                  color: Colors.grey,
                                  width: .5
                                )
                              ),
                              child: Column(
                                children: [
                                  Center(
                                    child: Image.network(document.data()['image']),
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.only(left: 8,right: 8),
                                    child: Text(document.data()['name'],textAlign: TextAlign.center,),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ) : Text('');
                  }).toList(),
                ),
              ],
            ),
          );
        });
  }
}

vendor_home_screen

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:grocery_app/widgets/categories_widget.dart';
import 'package:grocery_app/widgets/vendor_appbar.dart';
import 'package:grocery_app/widgets/vendor_banner.dart';
import 'package:grocery_app/widgets/products/featured_products.dart';
import 'package:grocery_app/widgets/products/best_selling_product.dart';
import 'package:grocery_app/widgets/products/recently_added_products.dart';

class VendorHomeScreen extends StatelessWidget {
  static const String id = 'vendor-screen';


  @override
  Widget build(BuildContext context) {

    return Scaffold(
      body: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return [
            VendorAppBar(),
          ];
        },
        body: ListView(
          physics: NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          children: [
            VendorBanner(),
            VendorCategories(),
            //Recently Added Products
            //Best Selling Products
            //Featured Products
            RecentlyAddedProducts(),
            FeaturedProducts(),
            BestSellingProduct()
          ],
        ),
      ),
    );
  }
}

HomeScreen

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:grocery_app/providers/store_provider.dart';
import 'package:grocery_app/widgets/categories_widget.dart';
import 'package:grocery_app/widgets/image_slider.dart';
import 'package:grocery_app/widgets/my_appbar.dart';
import 'package:grocery_app/widgets/near_by_store.dart';
import 'package:grocery_app/widgets/top_pick_scree.dart';
import 'package:provider/provider.dart';


class HomeScreen extends StatelessWidget {
  static const String id = 'home-screen';

  @override
  Widget build(BuildContext context) {

    Provider.of<StoreProvider>(context,listen:false);
    return Scaffold(
      backgroundColor: Colors.grey[200],
      body: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled){
          return [
            MyAppBar()
          ];
        },
        body: ListView(
          shrinkWrap: true,
          padding: EdgeInsets.only(top: 0.0),
          children: [
            ImageSlider(),
            Container(
              color: Colors.white,
              child: VendorCategories(),
            ),
            Container(
              color: Colors.white,
              child: TopPickStore(),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 6),
              child: NearByStores(),
            ),
          ],
        ),
      ),
    );
  }
}

As the Home has already a list, So when adding another list that comes a problem:

     body: ListView(
              ShrinkWrap: true,
              padding: EdgeInsets.only(top: 0.0),
              children: [
                ImageSlider(),
                Container(
                  color: Colors.white,
                  child: VendorCategories(),
                ),

add sinkWrap:true in your Home Page then Try again hope this will solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM