skip to Main Content

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


  1. Make a custom object eg- Params

    class Params{
    final List<String> handles;
    }
    

    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 using family in provider

    Login or Signup to reply.
  2. From the documentation
    Passing parameters to a provider (family) :

    When using code generation, we no-longer need to rely on the family modifier to pass parameters to a provider. Instead, the main function of our provider can accept any number of parameters, including named, optional, or default values.

    Do note however that these parameters should have still have a consistent ==. Meaning either the values should be cached, or the parameters should override ==.

    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).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search