将两个流合并到一个StreamProvider中
我有两个流:
-
Stream< FirebaseUser>FirebaseAuth.instance.onAuthStateChanged
-
Stream< User>userService.streamUser(String uid)
我的userService需要将经过身份验证的FirebaseUser的uid作为参数.
My userService requires the uid of the authenticated FirebaseUser as a parameter.
由于我可能需要在应用程序的多个部分中访问streamUser()流,因此我希望它成为项目根目录的提供者.
Since I will probably need to access the streamUser() stream in multiple parts of my app, I would like it to be a provider at the root of my project.
这是我的main.dart的样子:
This is what my main.dart looks like:
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
var auth = FirebaseAuth.instance;
var userService = new UserService();
return MultiProvider(
providers: [
Provider<UserService>.value(
value: userService,
),
],
child: MaterialApp(
home: StreamBuilder<FirebaseUser>(
stream: auth.onAuthStateChanged,
builder: (context, snapshot) {
if (!snapshot.hasData) return LoginPage();
return StreamProvider<User>.value(
value: userService.streamUser(snapshot.data.uid),
child: HomePage(),
);
}),
),
);
}
}
问题在于,当我导航到另一个页面时,MaterialApp下面的所有内容都被更改,并且失去了StreamProvider的上下文.
The issue is that when I navigate to a different page, everything below the MaterialApp is changed out and I lose the context with the StreamProvider.
是否可以将StreamProvider添加到MultiProvider provider-list?因为当我尝试时,我还必须为FirebaseUser创建另一个onAuthStateChanged流,并且我不知道如何将它们组合为一个提供程序.
Is there a way to add the StreamProvider to the MultiProvider providers-list? Because when I try, I also have to create another onAuthStateChanged stream for the FirebaseUser and I don't know how to combine them into one Provider.
所以这似乎可以正常工作:
So this seems to work fine:
StreamProvider<User>.value(
value: auth.onAuthStateChanged.transform(
FlatMapStreamTransformer<FirebaseUser, User>(
(firebaseUser) => userService.streamUser(firebaseUser.uid),
),
),
),
如果在某些情况下有人对此表示怀疑,请告诉我.
If anybody has doubts about this in certain edge cases, please let me know.