tableDetail.dart 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import 'package:flutter/cupertino.dart';
  2. import 'package:fooddeliveryapp/model/product.dart';
  3. class Item {
  4. int count;
  5. Product product;
  6. Item(int i, Product p) {
  7. this.count = i;
  8. product = p;
  9. }
  10. }
  11. class TableDetail with ChangeNotifier {
  12. //记录当前使用台号
  13. int _tableId;
  14. DateTime openTime;
  15. TableDetail({int id}) {
  16. this._tableId = id;
  17. notifyListeners();
  18. }
  19. List<Item> _items = [];
  20. List<Item> get items => _items;
  21. int getTableId() => _tableId;
  22. DateTime getOpenTime() => openTime;
  23. setTableId(int id) {
  24. print("[tabledetails]设置桌号id" + id.toString());
  25. this._tableId = id;
  26. this.openTime = DateTime.now();
  27. notifyListeners();
  28. }
  29. addItem(Product p) {
  30. Item item = _items.firstWhere((i) => i.product == p, orElse: () => null);
  31. if (item == null) {
  32. item = Item(0, p);
  33. _items.add(item);
  34. }
  35. item.count++;
  36. notifyListeners();
  37. }
  38. // 从购物车移除商品,判断数量,通知
  39. removeItem(Product p) {
  40. Item item = _items.firstWhere((i) => i.product == p, orElse: () => null);
  41. if (item == null) {
  42. return;
  43. }
  44. item.count--;
  45. if (item.count == 0) {
  46. _items.remove(item);
  47. }
  48. notifyListeners();
  49. }
  50. endCart() {
  51. _items = [];
  52. }
  53. // 获取购物车中指定商品数量,不存在返回0
  54. int getItemCount(Product p) {
  55. Item item = _items.firstWhere((i) => i.product == p, orElse: () => null);
  56. return item == null ? 0 : item.count;
  57. }
  58. // 计算总总额。取小数点2位转字符串
  59. String getTotalPrices() {
  60. double total = 0;
  61. for (var item in _items) {
  62. total += item.product.price * item.count;
  63. }
  64. return total.toStringAsFixed(2);
  65. }
  66. }