Eleandro Duzentos
Eleandro Duzentos

Reputation: 1568

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.

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.

The problem is:

Riverpod is only able to create an instance and that same instance is shared over the whole project. 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?

Upvotes: 10

Views: 4885

Answers (1)

Alex Hartford
Alex Hartford

Reputation: 6000

You're looking for the .family modifier. See the docs here. You could pass an id or key as the parameter to your StateProvider.

For example:

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

Upvotes: 15

Related Questions