Why does Riverpod generator not generate an AsyncNotifier in this case?

123 views Asked by At

I want to generate an AsyncNotifier that takes one argument on build:

@riverpod
class ListController extends _$ListController {
  late ServiceOne _serviceOne;
  late ServiceTwo _serviceTwo;

  @override
  Future<List<ItemModel>> build(ListModel List) {
    _serviceOne = ref.read(serviceOneServiceProvider);
    _serviceTwo = ref.read(serviceTwoServiceProvider);
    return _fetchListItems(list);
  }

  /// A method I´d like to call
  Future<void> someMethod() async {
    // ... some state mutation operations here...
  }

  /// 
  Future<List<ItemModel> _fetchListItems(list) async {
    // ... fetch models here from e.g. an API
  }
}

The problem here is, that the generator creates a ListControllerFamily provider instead of an AsyncNotifier. So I'm unable to access the methods like this:

ref.read(listControllerProvider.notifier).someMethod();

The .notifier getter is not available. I´ve the exact same setup for another class but without parameters and there it works as expected.

3

There are 3 answers

0
Dhafin Rayhan On BEST ANSWER

Your provider is a family provider, because you provided at least one parameter to the build method:

Future<List<ItemModel>> build(ListModel List) {

To access the notifier of a family provider, you have to call it as a function, and provide the argument since the list parameter here is a required positional parameter:

ref.read(listControllerProvider(someList).notifier).someMethod();

See also:

0
Ruble On

Try passing the argument like this:

final ListModel model = ...;
ref.read(listControllerProvider(model).notifier).someMethod();

And every time you need to contact this provider, you will need to pass an argument.

1
BG Park On

Add async in your build method.

@riverpod
class ListController extends _$ListController {
  late ServiceOne _serviceOne;
  late ServiceTwo _serviceTwo;

  @override
  FutureOr<List<ItemModel>> build(ListModel List) async {
    _serviceOne = ref.read(serviceOneServiceProvider);
    _serviceTwo = ref.read(serviceTwoServiceProvider);
    return _fetchListItems(list);
  }

  /// A method I´d like to call
  Future<void> someMethod() async {
    // ... some state mutation operations here...
  }

  /// 
  Future<List<ItemModel> _fetchListItems(list) async {
    // ... fetch models here from e.g. an API
  }
}