导航后流构建器未更新 [英] stream builder is not updating after navigation
问题描述
我正在使用流构建器来检测用户是否登录.
I am using a stream builder to detect if user logged in or not.
return StreamBuilder<User>(
stream: AuthService().user,
builder: (context, snapshot) {
if (snapshot.hasData)
return SectionWrapper();
else
return Authentication();
});
这是我正在使用的流
Stream<User> get user {
return _auth.onAuthStateChanged.map(_userFromFirebaseUser);
}
//create user object based on firebase user
User _userFromFirebaseUser(FirebaseUser user) {
return user != null ? User(uid: user.uid, email: user.email) : null;
}
在部分包装中,有2个按钮可导航到应用程序的两个不同部分,当我在这些部分之一中使用注销方法时,流构建器未更新,并且需要刷新才能更新状态.
in the section wrapper, there are 2 buttons that navigates to two different sections of the app, when I use sign out method in one of these sections, the stream builder is not updating, and it requires refresh to update the state.
我还尝试在部分包装中放置一个按钮以退出,该按钮可以正常工作并更新UI,然后再导航至其中一个部分.
also i tried to put a button in section wrapper to sign out, it works and update UI before I navigate to one of the sections.
这是sectionWrapper()小部件树.
and this is the sectionWrapper() widget tree.
Column(
children: <Widget>[
CupertinoButton(
child: Text('Donation & Selling Section'),
onPressed: () {
Navigator.pushReplacementNamed(
context, Section1.routeName,
arguments: user);
}),
CupertinoButton(
child: Text('Bookstores Section'),
onPressed: () {
Navigator.pushReplacementNamed(
context, Section2.routeName);
}),
//works before navigation, does not work after navigation back here
CupertinoButton(
child: Text('Sign out'),
onPressed: () async {
await AuthService().signOut();
}),
],
),
我还尝试对消费者使用流提供程序,但最终遇到了同样的问题.
I also tried to use stream provider with consumer and I ended with the same problem.
class Wrapper extends StatelessWidget {
static const String routeName = '/';
@override
Widget build(BuildContext context) {
final user = Provider.of<User>(context);
return user == null ? Authentication() : SectionWrapper();
}
}
我用流提供程序包装了材质应用.
I wrapped material app with a stream provider.
MultiProvider(
providers: [
StreamProvider<User>.value(value: AuthService().user),
//other providers
],
child: MaterialApp(
推荐答案
您的条件未在子页面中进行测试.您应该在sectionWrapper()页面中调用Provider.of.
Your conditional Is not being tested in the sub page. You should call Provider.of in the sectionWrapper() page.
您是说:
- 如果用户已登录,请构建sectionWrapper小部件
- 如果用户未登录构建身份验证小部件.
就是那个构建方法.构建完成后,您需要说出下一步要做什么.
That is it for that build method. Once that is built, you need to say what you want to do next.
例如.在下一个屏幕的小部件树上方,像您一样设置provider.of.然后,如果值更改,提供程序将强制对该屏幕的构建方法进行重建.
Eg. On the next screen, above your widget tree, set provider.of like you did. Then, if the value changes, provider will force a rebuild for that screen’s build method.
这篇关于导航后流构建器未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!