skip to Main Content

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);
  }
}

2

Answers


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

    Login or Signup to reply.
  2. Do not confuse "initialization" values with "family selectors", although family selectors often participate in the initialization.

    The build() method of a notifier can get initial data from:

    1. other providers (using the Notifier.ref) as in ref.watch(someOtherProvider),
    2. globals (although these will not continue to be observed for changes)
    3. library-locals or class locals if the provider is defined within a class
    4. family selectors, as defined earlier.

    So, there’s many ways to provide initialization values!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search