显示购物车 Badge 中的商品数量

Show the number of quantity items in the cart Badge

当我将相同的商品添加到购物车时,购物车徽章上的数量没有增加。即使添加相同的产品,我怎样才能增加数量。它只会在我添加不同的产品时发生变化。

购物车提供商

import 'package:flutter/foundation.dart';

class CartItem {
  final String id;
  final String title;
  final int quantity;
  final double price;

  CartItem({
    required this.id,
    required this.title,
    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;
  }


徽章

Consumer<Cart>(
                      builder: (_, cart, ch) => Badge(
                        child: ch!,
                        value: cart.itemCount.toString(),
                        color: Colors.red,
                      ),

您可以将此 getter 添加到您的购物车 class。

int get totalItems {
  return items.values.fold<int>(0, (currentValue, cartItem) {
    return currentValue += cartItem.quantity;
  });
}

Or you can add one more field in your Cart class as itemCount. In that case, you have to update the value of itemCount property every time adding something to the cart.

此外,查看我的 github repo 寻求帮助。