flutterdartriverpod

How to execute member method in FamilyAsyncNotifier of riverpod?


How to execute member method in FamilyAsyncNotifier?
(This is kind of continuous question to my previous question.) I initialized my FamilyAsyncNotifier by passing parameter to it. However, now I am not able to execute member method in FamilyAsyncNotifier. when it was just AsyncNotifier, member method was called like this.

await ref.read(postViewModel.notifier).fetchTargetPost(targetPostId);

However, I am not able to call it with FamilyAsyncNotifier. Does anybody know how to call member method in FamilyAsyncNotifier? I just wanted to pass parameter to AsyncNotifier but it seems like it is getting more complicated with FamilyAsyncNotifier. I really appreciate anybody's help on it.

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

class PostViewModel extends FamilyAsyncNotifier<Post?, String> implements BasePostListInterface {

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

  @override
  FutureOr<Post?> build(String targetPostDocumentId) async { // <- now I am able to initialize it with parameter
    return _fetchPostUseCase(targetPostDocumentId);
  }

  Future<Post> fetchTargetPost(String targetPostDocumentId) async { // However, I can't execute this member method from UI.
    state = const AsyncValue.loading();
    Post post = Post.empty();
    state = await AsyncValue.guard( () async {
      post = await _fetchPostUseCase(targetPostDocumentId);
      return post;
    });
    return post;
  }
}

Solution

  • postViewModel.notifier should be postViewModel(familykey).notifier. That is, since you have a family of providers, you must identify which provider you want the notifier for.