flutter 在异步函数后导航

eblbsuwk  于 2023-05-29  发布在  Flutter
关注(0)|答案(1)|浏览(145)

我使用AutoRouter包来处理所有的导航逻辑。到目前为止,一切似乎都正常,但我遇到了以下错误:

[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: Looking up a deactivated widget's ancestor is unsafe.
At this point the state of the widget's element tree is no longer stable.
To safely refer to a widget's ancestor in its dispose() method, save a reference to the ancestor by calling dependOnInheritedWidgetOfExactType() in the widget's didChangeDependencies() method.

这发生在我点击一个按钮后,该按钮在其按下回调中具有以下逻辑:

Provider.of<AuthProvider>(context, listen: false)
                        .signIn(emailController.text, passwordController.text)
                        .then(
                          (value) => AutoRouter.of(context)
                              .popAndPush(const HomeRoute()),
                        );

我也尝试了推荐的方法:

Provider.of<AuthProvider>(context, listen: false)
                        .signIn(emailController.text, passwordController.text);
if (context.mounted) {
AutoRouter.of(context).popAndPush(const HomeRoute())
}

在这种情况下,导航逻辑永远不会运行,因为context.mounted表达式解析为false。
我意识到,当对话框或弹出窗口出现时,这个问题很常见,因为它们的上下文与脚手架的上下文不同。我也试图通过声明一个全局scaffold键来使用上下文,但也没有成功。
我,但是,使用的页面视图的第一页是一个着陆页,第二个是登录页面和第三个是注册页面。我怀疑这是问题的原因。无论如何,任何帮助都是巨大的。

px9o7tmv

px9o7tmv1#

在async函数之前保存对AutoRouter的引用,并使用它在async函数之后导航。

final router = AutoRouter.of(context);
await asyncFunction();
router.popAndPush(const HomeRoute());

相关问题