【问题标题】:Shows warning: Do not use BuildContexts across async gaps显示警告:不要在异步间隙中使用 BuildContexts
【发布时间】:2023-02-19 18:35:38
【问题描述】:
if (_formKey.currentState!.validate()) {
                      try {
                        final newUser =
                            await _auth.createUserWithEmailAndPassword(
                                email: email.text, password: password.text);
                        if (newUser != null) {
                          // Navigator.push(
                          //     context,
                          //     MaterialPageRoute(
                          //       builder: (context) => DashboardScreen(),
                          //     ));
                          Navigator.pushNamed(context, 'dashboard');
                        }

                        setState(() {});
                      } catch (e) {
                        print(e);
                      }
                    }
                  },

此警告显示在 Navigator.pushNamed(context,'dashboard'); 试图导航到仪表板屏幕。

【问题讨论】:

  • 你把这个方法放在构建方法中了吗?
  • 如果您在显示“文档”的地方单击它,它会将您带到包含您的问题答案的页面。
  • 发生这种情况是因为您在异步函数中。添加 if (!mounted) return;在 Navigator.pushNamed(context, 'dashboard') 之前;

标签: flutter firebase dart


【解决方案1】:

1.您必须延迟其他过程才能完成

 Future.delayed(Duration(milliseconds: 200)).then((value) {
      Navigator.pushNamed(context, 'dashboard')
});

2.Navigator.pushNamed(context, 'dashboard')之前添加if (!mounted) return;

3.请在导航器颤动之前放置等待,因为您使用了异步方法调用,因此您必须等到该过程完成,然后您才能导航到您的页面

 await Navigator.pushNamed(context, 'dashboard');

4.此外,您可以将您的navigator存储到var中,然后使用它。

 final nav = Navigator.of(context);
 nav.pushNamed('dashboard');

【讨论】:

    猜你喜欢
    • 2021-10-22
    • 2023-01-15
    • 2022-12-31
    • 2023-02-09
    • 1970-01-01
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    相关资源
    最近更新 更多