首页 > 解决方案 > 颤振:sharedpreference 检索空值

问题描述

在 null 上调用了方法“getStringList”。Receiver: null 尝试调用:getStringList("userCart") 导致错误的相关小部件是:Consumer。详细信息存储在firebase中,显示用户已添加到购物车的商品数量时发生错误。

CartItemCounter dart 文件是调用消费者时抛出的错误。最初在 firebase 中注册时,useCart 被作为垃圾值给出。

import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
class StoreHome extends StatefulWidget {
  @override
  _StoreHomeState createState() => _StoreHomeState();
}

class _StoreHomeState extends State<StoreHome> {
  SharedPreferences sharedPreferences;
 @override
  void initState() {
    super.initState();
    SharedPreferences.getInstance().then((prefs){
      setState(() {
        sharedPreferences=prefs;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    final _width=MediaQuery.of(context).size.width;
    return SafeArea(
        child: Scaffold(
          appBar: AppBar(
            title: Text("E_shop",style: TextStyle(color:Colors.red,),
            ),
            centerTitle: true,
            actions: [
              Stack(
                children: [
                  IconButton(icon:Icon(Icons.add_shopping_cart,color: Colors.grey,),
                    onPressed: (){
                    Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>StoreHome()));
                    },
                  ),
                  Positioned(child: Stack(
                    children: [
                      Icon(Icons.brightness_1,size: 20.0,
                        color: Colors.green,),


                  Positioned(
                    top: 3.0,
                      bottom: 4.0,
                      left:4.0,
                      child: Consumer<CartItemCounter>(
                          builder: (context, counter,_){
                            return Text(
                              counter.count.toString(),
                              style:TextStyle(color:Colors.white,fontSize:12.0,fontWeight:FontWeight.w500),
                            );
                          },),
                  ),
                ],
              ),
                  ),
            ],
          ),
        ],
    ),
    drawer: MyDrawer(),
    body: CustomScrollView(
    slivers: [
    SliverPersistentHeader(
       pinned: true,
          delegate: SearchBoxDelegate(),
    ),
      StreamBuilder<QuerySnapshot>(
        stream: FirebaseFirestore.instance.collection("items").limit(15).orderBy("publishedDate",descending: true).snapshots(),
        builder: (context,dataSnapshot){
          return !dataSnapshot.hasData
              ?SliverToBoxAdapter(child: Center(child: circularProgress(),),)
              :SliverStaggeredGrid.countBuilder(
              crossAxisCount: 1,
              itemCount: 5,

              staggeredTileBuilder: (c)=>StaggeredTile.fit(1),
              itemBuilder: (context,index){
                ItemModel model=ItemModel.fromJson(dataSnapshot.data.docs[index].data());
                return sourceInfo(model,context);
              },
             );

        },
      ),
    ],
    ),

        ),
    );


  }
  circularProgress(){
    return Container(
      alignment: Alignment.center,
      padding: EdgeInsets.only(top: 12.0),
      child: CircularProgressIndicator(valueColor: AlwaysStoppedAnimation(Colors.lightGreenAccent),),
    );
  }

  Widget sourceInfo(ItemModel model, BuildContext context  , {Color background, removeCartFunction}) {

          return InkWell(
            onTap: (){
              Navigator.pushReplacement(context, MaterialPageRoute(builder: (context)=>ProductPage(itemModel:model)));
            },
            splashColor: Colors.pink,
            child: Padding(
                padding: EdgeInsets.all(6.0),
            child: Container(
              height: 300.0,
              width: MediaQuery.of(context).size.width,
              child: Row(
                children: [
                  Image.network(model.thumbnailUrl ,width:140.0,height: 140.0,),
                  SizedBox(width: 4.0,),
                  Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(height: 16.0,),
                          Container(
                            child: Row(
                              mainAxisSize: MainAxisSize.max,
                              children: [
                                Expanded(child: Text(
                                  model?.title ?? '',style: TextStyle(color: Colors.black,fontSize: 14.0),
                                ),
                                )
                              ],
                            ),
                          ),
                          SizedBox(height: 5.0,),
                          Container(
                            child: Row(
                              mainAxisSize: MainAxisSize.max,
                              children: [
                                Expanded(child: Text(
                                  model?.shortInfo ?? '',style: TextStyle(color: Colors.black54,fontSize: 12.0),
                                ),
                                )
                              ],
                            ),
                          ),
                          SizedBox(height: 20.0,),
                          Row(
                            children: [
                              Container(
                                decoration: BoxDecoration(
                                  shape: BoxShape.rectangle,
                                  color: Colors.pink,

                                ),
                                alignment: Alignment.topLeft,
                                width: 40.0,
                                height: 43.0,
                                child: Center(
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Text(
                                        "50%",style: TextStyle(
                                        fontSize: 15.0,color: Colors.white,
                                        fontWeight: FontWeight.bold,
                                      ),
                                      ),
                                      Text(
                                        "OFF",style: TextStyle(
                                        fontSize: 12.0,color: Colors.white,
                                        fontWeight: FontWeight.bold,
                                      ),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                              SizedBox(width: 10.0,),
                              Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Padding(
                                      padding: EdgeInsets.only(top: 0.0),
                                  child: Row(
                                    children: [
                                      Text(
                                        "Original Price :%",
                                        style: TextStyle(
                                          fontSize: 14.0,
                                          color: Colors.grey
                                        ),
                                      ),
                                      Text(
                                        (model?.price??'').toString(),
                                        style: TextStyle(
                                            fontSize: 15.0,
                                            color: Colors.grey,
                                          decoration: TextDecoration.lineThrough,

                                        ),
                                      )
                                    ],

                                  ),
                                  ),

                                  Padding(
                                    padding: EdgeInsets.only(top: 5.0),
                                    child: Row(
                                      children: [
                                        Text(
                                          "New Price :%",
                                          style: TextStyle(
                                              fontSize: 16.0,
                                              color: Colors.red,
                                          ),
                                        ),
                                        Text(
                                          "%",
                                          style: TextStyle(
                                              fontSize: 15.0,
                                              color: Colors.grey,
                                          ),
                                        ),
                                        Text(
                                          (model.price+model.price).toString(),
                                          style: TextStyle(
                                              fontSize: 15.0,
                                              color: Colors.grey
                                          ),
                                        ),
                                      ],

                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                          Flexible(child: Container(

                          ),
                          ),
                           //to implement cart add/remove remove
                          Align(
                            alignment: Alignment.centerRight,
                            child: removeCartFunction==null
                              ?IconButton(
                                icon: Icon(Icons.add_shopping_cart,color: Colors.pinkAccent,),
                                onPressed: (){
                                  checkItemInCart(model.shortInfo,context);
                                },)
                                :IconButton(
                                icon: Icon(Icons.delete),
                                onPressed: null)
                          )
                        ],
                      ))
                ],
              ),
            ),
              ),
          );

  }
  void checkItemInCart(String shortInfoAsId, BuildContext context) {
    sharedPreferences.getStringList(EcommerceApp.userCartList).contains(shortInfoAsId)
        ?Fluttertoast.showToast(msg: "item already in cart")
        :addItemToCart(shortInfoAsId,context);
  }

   addItemToCart(String shortInfoAsId, BuildContext context) {
    List tempCartList=sharedPreferences.getStringList(EcommerceApp.userCartList);
    tempCartList.add(shortInfoAsId);
    FirebaseFirestore.instance.collection("users").doc(sharedPreferences.getString(EcommerceApp.userUID))
        .update({
      EcommerceApp.userCartList: tempCartList,
    }).then((value){
      Fluttertoast.showToast(msg: "Item added to cart successfully");
      sharedPreferences.setStringList(EcommerceApp.userCartList, tempCartList);
      Provider.of<CartItemCounter>(context,listen: false).displayResult();
    });
  }


}```


the CartItemCounter dart file is that thrown error when calling consumer<cartitemcounter>.initially useCart is given as garbage value when registering in firebase.



```class CartItemCounter extends ChangeNotifier{


static SharedPreferences sharedPreferences;


  int _counter=sharedPreferences.getStringList("userCart").length-1;
  int get count=>_counter;

  Future<void> displayResult() async{
    
    int _counter=sharedPreferences.getStringList("userCart").length-1;

    await Future.delayed(const Duration(milliseconds: 100),(){
      notifyListeners();
    });
  }
}```




The method 'getStringList' was called on null.
Receiver: null
Tried calling: getStringList("userCart")
The relevant error-causing widget was: 
  Consumer<CartItemCounter> .the details are stored in firebase,the error occurs when displaying the no of items the user have added to the cart.

标签: firebaseflutterdartsharedpreferences

解决方案


错误:

getStringList("...") was called on null

意味着该方法是在一个空对象上调用的,这意味着您正在尝试调用 sharedPrefs.getStringList() 但是,由于它尚未加载,因此 sharedPrefs 目前为空。因此,您会遇到问题。解决此问题的简单技巧:

@override
Widget build(BuildContext context) {
    final _width=MediaQuery.of(context).size.width;
    return SafeArea(
        child: 
          sharedPrefs == null? // If sharedPrefs is not retreived yet
          Scaffold(body: Center(child: Text("Hold on :)"))): // Show this widget
          Scaffold( // Else do your normal job
          appBar: AppBar(
            title: Text("E_shop",style: TextStyle(color:Colors.red,),
          ),
          ......... and so on..

推荐阅读