I’m using riverpod with code generation for state management.
Here, I’ve a variable named ‘handle’ which is passed onto the constructor of my widget and then I need to pass this variable in a list to a network call function.
Network call code
@riverpod
Future<List<User>?> getUsers(GetUsersRef ref, String handle) async {
....
}
Wen I make a network call using ref.watch(GetUsersProvider(handle)) in my consumerWidget, it works fine in this case but the problem arises when I want to pass a list of string to my network call function.
Network call code 2
@riverpod
Future<List<User>?> getUsers(GetUsersRef ref, List<String> handles) async {
....
print("Network call successful");
}
In this case when I call ref.watch(GetUsersProvider([handle]), my widget continuously rebuilds itself and never stops loading even though the network call is successful.
How should I tackle this?
I tried passing const List<String> = ['handleName']
, this works but then I can’t really create a const List of Strings using the handle variable passed to the constructor.
How do you guys pass a List of String to a provider in riverpod using code generation?
2
Answers
Make a custom object eg- Params
When you pass arguments to riverpod. It creates provider for each argument. In your case it creates list.length no. of providers.
Check out
.family
in riverpod. Your provider uses family. In family it recognize each provider with == against it arguments to check provider identity. As you passes a list to it. So it made a list of same provider but with different values.And it is recommended to use
autodispose
when usingfamily
in providerFrom the documentation
Passing parameters to a provider (family) :
The last paragraph matters to us now. Off the top of my head, the idea comes to making an immutable wrapper for the list (use freezed), or using an immutable list type (third-party packages).