Search code examples
flutterdartflutter-providerstate-management

Show the number of quantity items in the cart Badge


When I add the same item to the cart, the quantity on the cart badge does not increase. How can I increase the number, even when adding the same product. It only changes when I add a different product.

Cart provider

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;
  }


Badge

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

Solution

  • You can add this getter to your Cart 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.

    Also, check my github repo for help.