Firebase 颤振:SharedReference检索空值
对null调用了方法“getStringList”。 收件人:空 尝试调用:getStringList(“userCart”) 导致错误的相关小部件是: 消费者。详细信息存储在firebase中,当显示用户已添加到购物车的项目数量时,会发生错误 CartItemCounter dart文件是调用consumer时抛出的错误。在firebase中注册时,最初useCart作为垃圾值提供Firebase 颤振:SharedReference检索空值,firebase,flutter,dart,sharedpreferences,Firebase,Flutter,Dart,Sharedpreferences,对null调用了方法“getStringList”。 收件人:空 尝试调用:getStringList(“userCart”) 导致错误的相关小部件是: 消费者。详细信息存储在firebase中,当显示用户已添加到购物车的项目数量时,会发生错误 CartItemCounter dart文件是调用consumer时抛出的错误。在firebase中注册时,最初useCart作为垃圾值提供 import 'package:flutter_staggered_grid_view/flutter_stag
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.
import'包:颤振交错网格视图/颤振交错网格视图.dart';
导入“包:cloud_firestore/cloud_firestore.dart”;
进口“包装:颤振/材料.省道”;
进口“包装:fluttoast/fluttoast.dart”;
导入“包:provider/provider.dart”;
导入“package:shared_preferences/shared_preferences.dart”;
类StoreHome扩展了StatefulWidget{
@凌驾
_StoreHomeState createState()=>\u StoreHomeState();
}
类_StoreHomeState扩展状态{
SharedReferences SharedReferences;
@凌驾
void initState(){
super.initState();
SharedReferences.getInstance()。然后((prefs){
设置状态(){
SharedReferences=prefs;
});
});
}
@凌驾
小部件构建(构建上下文){
final _width=MediaQuery.of(context).size.width;
返回安全区(
孩子:脚手架(
appBar:appBar(
标题:文本(“E_shop”,样式:TextStyle(颜色:Colors.red,),
),
标题:对,
行动:[
堆叠(
儿童:[
图标按钮(图标:图标(图标。添加购物车,颜色:颜色。灰色,),
已按下:(){
pushReplacement(context,MaterialPageRoute(builder:(context)=>StoreHome());
},
),
定位(子:堆栈)(
儿童:[
图标(图标。亮度1,尺寸:20.0,
颜色:颜色。绿色,),
定位(
排名:3.0,
底部:4.0,
左:4.0,
儿童:消费者(
构建器:(上下文、计数器){
返回文本(
counter.count.toString(),
样式:TextStyle(颜色:Colors.white,fontSize:12.0,fontWeight:fontWeight.w500),
);
},),
),
],
),
),
],
),
],
),
抽屉:MyDrawer(),
正文:自定义滚动视图(
条子:[
滑冰机(
对,,
委托:SearchBoxDelegate(),
),
StreamBuilder(
stream:FirebaseFirestore.instance.collection(“items”).limit(15).orderBy(“publishedDate”,降序:true).snapshots(),
生成器:(上下文,数据快照){
return!dataSnapshot.hasData
?SliverToBoxAdapter(子对象:中心(子对象:循环过程(),),)
:SliverStaggeredGrid.countBuilder(
交叉轴计数:1,
物品计数:5,
交错文件生成器:(c)=>交错文件.fit(1),
itemBuilder:(上下文,索引){
ItemModel model=ItemModel.fromJson(dataSnapshot.data.docs[index].data());
返回sourceInfo(模型、上下文);
},
);
},
),
],
),
),
);
}
循环进程(){
返回容器(
对齐:对齐.center,
填充:仅限边缘设置(顶部:12.0),
子项:循环压缩器指示器(值颜色:AlwaysStoppedAnimation(颜色.浅绿色重音)),
);
}
Widget sourceInfo(ItemModel模型,BuildContext上下文,{Color background,removeCartFunction}){
回墨槽(
onTap:(){
pushReplacement(上下文,materialpage(builder:(context)=>ProductPage(itemModel:model));
},
颜色:颜色。粉红色,
孩子:填充(
填充:所有边缘设置(6.0),
子:容器(
高度:300.0,
宽度:MediaQuery.of(context).size.width,
孩子:排(
儿童:[
Image.network(model.thumbnailUrl,宽度:140.0,高度:140.0,),
尺寸控制盒(宽度:4.0,),
扩大(
子:列(
crossAxisAlignment:crossAxisAlignment.start,
儿童:[
尺寸箱(高度:16.0,),
容器(
孩子:排(
mainAxisSize:mainAxisSize.max,
儿童:[
扩展(子:文本)(
型号?.title???”,样式:TextStyle(颜色:Colors.black,字体大小:14.0),
),
)
],
),
),
尺寸箱(高度:5.0,),
容器(
孩子:排(
mainAxisSize:mainAxisSize.max,
儿童:[
扩展(子:文本)(
型号?.shortInfo???”,样式:TextStyle(颜色:Colors.black54,fontSize:12.0),
),
)
],
),
),
尺寸箱(高度:20.0,),
划船(
儿童:[
容器(
装饰:盒子装饰(
形状:BoxSha
getStringList("...") was called on null
@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..