Flutter 向我发出警告“不要跨异步间隙使用‘BuildContext’。尝试重写代码以不使用‘BuildContext’,或者通过‘mounted’检查来保护使用”。该警告在我的应用程序中出现了两次,我无法通过添加“安装守卫”来使它们消失。下面是一个完整的独立应用程序,演示了我的应用程序的简单版本。你能告诉我解决这个问题的理想方法是什么吗?如果是“骑警”,我应该把它们放在哪里?
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Search History Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(),
);
}
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Search History'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
clearEnglishHistory(context);
},
child: const Text('Clear History'),
),
),
);
}
Future<void> clearEnglishHistory(BuildContext context) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool confirmClear = await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text('Confirmation'),
content: const Text('Do you really want to clear search history?'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop(false);
},
child: const Text('No'),
),
TextButton(
onPressed: () {
Navigator.of(context).pop(true);
},
child: const Text('Yes'),
),
],
);
},
);
if (confirmClear == true) {
await prefs.remove('english history');
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('History cleared'),
));
}
}
}
您需要使用 lint 消息禁用该消息,或者您可以在显示小吃栏之前添加已安装的检查。像这样的东西:
if (confirmClear == true) {
await prefs.remove('english history');
if(!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('History cleared'),
));
}