[英]Riverpod StateNotifierProvider depend on a FutureProvider
[英]Issue implementing StateNotifierProvider from Riverpod
我正在嘗試使用 Riverpod 實現購物車系統來管理購物車的 state。
這是用戶單擊產品以將其添加到購物車的部分:
GestureDetector(
child: Icon(Icons.shopping_cart),
onTap: () async {
print("cart test");
//create new cart item
Cart cartItem = new Cart(
id: product.id,
name: product.name,
oldPrice: product.oldPrice,
price: product.price,
imageUrl: product.imageUrl,
category: product.category,
quantity: 1
);
var cartInstance = context.read(cartListProvider);
if(isExistsInCart(cartInstance.state,cartItem))
context.read(cartListProvider).edit(cartItem,1);
else
{
context.read(cartListProvider).add(cartItem);//if already available in cart, just increase quantity
var string = json.encode(context.read(cartListProvider).state);
await storage.write(key: cartKey, value: string);
}
},
)
這里有提供者 class:
import 'package:cart_system_riverpod/models/cart.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final cartListProvider = StateNotifierProvider((ref){
return CartList([]); //init empty cart
});
我還將 ProviderScope 添加到 Widgets 樹的頂部。
我的問題是我在實施時遇到錯誤:
cartInstance = context.read(cartListProvider)
和
context.read(cartListProvider).edit(cartItem,1);
總是在read(...)
部分
編輯器顯示提示The method 'read' isn't defined for the type 'BuildContext'.
從 Riverpod 1.0.0 中刪除了context.read
以支持ref.read
所以用ref.read
替換context.read
嘗試這個:
Consumer(
builder: (context, ref, _) {
return GestureDetector(
child: Icon(Icons.shopping_cart),
onTap: () async {
print("cart test");
//create new cart item
Cart cartItem = new Cart(
id: product.id,
name: product.name,
oldPrice: product.oldPrice,
price: product.price,
imageUrl: product.imageUrl,
category: product.category,
quantity: 1);
var cartInstance = ref.read(cartListProvider);
if (isExistsInCart(cartInstance.state, cartItem))
ref.read(cartListProvider).edit(cartItem, 1);
else {
ref.read(cartListProvider).add(
cartItem); //if already available in cart, just increase quantity
var string = json.encode(ref.read(cartListProvider).state);
await storage.write(key: cartKey, value: string);
}
},
);
},
);
點擊這里閱讀更多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.