flutter - 如何获取购物篮中所有商品的总价
问题描述
如何获得购物篮中所有商品的总价?
在购物车中添加商品后,我想获取购物车中所有商品的总价。当每件商品的数量增加时,价格也应该增加,当数量减少时,价格也会下降。请帮助我,
购物车类中的总变量输出 null
购物车类
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'dish_object.dart';
class Cart extends StatefulWidget {
final List<Dish> _cart;
Cart(this._cart);
@override
_CartState createState() => _CartState(this._cart);
}
class _CartState extends State<Cart> {
_CartState(this._cart);
List<Dish> _cart;
double totalPrice = 0;
double getTotalPrice() {
double total = 0;
_cart.forEach((item) {
total += item.totalPrice;
});
setState(() {
totalPrice = total;
});
}
@override
void initState() {
super.initState();
getTotalPrice();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Cart'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.send_rounded),
tooltip: "Confirm Order",
onPressed: () {
if (_cart.isNotEmpty) {
setState(() {
Fluttertoast.showToast(
msg: "Order Confirmed",
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.grey,
textColor: Colors.white,
fontSize: 16.0);
});
}
if (_cart.isEmpty) {
setState(() {
Fluttertoast.showToast(
msg: "Cart Empty",
toastLength: Toast.LENGTH_LONG,
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
fontSize: 16.0);
});
}
}),
if (_cart.length > 0)
Padding(
padding: const EdgeInsets.only(left: 0.0),
child: CircleAvatar(
radius: 10.0,
backgroundColor: Colors.red,
foregroundColor: Colors.white,
child: Text(
_cart.length.toString(),
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 12.0,
),
),
),
),
],
),
body: ListView.builder(
itemCount: _cart.length,
itemBuilder: (context, index) {
var item = _cart[index];
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 2.0),
child: Card(
elevation: 4.0,
child: ListTile(
//Leading
leading: Text(item.totalPrice.toString() +
item.category +
"\n" +
"R" +
item.price.toString()),
//Title
title: Text(item.brandName +
"\n" +
"(" +
item.counter.toString() +
")"),
//Subtitle
subtitle: GestureDetector(
child: Icon(
Icons.add,
color: Colors.green,
),
onTap: () {
setState(() {
item.incrementCounter();
});
},
),
//Trailing
trailing: GestureDetector(
child: Icon(
Icons.remove_circle,
color: Colors.red,
),
onTap: () {
setState(() {
item.decrementCounter();
});
},
),
isThreeLine: true,
),
),
);
},
),
);
}
}
解决方案
您可以尝试添加一个变量 _totalPrice 并访问它
double _totalPrice = 0;
可以通过一项通用功能进行更改:
double getTotalPrice() {
double total = 0;
_cart.forEach((item) {
total+= item.totalPrice;
});
setState(() {
_totalPrice = total;
});
}
将 getTotalPrice() 添加到您的 initState() 函数中,以便在安装屏幕或代码中的其他位置时调用它。
或每次添加/删除产品时增加/减少总价值
_addPrice(double price) {
setState(() {
_totalPrice += price;
});
}
_subtractPrice(double price) {
setState(() {
_totalPrice -= price;
});
}
-- 编辑:并确保将变量插入到视图中要显示的任何位置