我的Flutter应用里有个按钮

onPressed: () async {
  try {
    final newUser = await _auth.createUserWithEmailAndPassword(email: email, password: password);
    if (newUser.user != null) {
       await Future.delayed(Duration.zero);
       Navigator.of(context).pushNamed(ChatScreen.id);
    }
  } catch (e) {
    print(e);
  }
},

IDE报告"不要跨同步间隙使用BuildContext." 我做错了什么?

推荐答案

When doing asynchronous tasks during widget's synchronous operations, you must check the widget is still available.

对于您的情况,请在导航器行之前添加此行

if (!mounted) return;

通过这样做,您可以判断当前的Widget是否已装载并可用.如果正在重建或销毁Widget,则判断它是否已装载将返回FALSE.

If it returns true it means the Widget is ready and you can use async / sync tasks almost everywhere.

Flutter相关问答推荐

Flutter ReorderableListView在可滚动父级中无法完美工作

我怎样才能判断一个字符串值是否为空(&Q;&Q;)?

如何在Firebase项目中更改包名称和包ID

Flutter -如何停止块监听程序在后台堆栈中运行

CLI数据库连接后将SHA-1密钥添加到Firebase项目

如何使文本表格域在抖动中变圆?

为Android生成时出现Flutter 错误:给定资源值的<;COLOR&>无效

从图标启动器打开时,VSCode未检测到Web设备

构建上下文不能跨异步间隙使用

Flutter ListView 在调用 setState 后未更新

Flutter ImagePicker - 在 onPressed 中异步获取图像显示 lint 警告

是否可以在 flutter 应用程序中使用 jetpack compose?

为什么 appBar 小部件在 flutter 中不是常量

底部工作表顶部的一块 Flutter

Flutter Bloc 使用 Cubit 监听流和emits 状态

如何将金钱格式化为数以百万计的Flutter 动?

Flutter HLS .m3u8 视频无法实时播放

如何在 Flutter 中使用简写 IF 禁用单选按钮?

根据索引/变量更改小部件的 colored颜色

Flutter audioplayers错误-单击音频按钮时不播放音频