8

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?

Eleandro Duzentos
  • 1,370
  • 18
  • 36

1 Answers1

14

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) => ...);
Alex Hartford
  • 5,110
  • 2
  • 19
  • 36
  • I don't think so. family just let me pass an argument while getting the provider. What I need is to generate differente instances of the same provider so each widget on the list can deal with its own state. See it like a ListView where each ListTile has its own StateNotifierProvider. – Eleandro Duzentos Apr 14 '21 at 18:49
  • 3
    The argument is what you could use to make the different instances of the same provider, though. You could also have the family provider interacting with a StateNotifier that holds state that is common to all the items. – Alex Hartford Apr 14 '21 at 20:32
  • Thank you for your answer. After read the docs again I was able to rethink my implementation and you were right about using family. – Eleandro Duzentos Apr 15 '21 at 10:07
  • 2
    Look into other [solution](https://github.com/rajeshbbalam/flutter_riverpod_multi_instance),by overriding provider with in the ProviderScope. – Rajesh Balam Dec 02 '22 at 11:13