Search code examples
flutterdartproviderriverpod

About the latest technologies in Riverpod


I recently started learning Flutter. So when I asked a question about Riverpod on this site, I received the following advice:

The literature is rushing to catch up with Remi's prolific development. In brief, avoid legacy ChangeNotifier, StateNotifier (and their providers) and StateProvider. Use only Provider, FutureProvider, StreamProvider, and Notifier, AsyncNotifier, StreamNotifier (and their providers). (I appreciate the person who gave me advice. Thank you.)

And here is the code that is causing the issue:

final sampleProvider = StateNotifierProvider<SampleNotifier, int>((ref) {
  return SampleNotifier();
});

class SampleNotifier extends StateNotifier<int> {
  SampleNotifier() : super(0);
  void setDay({required int day}) {
    state = day;
  }
}

I don't understand the issue you were advised about. Could you please provide more details about what needs to be changed in the code and how?


Solution

  • In this case you can use Notifier and NotifierProvider:

    final sampleProvider = NotifierProvider<SampleNotifier, int>(() {
      return SampleNotifier();
    });
    
    class SampleNotifier extends Notifier<int> {
    
      @override
      int build() {
        // Load initial value
        // it is also safe to use `ref.watch` here
        return 0;
      }
    
      void setDay({required int day}) {
        // use here `ref.read` when necessary
        state = day;
      }
    }