River_pod: Initialize StateNotifierProvider Asynchronously

Created on 16 Sep 2020  路  9Comments  路  Source: rrousselGit/river_pod

How can I initialize StateNotifierProvider asynchronously? I want to initialize a list of before creating an instance of it. The data are coming from an api. The problem is the StateNotifierProvider doesn't work in async. Here below is my code:

final countryListProvider = StateNotifierProvider((ref) async {
  try {
    final countryList = await ref.watch(countryRepository).getAllCountries();
    return CountryList(countryList);
  } catch (e) {
    print(e) // also how can i show the error in the UI
  }
});

class CountryList extends StateNotifier<List<CountryEntity>> {
   CountryList([List<Todo> initialCountryList]): super(initialCountryList ?? []);

   filterCountries(String str) async {
     try {
       final regex = RegExp(str, caseSensitive: false);
       return state
            .where((element) => regex.hasMatch(element.name))
            .toList();
    } catch(e) {
      rethrow;
    }
   } 
}
documentation

All 9 comments

Hi, thanks for this new state management solution. I think I don't need a FutureProvider because I do not need to listen to it. I will only use country list data to show as a suggestion to my country text field.

oh i see. if i do that where should i call fetch? inside init state? Another thing. What does guard do? Is there a documentation for AsyncValue on how to use it? Thanks!

No need for initState. The StateNotifierProvider is enough

For AsyncValue, see its dartdoc https://pub.dev/documentation/riverpod/latest/all/AsyncValue-class.html

Alright. thank you so much! you may close this issue.

Additional. Can you provide a use case for each Providers in the https://riverpod.dev/? I am overwhelmed because of many Providers. hehehe!

Each provider has its own documentation on pub https://pub.dev/documentation/riverpod/latest/all/FutureProvider-class.html

I'll search for a way to make this more accessible

Thanks Thanks!

Was this page helpful?
0 / 5 - 0 ratings