tableDetail.dart 1.8 KB

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