【发布时间】:2022-01-19 12:21:41
【问题描述】:
我有一个设置页面,其中保存了 SavedPreferences 中密钥文件的路径。也可以在这个设置页面重新定义keyfile的路径。
class Settings extends StatefulWidget {
const Settings({Key? key}) : super(key: key);
@override
_SettingsState createState() => _SettingsState();
}
class _SettingsState extends State<Settings> {
void initState() {
getSettings();
super.initState();
}
void getSettings() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
_keyPath = prefs.getString('keyPath')!;
_keyFile = _keyPath.split('/').last;
}
String _keyPath = '';
String _keyFile = '';
Future<void> openFile() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
_keyPath = (await FlutterFileDialog.pickFile())!;
setState(() {
print(_keyPath);
_keyFile = _keyPath.split('/').last;
prefs.setString('keyPath', _keyPath);
});
}
@override
Widget build(BuildContext context) {
getSettings();
return Scaffold(
appBar: AppBar(
title: const Text('Settings'),
),
body: Column(
children: [
Row(
children: [
Expanded(
child: Column(
children: [
Text('Key File: '),
Text(_keyFile),
],
),
),
Expanded(
child: ElevatedButton(onPressed: openFile, child: Text('Open')),
)
],
)
],
),
);
}
}
这在第一次初始化时工作正常,但是当小部件已经初始化并且第二次导航回来时,当导航回此页面时,我无法使用 SharedPreferences 中保存的键。
我知道我在重新导航时获得了 _keyFile 和 _keyPath 的值
String _keyPath = '';
String _keyFile = '';
在没有 initState 的情况下重新导航到小部件以使用 SharedPreferences 时,无法弄清楚如何调用异步函数
我想这应该通过状态来完成,而不是从 SharedPreferences 中查询项目,但我不知道如何准确地做到这一点。
【问题讨论】: