简体   繁体   English

Flutter Riverpod:如何为 GridView 上的每个有状态小部件创建同一提供程序的不同实例

[英]Flutter Riverpod: How to create different instances of the same provider for each Stateful widget on a GridView

I have a GridView which contains a list of StatefulWidgets that shows a preview of the image being uploaded and the progress of the upload for that image.我有一个 GridView ,其中包含一个StatefulWidgets列表,其中显示了正在上传的图像的预览以及该图像的上传进度。

Each widget on the list should have its own state where some of them can upload successfully and others may fail, so the user can retry only those images that failed to upload.列表中的每个小部件都应该有自己的 state ,其中一些可以成功上传,其他可能会失败,因此用户只能重试那些未能上传的图像。

The problem is:问题是:

Riverpod is only able to create an instance and that same instance is shared over the whole project. Riverpod 只能创建一个实例,并且该实例在整个项目中共享。 So, if I use Riverpod to track the state of each image, all images on the GridView will share the same state instead of each one have its own state. So, if I use Riverpod to track the state of each image, all images on the GridView will share the same state instead of each one have its own state.

Is there a way to use the same provider, but instead of get the same instance every time I call context.read(provider) or watch(provider.state) I get a new independent and fresh one?有没有办法使用相同的提供程序,但不是每次我调用context.read(provider)watch(provider.state)时都得到相同的实例,而是得到一个新的独立和新鲜的实例?

You're looking for the .family modifier.您正在寻找.family修饰符。 See the docs here .请参阅此处的文档。 You could pass an id or key as the parameter to your StateProvider.您可以将 id 或密钥作为参数传递给您的 StateProvider。

For example:例如:

final imageProvider = StateProvider.family<ImageModel, String>((ref, id) => ...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM