Search code examples
flutterdartsharedpreferencesriverpod

integrating shared_preferences into riverpod


I am looking to use shared_preferences with riverpod. I'm a riverpod novice and have never worked with shared_preferences before, so I was looking for a guide on/example of how to combine the two. I did see this one but that was using the outdated SharedPreferences instead of SharedPreferencesWithCache or SharedPreferencesAsync.

Here are the 3 ways I came up with (with my limited knowledge):

final sharedPreferencesProvider = Provider((ref)=>SharedPreferencesAsync());

or

final sharedPreferencesProvider = FutureProvider<SharedPreferences>((ref) async {
  final prefs = await SharedPreferences.getInstance();
  return prefs;
});

or

final sharedPreferencesProvider =
    FutureProvider<SharedPreferencesWithCache>((ref) async {
  final prefs = await SharedPreferencesWithCache.create(
      cacheOptions: const SharedPreferencesWithCacheOptions(allowList: null));
  return prefs;
});

I'm not sure which one to use. Also, it feels weird having to have the provider of the withCache variant be a FutureProvider. That means I have to go trough all this AsyncValue hassle (see below) while SharedPreferencesWithCache is meant to not have to deal with that since you should be able to call it synchronously thanks to it being cached. Maybe instead of having it in a FutureProvider, just have it in a global variable? But then the question arises: where do I put that global variable?

Text(ref.watch(sharedPreferencesProvider).asData!.value.getString("my_key")!);

I would also like to have some kind of wrapper around the raw prefs, that seems a little more robust than continously calling setString etc. not sure how I would integrate that class into all of this though... Maybe something like in the previously linked example?


Solution

  • You can simplify this using Riverpod's annotations, which will automatically generate the necessary provider for you, so you don't need to worry about the provider type. Here's an example of how to use it with SharedPreferences:

    // A FutureProvider for accessing SharedPreferences asynchronously
     @Riverpod(keepAlive: true)
     Future<SharedPreferences> sharedPreferences(SharedPreferencesRef ref) =>
     SharedPreferences.getInstance();
    

    With this approach, you can keep your code clean, and the provider will automatically handle the async part for you. It also supports caching thanks to the keepAlive option.

    You can access the preferences like this:

    final prefs = ref.watch(sharedPreferencesProvider).asData?.value;
    final myValue = prefs?.getString("my_key");
    

    For more information on robust app initialization with Riverpod, you can check out this helpful article: Robust App Initialization with Riverpod