RangeError(索引):索引超出范围:没有有效的索引:Flutter中的0映射



我正在尝试使用提供程序编写添加到购物车逻辑,因此您正在使用API中的特定url进行发布请求。此外,我创建了Map而不是List,并编写了此函数。此外,我正在尝试获取地图的元素。我得到了错误:RangeError (index): Index out of range: no indices are valid: 0

我的提供商逻辑:

class AddToCart with ChangeNotifier {
final Map<String, ProductToBasket> _productCart = {};
Map<String, ProductToBasket> get itemsInCart {
return _productCart;
}

void addInCart({ final String? productId}) async {
if (_productCart.containsKey(productId)) {
try {
final res = await http.post(
Uri.parse('https://secureLink/api/baskets/products'), body: {
'productId' : productId.toString()
});
} catch (e) {
e.toString();
rethrow;
}
} else {
try {
_productCart.putIfAbsent(productId!, () => ProductToBasket(productId: productId));
await http.post(
Uri.parse('https://secureLink/api/baskets/products'), body: {
'productId' : productId.toString()
});
} catch (e) {
e.toString();
rethrow;
}
}
notifyListeners();
}
}

在我的ui中,我调用onPressed函数中的函数,在这里我得到了上面描述的错误:

IconButton(
onPressed: () {providerAddToCart.addInCart(productId: providerAddToCart.itemsInCart.values.elementAt(index).productId);},
icon: FaIcon(
FontAwesomeIcons.shoppingCart,
size: 14,
),
)

检查您的">_productCart";首先列出。告诉我更多的细节。

最新更新