Getting a getter length called on null error when I call the getCartQuantity() method. Something about the cart being null. I do not know what the problem is.
This is the actual ERROR MESSAGE! NoSuchMethodError: The getter 'length' was called on null. Receiver: null tried calling: length
import 'package:butcherbox/models/productsModel.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class StoreLogic extends ChangeNotifier {
List<ProductsModel> _products;
List<ProductsModel> _cart;
ProductsModel _activeProduct = null;
StoreLogic() {
_products = [
ProductsModel(
id: 001,
imageText: 'images/biggiecombo.jpg',
name: 'ButcherBox Mini Combo Pack',
category: 'Beef and Chicken',
price: 500,
quantity: 0,
),
ProductsModel(
id: 002,
imageText: 'images/thecombopack.jpg',
name: 'ButcherBox Biggie Combo',
category: 'Beef and Chicken',
price: 950,
quantity: 0,
),
ProductsModel(
id: 003,
imageText: 'images/regular1kg.jpg',
name: 'ButcherBox Regular 1kg',
category: 'Beef',
price: 1800,
quantity: 0,
),
];
notifyListeners();
}
List<ProductsModel> get products => _products;
List<ProductsModel> get cart => _cart;
ProductsModel get activeProduct => _activeProduct;
setActiveProduct(ProductsModel p) {
_activeProduct = p;
}
addOneItemToCart(ProductsModel p) {
ProductsModel found =
_cart.firstWhere((a) => a.id == p.id, orElse: () => null);
if (found != null) {
found.quantity = 1;
} else {
_cart.add(p);
}
notifyListeners();
}
getCartQuantity() {
int totalItems = 0;
for (int i = 0; i < cart.length; i ) {
totalItems = cart[i].quantity;
}
return totalItems;
}
}
The cart.length returns the error
CodePudding user response:
Check if your cart is null before performing an operation on it.
getCartQuantity() {
int totalItems = 0;
if(cart == null) return totalItems; //add this line.
for (int i = 0; i < cart.length; i ) {
totalItems = cart[i].quantity;
}
return totalItems;
}
But in general, it appears you are not using null-safety, which I strongly advise you to do.