錯誤信息:
Don't use 'BuildContext's across async gaps. (Documentation) Try rewriting the code to not use the 'BuildContext', or guard the use with a 'mounted' check.
為了處理“不建議在異步操作中使用 BuildContext”的警告,您需要確保在異步操作完成后,BuildContext 仍然有效??梢允褂?mounted 屬性來檢查 BuildContext 是否有效,mounted 屬性在 StatefulWidget 中可用,表示當(dāng)前小部件是否仍然在小部件樹中。
修改后的代碼示例
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('提示'),
content: Text('是否確認操作?'),
actions: [
TextButton(
onPressed: () {
// 關(guān)閉彈框
Navigator.of(context).pop();
// 等待3秒后檢查小部件是否仍然存在
Future.delayed(Duration(seconds: 3), () {
if (context.mounted) {
Navigator.of(context).pop(); // 返回上一個頁面
}
});
},
child: Text('確認'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop(); // 只是關(guān)閉彈框
},
child: Text('取消'),
),
],
);
},
);
說明:
-
context.mounted: 這個檢查確保在延遲操作后,BuildContext仍然有效。如果小部件已經(jīng)被銷毀(例如,用戶導(dǎo)航到了其他頁面),Navigator調(diào)用不會發(fā)生,從而避免使用無效的BuildContext。 - 這個方法避免了在異步操作完成后直接使用
BuildContext,而不檢查其有效性。
請確保這段代碼放在一個 StatefulWidget 中,因為 mounted 屬性在 StatefulWidget 中可用。如果您使用的是 StatelessWidget,需要將其轉(zhuǎn)換為 StatefulWidget 以訪問 mounted 屬性。