flutterdartriverpod

Passing parameter to AsyncNotifier of Riverpod in Flutter


I would like to initialize an AsyncNotifier with parameter. I have looked at a couple answers on SO but I have not been able to find one for my case. (This might work if I used annotation approach but I am not using it so this doesn't work for my case. Since I need to pass parameter from UI, calling ref.read/ref.watch in AsyncNotifier doesn't work as well) The code below is what I am trying to achieve. can anyone help me on this?

final postViewModel =
    AsyncNotifierProvider<PostViewModel, Post?>(
  () => PostViewModel(),
);

class PostViewModel extends AsyncNotifier<Post?> implements BasePostListInterface {

  late final FetchPostUseCase _fetchPostUseCase =
  ref.read(fetchPostUseCaseProvider);

  @override
  FutureOr<Post?> build(String targetPostDocumentId) async { // <- how to achieve passing parameter to build() ?
    return await _fetchPostUseCase(targetPostDocumentId);
  }
}

Solution

  • You need to use FamilyAsyncNotifier instead. When using family provider, it is also preferred to use it along with the autodispose option, which would need you to extend AutoDisposeFamilyAsyncNotifier for the notifier.

    This is covered in this page of the docs. Make sure to turn off the "Code generation" option in the side menu.