Home > Mobile >  flutter show late initialization error which flutter provider package?
flutter show late initialization error which flutter provider package?

Time:08-10

why this error is shown on emulator ? it show in _items when debugging. in flutter provider show error on emulator Late Initialization error : field _ items has not been initialize. it show testing/ error

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 {
  late Map<String, CartItem> _items;

  Map<String, CartItem> get items {
    return {..._items};
  }

  int get iteamCount {
    return _items.length;
  }

  void addItem(String productId, double price, String title) {
    if (_items.containsKey(productId)) {
      //change quantity
      _items.update(
          productId,
          (existingCartItem) => CartItem(
                id: existingCartItem.id,
                title: existingCartItem.title,
                quantity: existingCartItem.quantity   1,
                price: existingCartItem.price,
              ));
    } else {
      _items.putIfAbsent(
          productId,
          () => CartItem(
                id: DateTime.now().toString(),
                title: title,
                price: price,
                quantity: 1,
              ));
    }
  }
}
    

CodePudding user response:

_items should be initialized before used.

Or you can just replace late Map<String, CartItem> _items with Map<String, CartItem> _items = {}.

  • Related