【问题标题】:Flutter "Do not use BuildContexts across async gaps"Flutter \"不要跨异步间隙使用 BuildContexts\"
【发布时间】:2023-01-15 09:51:23
【问题描述】:

基本上,当用户在对话框中按下注销时,我想返回到我的 LoginView。

onSelected: (value) async {
              switch (value) {
                case MenuAction.logout:
                  final shouldLogout = await showLogOutDialog(context);
                  final navigator = Navigator.of(context);
                  if (shouldLogout) {
                    await FirebaseAuth.instance.signOut();
                    navigator.pushNamedAndRemoveUntil(
                      '/login',
                      (route) => false,
                    );
                  }
              }
            },

显示注销对话框功能:

Future<bool> showLogOutDialog(BuildContext context) {
  return showDialog<bool>(
    context: context,
    builder: (context) {
      return AlertDialog(
        title: const Text('Sign out'),
        content: const Text('Are you sure you want to sign out?'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop(false);
            },
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () {
              Navigator.of(context).pop(true);
            },
            child: const Text('Logout'),
          ),
        ],
      );
    },
  ).then((value) => value ?? false);

我收到此错误:“不要在异步间隙中使用 BuildContexts。”。

谁能帮助我?

提前致谢!

【问题讨论】:

  • 我发现的一些答案告诉我只需将最终的 navigator = Navigator.of(context) 放在最终的 shoulLogout 之上,它似乎可以工作,但后来其他人说这不是正确的方法。因为它隐藏了相关的分析器警告,它只是分析器中的一个错误。

标签: flutter dart


【解决方案1】:

这是不安全的,请尝试检查是否未安装小部件,如 Flutter YouTube Channel 所示。

if (!mounted) return
Navigator.of(context);

【讨论】:

    猜你喜欢
    • 2021-10-22
    • 2022-12-31
    • 2023-02-19
    • 2023-02-09
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 1970-01-01
    相关资源
    最近更新 更多