简体   繁体   中英

How to have multiple app-wise streams in flutter, when one stream depends on the other?

I have two streams whose data I need to use app-wise.

My main obstacle is that one of the streams needs the other's data, thus, I cannot call a MultiProvider .

My current implementation looks as follows, however I do not like it: I think it is not ok to return multiple MaterialApps. Actually, my app turns black for a while, when changing from one MaterialApp to the other.

This is my current implementation:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return StreamProvider<User>.value( //First, listen to the User Stream here
      value: AuthService().user,
      child: MyMaterialApp(),
    );
  }
}


class MyMaterialApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    final user = Provider.of<User>(context); //To get the user data here, and use it bellow

    if (user == null){ //If I don't have the User yet, return Loading()
      return MaterialApp(
        debugShowCheckedModeBanner: false,
        title: "myApp",
        theme: myTheme(),
        home: Loading(),
      );
    } else {
      return StreamProvider<UserData>.value(
        value: DatabaseService(uid: user.uid).userData, //Once I have it, use it to build the UserData Stream
        child: MaterialApp(
            debugShowCheckedModeBanner: false,
            title: "myApp",
            theme: myTheme(),

            home: Wrapper(),
            initialRoute: '/',
            routes: {
              '/home': (context) => Wrapper(),
              //...
            }
        ),
      );
    }
  }
}

Thank you very much!

Based on this post https://github.com/rrousselGit/provider/issues/222 I was able to solve it by doing the following:

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        StreamProvider<User>.value(value: AuthService().user),
        Consumer<User>(
          builder: (context, user, child) => StreamProvider<UserData>.value(
            value: DatabaseService(uid: user == null ? null : user.uid).userData,
            child: child,
          ),
        )
      ],
      child: MaterialApp(
          debugShowCheckedModeBanner: false,
          title: "myApp",
          theme: myTheme(),

          home: Wrapper(),
          initialRoute: '/',
          routes: {
            '/home': (context) => Wrapper(),
            //...
          }
      ),
    );
  }
}

The Consumer listens to the User data and passes it to the next Stream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM