Flutter/Riverpod - how to combine providers for fetching data list and holding the data list as state?

1.7k views Asked by At

I've been playing with the RiverPod 2.0 state management package to understand how to use it for CRUD type operations

What I can't understand is how to use the range of providers to support..

  • The asynchronous loading of a data object list prior to displaying it in a list view , i.e. a FutureProvider
  • Maintaining the data object list in a provider to support CRUD use cases, i.e. a StateNotifierProvider.

In my Flutter list view I am reading the data from the StateNotifierProvider, not the FutureProvider.

It seems like you need two distinct providers for this one situation. Is that correct?

Currently, I am using a FutureProvider to load the data list, and inside this FutureProvider pushing the data into the StateNotifierProvider. Is that the correct approach?

1

There are 1 answers

0
Ruble On

The new way is to use AsyncNotifier to asynchronously read data from a database or server. You can read a good article on the subject in more detail:

How to use Notifier and AsyncNotifier

The old way, on the other hand, was to use StateNotifier with Async state. Something like that:

final dataProvider = StateNotifierProvider<DATANotifier, AsyncValue<YOURDATA>>((ref) {
  return DATANotifier();
});

class DATANotifier extends StateNotifier<AsyncValue<YOURDATA>> {
  DATANotifier() : super(const AsyncValue.loading()) {
    _init();
  }

  Future<void> _init() async {
    state = await AsyncValue.guard(() => LocalStorage().getData());
  }

  // Post your CRUD methods for working with data here
}

The FutureProvider is an asynchronous version of the StateProvider in the sense that it does not serve as a place to store and handle large logic.