skip to Main Content

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.

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search