如何在Riverpod中使用嵌套提供者的概念-
我们没有通过构造函数推送数据,而是使用ChangeNotifierProvider.value() (嵌套提供程序),然后使用模型来显示数据。提供者本身将把构建器数据推入模型字段
class ProductModel with ChangeNotifier {
final String imageUrl;
ProductModel({required this.imageUrl});}
来自product_grid.dart
GridView.builder(
itemCount: selectedProductList.length,
itemBuilder: (ctx, i) =>
ChangeNotifierProvider.value(
value: selectedProductList[i],
child: const ProductItem(),),);
转到product_item.dart
final productModel = Provider.of<ProductModel>(context);
return GridTile(
child: Image.network(
productModel.imageUrl,
fit: BoxFit.cover,
),
发布于 2022-05-17 21:48:22
听起来,您想要的是ProviderScope
,您可以覆盖它的后代提供程序的值。
创建一个提供者:
final selectedProduct = Provider<ProductModel>((_) => throw UnimplementedError());
GridView.builder(
itemCount: selectedProductList.length,
itemBuilder: (ctx, i) =>
ProviderScope(
overrides: [selectedProduct.overrideWithValue(selectedProductList[i])],
child: const ProductItem(),),);
然后在product_item.dart
final productModel = ref.watch(selectedProduct);
return GridTile(
child: Image.network(
productModel.imageUrl,
fit: BoxFit.cover,
),
如果您想查看一下Remi是如何做到的,那么这个示例在Todo应用程序中有上面的实现:https://github.com/rrousselGit/riverpod/blob/master/examples/todos/lib/main.dart
希望这能帮上忙!
https://stackoverflow.com/questions/72253838
复制相似问题