Flutter调用getCartQuantity()方法时出现getter 'length'调用在null上的错误排查
Hey there, let's tackle this null pointer error you're facing. The root cause is pretty straightforward: your _cart list is never initialized, so when you try to access cart.length in getCartQuantity(), you're calling a getter on a null value.
Let's break down the problem
Looking at your StoreLogic class:
- You initialize
_productsin the constructor, but_cartis only declared asList<ProductsModel> _cart;—it's never assigned an empty list or any value. That means_cartstaysnullforever until you explicitly set it. - When you call
getCartQuantity(), the linefor (int i = 0; i < cart.length; i++)tries to get the length ofcart, which is just the getter returning the uninitialized_cart(akanull). Hence theNoSuchMethodError.
The fix
You have two easy ways to initialize _cart to avoid this:
Option 1: Initialize during declaration
Change the _cart declaration to:
List<ProductsModel> _cart = [];
Option 2: Initialize in the constructor
Add the initialization line inside your StoreLogic() constructor, right after setting _products:
StoreLogic() { _products = [ // your product items here ]; _cart = []; // Add this line notifyListeners(); }
Bonus: Fix another potential null issue
Your addOneItemToCart() method also uses _cart.firstWhere(...)—if _cart is null, this will throw another error. Initializing _cart as above will fix this too.
Extra tip for null safety
If you're using Flutter's null safety (which you should be!), you can make your code more robust by declaring _cart as a non-nullable list from the start. For example:
final List<ProductsModel> _cart = [];
Or use late if you need to initialize it later (but in this case, immediate initialization is better).
Also, you can add a null check in getCartQuantity() as a fallback, though initializing _cart is the proper fix:
getCartQuantity() { if (cart == null) return 0; // Fallback if cart is null (shouldn't happen after initialization) int totalItems = 0; for (int i = 0; i < cart.length; i++) { totalItems += cart[i].quantity; } return totalItems; }
Once you initialize _cart, your getCartQuantity() method will work as expected, and you won't see that null pointer error anymore.
内容的提问来源于stack exchange,提问作者thearach

