我在颤振中得到一个名为null错误的getter.当试图访问列表的长度时



当我调用getCartQuantity()方法时,在null错误上调用getter长度。关于购物车是空的。我不知道是什么问题。

这是实际的错误消息!NoSuchMethodError: getter 'length'在null时被调用。接收器:零已尝试呼叫:长度

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

购物车。Length返回错误

在对其执行操作之前检查您的购物车是否为空。

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

但总的来说,你似乎没有使用null-safety,我强烈建议你这样做。