Search code examples
flutterriverpodflutter-riverpod

How to pass initial value to a Notifier using family modifier?


This is my Notifier:

class Counter extends Notifier<int> {
  final int initial;
  Counter(this.initial);

  @override
  int build() => initial;
}

I need to pass initial value to it, but I'm unable to do that using the family modifier anymore.

// Error
final counterProvider = NotifierProvider.family<Counter, int, int>((initial) {
  // How to get the initial value to pass here?
  return Counter(initial);
});

Solution

  • The syntax for using family/autoDispose using Notifier/AsyncNotifier is different. You're supposed to change the inherited type

    So instead of:

    final provider = NotifierProvider(MyNotifier.new);
    
    class MyNotifier extends Notifier<Value> {
    

    With family you should do:

    final provider = NotifierProvider.family(MyNotifier.new);
    
    class MyNotifier extends FamilyNotifier<Value, Param> {
    

    And the same reasoning applies with autoDispose.