如何在Flutter的widget build期间进行导航?

24

我正在尝试检测用户是否已注销并将其重定向到登录页面。以下是我的方法:

  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小部件,因为父部件包含应用栏和浮动按钮,而登录视图需要在没有这些控件的情况下显示...我需要导航。

这可行吗?


用户如何登录?是通过 Firebase 吗? - DomingoMG
3个回答

56

将其包装在 Future.microtask 中。这将安排它在下一个异步任务循环中执行(即在 build 完成后执行)。

Future.microtask(() => Navigator.push(
  context, 
  MaterialPageRoute(builder: (context) => LoginView())
));

但在这种情况下,我遇到了一个无限循环。你还有其他的方法可以做到吗? - Valary o
1
@Valaryo Future.microtask 只会触发一次,所以如果你做得对的话,循环是不可能的。我唯一能想象到这会导致无限循环的方式是,如果你正在使用它导航到你已经在的页面并且加载页面是触发导航的原因。还可能存在一个问题,如果你试图在 build 方法期间导航,并且小部件正在多次重建,那么在第一个触发后,你将继续排队导航。(这就是为什么在 build 方法中执行非 UI 操作通常是个坏主意的原因。) - Abion47
所以我尝试重定向到登录页面,使其全屏并保持静态。但我的登录不在登录页面上,我已经尝试将其放在页脚和顶级包装器中。 - Valary o
我使用 Provider 监听状态。你有什么想法可以解决吗? - Valary o
谢谢。这个很棒! - Jeremi
显示剩余2条评论

0

Flutter中的流

通常情况下,使用流来处理用户更改。 当用户注销时,检测到该更改并可以将其重定向到另一个窗口。


-3

问题在这里:

snapshot.hasError && _isAuthenticationError(snapshot.error)

不要使用这个,而是使用 OR

snapshot.hasError || _isAuthenticationError(snapshot.error)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接