17.6 购物商品数量修改
实现步骤:
lib/common/components/quantity.dart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| import 'package:flutter/cupertino.dart';
import '../index.dart';
class QuantityWidget extends StatelessWidget { final Function(int quantity) onChange; final int quantity; final double? size; final double? fontSize; final double? paddingHorizontal; final Color? color;
QuantityWidget({ Key? key, required this.quantity, required this.onChange, this.size, this.fontSize, this.paddingHorizontal, Color? color, }) : color = color ?? AppColors.onSurfaceVariant, super(key: key);
@override Widget build(BuildContext context) { return <Widget>[ ButtonWidget.icon( Icon( CupertinoIcons.minus, size: fontSize ?? 14, color: color, ), onTap: () => onChange(quantity - 1 < 0 ? 0 : quantity - 1), ),
TextWidget.body2( "$quantity", color: color, ) .center() .tight(width: size ?? 24, height: size ?? 24) .decorated( borderRadius: const BorderRadius.all(Radius.circular(4)), border: Border.all(color: color!, width: 1), ) .paddingHorizontal(paddingHorizontal ?? AppSpace.iconTextSmail),
ButtonWidget.icon( Icon( CupertinoIcons.plus, size: fontSize ?? 14, color: AppColors.highlight, ), onTap: () => onChange(quantity + 1), ), ].toRow(); } }
|
第 2 步:购物车项加入数量控制
lib/pages/cart/cart_index/widgets/cart_item.dart
1 2 3 4 5 6 7 8 9 10 11 12 13
| <Widget>[ ...
QuantityWidget( quantity: lineItem.quantity ?? 0, onChange: (quantity) => onChangeQuantity?.call(quantity), ),
].toRow().paddingTop(AppSpace.listRow),
|
第 3 步:控制器
lib/pages/cart/cart_index/controller.dart
1 2 3 4 5
| Future<void> onChangeQuantity(LineItem item, int quantity) async { CartService.to.changeQuantity(item.productId!, quantity); update(["cart_index"]); }
|
第 4 步:视图
lib/pages/cart/cart_index/view.dart
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| Widget _buildOrders() { return ListView.separated( itemBuilder: (BuildContext context, int index) { LineItem item = CartService.to.lineItems[index]; return CartItem( ... onChangeQuantity: (quantity) => controller.onChangeQuantity(item, quantity), ).paddingAll(AppSpace.card).card(); }, separatorBuilder: (BuildContext context, int index) { return SizedBox(height: AppSpace.listRow); }, itemCount: CartService.to.lineItems.length, ); }
|
提交代码到 git