Search code examples
flutterproviderriverpod

Is there any ways to pass parameters in riverpod's provider


How do I pass a FirebaseAuth user to a StreamProvider in riverpod?

When using old provider package, I used to get the user.uid from FirebaseAuth and pass the variable to the StreamProvider, returning the StreamProvider if we could get the user.uid.

@override
  Widget build(BuildContext context) {
    final FirebaseAuthService authService =
        Provider.of<FirebaseAuthService>(context, listen: false);
    return StreamBuilder<User>(
      stream: authService.onAuthStateChanged,
      builder: (BuildContext context, AsyncSnapshot<User> snapshot) {
        final User loggedInUser = snapshot.data;
        if (loggedInUser != null) {
          final String userId = loggedInUser.userId;
          return MultiProvider(
            providers: <SingleChildWidget>[
              StreamProvider<User>(
                initialData: User.initialData(),
                create: (_) => DB.instance.getLoggedInUserStream(
                  loggedInUserId: userId,
                ),

Solution

  • You can use the family feature of Riverpod.

    final user = StreamProvider.family<User, String>((ref, uid) {
      // use uid to get User
      return User;
    });
    

    Then use the provider:

    useProvider(user(uid));
    

    Alternatively, you could read the value from the user provider directly from your FirebaseAuthService provider.

    final user = StreamProvider<User>((ref) {
      final stream = ref.watch(FirebaseAuthService.stream);
      // get uid from stream data
      return User;
    });