flutter - 如何添加我购物车中所有商品的总数而不是商品*数量,还添加运费和折扣以使其总计?
问题描述
我正在尝试添加我们在每件商品的数量 * 价格之后获得的商品总量,并在其中添加运费使其总计,然后我们继续结帐。这是我的购物车模型
class CartItem {
final String id;
final String name;
final int quantity;
final double price;
CartItem(
{@required this.id,
@required this.name,
@required this.quantity,
@required this.price});
}
class Cart with ChangeNotifier {
Map<String, CartItem> _items = {};
Map<String, CartItem> get items {
return {..._items};
}
int get itemCount {
return _items.length;
}
void addItem(String pdtid, String name, double price) {
if (_items.containsKey(pdtid)) {
_items.update(
pdtid,
(existingCartItem) => CartItem(
id: DateTime.now().toString(),
name: existingCartItem.name,
quantity: existingCartItem.quantity + 1,
price: existingCartItem.price));
} else {
_items.putIfAbsent(
pdtid,
() => CartItem(
name: name,
id: DateTime.now().toString(),
quantity: 1,
price: price,
));
}
notifyListeners();
}
void removeItem(String id) {
_items.remove(id);
notifyListeners();
}
void removeSingleItem(String id) {
if (!_items.containsKey(id)) {
return;
}
if (_items[id].quantity > 1) {
_items.update(
id,
(existingCartItem) => CartItem(
id: DateTime.now().toString(),
name: existingCartItem.name,
quantity: existingCartItem.quantity - 1,
price: existingCartItem.price));
}
notifyListeners();
}
double get totalAmount {
var total = 0.0;
_items.forEach((key, cartItem) {
total += cartItem.price * cartItem.quantity;
});
return total;
}
void clear() {
_items = {};
notifyListeners();
}
}
这是我的购物车屏幕代码;
class CartScreen extends StatelessWidget {
static const routeName = '/cart';
@override
Widget build(BuildContext context) {
final cart = Provider.of<Cart>(context);
return Scaffold(
appBar: AppBar(
title: Text(
'My Cart',
style: TextStyle(fontSize: 30, color: Theme.of(context).accentColor),
),
),
body: Column(
children: <Widget>[
Expanded(
child: ListView.builder(
itemCount: cart.items.length,
itemBuilder: (ctx, i) => CartPdt(
cart.items.values.toList()[i].id,
cart.items.keys.toList()[i],
cart.items.values.toList()[i].price,
cart.items.values.toList()[i].quantity,
cart.items.values.toList()[i].name)),
),
CheckoutButton(
cart: cart,
),
],
),
);
}
}
我只是想添加总金额并添加运费以使其总计并低于结帐按钮
解决方案
推荐阅读
- javascript - 异步函数具有旧状态 React-Redux
- google-sheets-api - 客户必须启用什么才能使用我的应用编辑他们的 Google 表格
- java - 了解pdf中的图形(变换矩阵cm)坐标(图形的解析位置)系统?
- java - 正则表达式需要一个字母和一个非字母并且没有空格
- java - 如何逐点获取地图中的值?
- joomla - Mod_security - 需要帮助
- android - Android 以编程方式使用 ConstraintLayout 添加 ImageView
- javascript - 引导和反应,在单选按钮上分配 .active 类
- android - 使用 Kotlin 的片段中的 runOnUiThread() 方法
- google-apis-explorer - 如何使用 REST API 将 Bitbucket 存储库连接到 Google 云源存储库