5

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);
});
iDecode
  • 22,623
  • 19
  • 99
  • 186

2 Answers2

8

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.

Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432
1

To add to @Rémi Rousselet's answer, the way to do this using generators (which is the recommended way of using riverpod) is as follows:

import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'counter.g.dart';

@riverpod
class Counter extends _$Counter {
  @override
  int build(int initial) => initial;
}
Alex Lomia
  • 6,705
  • 12
  • 53
  • 87