如何通过使用DocumentSnapshot来转换从Firestore检索到的数据?



我试图计算购物车中使用DocumentSnapshot从Firestore检索的项目的总价格。我的技巧是在ListView Builder完成迭代时总结价格,但我得到了'double'类型不是'String'类型的子类型';错误消息。

这是汇总购物车中价格的代码:

price = double.parse(documentSnapshot['price']) + price;

price的初始化

double price = 0;

购物车代码

Widget bodySection(BuildContext context) {
return StreamBuilder(
stream: FirebaseFirestore.instance
.collection('users')
.doc(userid)
.collection('cart')
.snapshots(),
builder: (context, AsyncSnapshot<QuerySnapshot> streamSnapshot) {
if (streamSnapshot.hasData) {
return Padding(
padding: EdgeInsets.symmetric(
horizontal: getProportionateScreenWidth(20)),
child: ListView.builder(
itemCount: streamSnapshot.data!.docs.length,
itemBuilder: (context, index) {
final DocumentSnapshot documentSnapshot =
streamSnapshot.data!.docs[index];
price = double.parse(documentSnapshot['price']) + price;
String imgurl = documentSnapshot['imgUrl'];
return Padding(
padding: EdgeInsets.symmetric(vertical: 10),
child: Dismissible(
key: Key(documentSnapshot['id']),
direction: DismissDirection.endToStart,
onDismissed: (direction) {
setState(() {
});
},
background: Container(
padding: EdgeInsets.symmetric(horizontal: 20),
decoration: BoxDecoration(
color: Color(0xFFFFE6E6),
borderRadius: BorderRadius.circular(15),
),
child: Row(
children: [
Spacer(),
Icon(Icons.delete),
],
),
),
child: Container(
padding: EdgeInsets.all(
getProportionateScreenWidth(8)),
decoration: BoxDecoration(
color: Colors.white ,
borderRadius: BorderRadius.circular(15),  
),
child: Row(
children: [
SizedBox(
width: 88,
child: AspectRatio(
aspectRatio: 0.88,
child: Container(
padding: EdgeInsets.all(
getProportionateScreenWidth(5)),
decoration: BoxDecoration(
color: Colors.black,
borderRadius: BorderRadius.circular(10),
image: DecorationImage(image: NetworkImage(imgurl), fit: BoxFit.cover)
),
),
),
),
SizedBox(width: 20),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
documentSnapshot['brand'] + " " + documentSnapshot['name'], 
style: TextStyle(
color: Colors.black, fontSize: 16),
maxLines: 2,
),
SizedBox(height: 10),
Text.rich(
TextSpan(
text:
"RM " + price.toString(),
style: TextStyle(
fontWeight: FontWeight.w600,
color: kPrimaryColor),
),
)
],
),
Spacer(),
Column(
children: [
SizedBox(height: 30,),
Text(
"x 1", 
style: TextStyle(
color: Colors.black, fontSize: 16),
),
],
),
],
),
),
));
}
),
);
}
return const Center(
child: CircularProgressIndicator(),
);
});

}

price = double.parse(documentSnapshot['price']) + price;

price = documentSnapshot['price'] + price;

我认为你的documentSnapshot['price']已经返回double &翻倍。parse(' ')接受字符串,这就是为什么它显示的'double'类型不是' string '类型的子类型

最新更新