You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter调用getCartQuantity()方法时出现getter 'length'调用在null上的错误排查

Fixing "getter 'length' called on null" in Flutter StoreLogic

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 _products in the constructor, but _cart is only declared as List<ProductsModel> _cart;—it's never assigned an empty list or any value. That means _cart stays null forever until you explicitly set it.
  • When you call getCartQuantity(), the line for (int i = 0; i < cart.length; i++) tries to get the length of cart, which is just the getter returning the uninitialized _cart (aka null). Hence the NoSuchMethodError.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 23:22:39