Flutter Provider - StreamProvider depending on another StreamProvider

106

you can do it by using the first stream as dependency of the second like below

StreamProvider<FrediUser>(
      create: (context) => firstStream(),
      initialData: 'initialData',
      builder: (context, child) {
        return StreamProvider(
          create: (context) => secondStream(
              context.watch<FrediUser>(),
          ),
          initialData: 'initialData',
          child: child,
        );
      },
    )
Share:
106
Tomas Ward
Author by

Tomas Ward

I love programming.

Updated on January 04, 2023

Comments

  • Tomas Ward
    Tomas Ward 10 months

    TLDR How to use data from one stream provider to call another?

    Background of the Problem

    Hello! I have this Firebase Realtime Database Structure

    Users Database Structure.

    Each user's Group IDs are stored here. They can be accessed to then query the following 'Groups' Json tree.

    Groups database structure

    Here there is all the data for a group, which multiple users can access. The structure is like this to avoid data redundancy.

    Problem

    I am using the Provider package. To get the user data, it works like a charm:

    1. I use a Stream Provider
    2. I query the database with an onValue function --> Stream.
    3. I map the data from that Stream to a class and transform it to that class's structure using fromMap() factory function
    Stream<FrediUser> currentUserDataStream() {
        var userRef = 
        FirebaseDatabase.instance.reference().child('Users').
        child(currentUserID!);
        return userRef.onValue.map((event) => 
        FrediUser.fromMap(event.snapshot.value));
    }
    

    That works if I have to access the User map and its nested children. But as illustrated in the example above, what happens if I have to access the User map first and then the Groups map? I want to do all of this using stream providers.

  • Tomas Ward
    Tomas Ward over 1 year
    With a bit of tweaking for my use case, this is the correct answer. I was able to get data from the first stream and pass it to the second. For example, I did a first tream of type User? where I could access the uid of the current logged in user. Then my second stream (with all the user data) of type FrediUser had an updated uid to look up.
  • Tomas Ward
    Tomas Ward over 1 year
    Now I will apply it to the actual case in question, but I am sure it will work the same way