Home > Software engineering >  Flutter RiverPod: Is it ok to return another provider from build method of Notifier?
Flutter RiverPod: Is it ok to return another provider from build method of Notifier?

Time:02-03

I want to keep my return value as AsyncValue rather than Stream so I am returning StreamProvider from build method of Notifier. After reading the codebase of riverpod I can't see any drawback of this, but I have never come across any project doing something like this. Is this fine, or is there any straight forward way to convert Stream to AsyncValue.

final _userProvider = StreamProvider.autoDispose<User?>((ref) {
  final repository = ref.watch(repositoryProvider);
  return repository.getUser(); //returns Stream<User?>
});

class AuthNotifier extends AutoDisposeNotifier<AsyncValue<User?>> {
  @override
  AsyncValue<User?> build() {
    return ref.watch(_userProvider);
  }

  Future<void> singOut() {
    return ref.read(repositoryProvider).signOut();
  }
}

final authProvider =
    AutoDisposeNotifierProvider<AuthNotifier, AsyncValue<User?>>(
        AuthNotifier.new);

CodePudding user response:

This is fine, yes. Being able to do such a thing is the goal of the build method & ref.watch

As long as you don't return the provider itself but the value exposed by the provider, there is no problem:

build() {
  return ref.watch(provider); // OK
}

build() {
  return provider // KO
}
  • Related