显示警告:不要在异步间隙中使用 BuildContexts

huangapple go评论74阅读模式
英文:

Shows warning: Do not use BuildContexts across async gaps

问题

if (_formKey.currentState!.validate()) {
  try {
    final newUser =
        await _auth.createUserWithEmailAndPassword(
            email: email.text, password: password.text);
    if (newUser != null) {
      Navigator.pushNamed(context, 'dashboard');
    }

    setState(() {});
  } catch (e) {
    print(e);
  }
}
英文:
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);
                      }
                    }
                  },

this warning shown on Navigator.pushNamed(context,'dashboard');
trying to navigate to the dashboar screen.

显示警告:不要在异步间隙中使用 BuildContexts

答案1

得分: 0

  1. 你需要延迟一段时间,以便其他进程能够完成,然后执行以下操作:
Future.delayed(Duration(milliseconds: 200)).then((value) {
    Navigator.pushNamed(context, 'dashboard');
});
  1. 在执行 Navigator.pushNamed(context, 'dashboard') 之前添加 if (!mounted) return;

  2. 在使用异步方法调用时,请在导航器前面加上 await,因为您使用了异步方法调用,所以必须等待进程完成,然后才能导航到您的页面:

await Navigator.pushNamed(context, 'dashboard');
  1. 此外,您可以将您的导航器存储到一个变量中,然后使用它:
final nav = Navigator.of(context);
nav.pushNamed('dashboard');
英文:

1.
You have to put delay for other process can finish till then

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

2.
add if (!mounted) return; before Navigator.pushNamed(context, 'dashboard')

3.
Please put await before the navigator flutter because you used an asynchronously method call so you have to wait until the process is finished then you can navigate to your pages

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

4.
Also, you can store your navigator into a var and then use it.

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

huangapple
  • 本文由 发表于 2023年1月9日 13:21:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75053442.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定