我正在尝试检测该用户不再经过身份验证并将用户重定向到登录。这就是我的做法
Widget build(BuildContext context) {
return FutureBuilder(
future: _getData(context),
builder: (context, snapshot) {
try {
if (snapshot.hasError && _isAuthenticationError(snapshot.error)) {
Navigator.push(context, MaterialPageRoute(builder: (context) => LoginView()));
}
不幸的是,在构建时进行导航不起作用。它抛出此错误
flutter: setState() or markNeedsBuild() called during build.
flutter: This Overlay widget cannot be marked as needing to build because the framework is already in the
flutter: process of building widgets. A widget can be marked as needing to be built during the build
我不能只返回LoginView
小部件,因为父小部件包含应用栏和浮动按钮,登录视图需要在没有这些控件的情况下显示。我需要导航。
有可能做到吗?
将其包装在Future.microtask
中。这将安排它在下一个异步任务周期(即build
完成后(发生。
Future.microtask(() => Navigator.push(
context,
MaterialPageRoute(builder: (context) => LoginView())
));
颤振中的流
通常的做法是使用发生用户更改的流。 当用户注销时,他会检测到该更改,并可以将其定向到另一个窗口。
这里的问题:
snapshot.hasError && _isAuthenticationError(snapshot.error)
代替这个,使用 OR
snapshot.hasError || _isAuthenticationError(snapshot.error)