flutter - 如何在颤动的文本小部件中显示 SharedPreferences 值?
问题描述
任务是从 SharedPrefrences 中获取值并将其显示在 Text 小部件中。
这里我尝试将值存储在变量_userCurrency 中并在ListTile 中显示。问题似乎是 ListTile 以“null”值快速加载。
甚至 getUserCurrencySymbol() 也没有返回任何值。我已经尝试过 return MySharedPreferences.instance.getUserCurrencyValue('userCurrency'); 和其他可能的解决方案。
菜单.dart
late String _userCurrency;
getUserCurrencySymbol().then((value) {_userCurrency = value.toString();});
return StatefulBuilder(
builder: (BuildContext context, void Function(void Function()) setState) {
return ListView(
children: [
ListTile(title: Text(_userCurrency)),
]
) //ListView
},
); //Stateful builder
控制器.dart
Future<String> getUserCurrencySymbol() async {
return MySharedPreferences.instance.getUserCurrencyValue('userCurrency').then((value) {return value.toString();});
}
class MySharedPreferences {
MySharedPreferences._privateConstructor();
static final MySharedPreferences instance = MySharedPreferences._privateConstructor();
setUserCurrencyValue(String key, String value) async {
SharedPreferences instance = await SharedPreferences.getInstance();
instance.setString(key, value);
}
getUserCurrencyValue(String key) async {
SharedPreferences instance = await SharedPreferences.getInstance();
return instance.getString(key) ?? "Bitcoin";
}
解决方案
您可以使用FutureBuilder加载数据并处理加载/错误状态
FutureBuilder<String>(
future: getUserCurrencySymbol(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if(snapshot.hasError) {
//fixme just to check an error
print("Error: ${snapshot.error}");
return Text("Error");//or what you want
}
if (!snapshot.hasData) {
return CircularProgressIndicator();//or what you want
}
return ListView(
children: [
ListTile(title: Text(snapshot.data)),
]
);
},
)
并尝试更改 getUserCurrencySymbol();
Future<String> getUserCurrencySymbol() {
return MySharedPreferences.instance.getUserCurrencyValue('userCurrency');
}
推荐阅读
- python - 为什么python循环会产生双重结果?
- javascript - 嵌套在另一个未运行的函数中的验证函数
- sqlite - 我可以在 SQLite/SQLite 的条件结构中的 SELECT 之外使用 CASE WHEN 吗?
- java - 替代已弃用的 chromedriverchromemapfile
- google-apps-script - 如何授权触发表单提交等事件的脚本?
- python - 如何创建 TensorFlow 模型的检查点文件?
- javascript - 如何在 D3 中创建一个可移动的滑块来选择字符串的一部分
- python - Matplotlib 花式断条
- sql-server - 如何从不同的 SQL Server 查询多个数据库
- python - 获取已发送请求的跟踪 ID