[英]How to display SharedPreferences value in Text widget in flutter?
The task is to get value from SharedPrefrences and display it in the Text widget.任务是从 SharedPrefences 获取值并将其显示在 Text 小部件中。
Here I tried to store the value in the variable _userCurrency and display it in ListTile.在这里,我尝试将值存储在变量 _userCurrency 中并将其显示在 ListTile 中。 The problem seems that the ListTile loads quickly with the value "null".
问题似乎是 ListTile 以“null”值快速加载。
Even getUserCurrencySymbol() isn't returning any value.甚至 getUserCurrencySymbol() 也不返回任何值。 I have already tried return MySharedPreferences.instance.getUserCurrencyValue('userCurrency');
我已经尝试过return MySharedPreferences.instance.getUserCurrencyValue('userCurrency'); and other possible solutions.
和其他可能的解决方案。
menu.dart菜单.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
controller.dart控制器.dart
Future<String> getUserCurrencySymbol() async {
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";
}
You should use setState
to update the ui when the data is loaded.您应该在加载数据时使用
setState
来更新 ui。
getUserCurrencySymbol().then((value) {
setState((){
_userCurrency = value.toString();
});
});
You can use FutureBuilder to load data and handle loading/error states您可以使用FutureBuilder加载数据并处理加载/错误状态
FutureBuilder<String>(
future: getUserCurrencySymbol(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (!snapshot.hasData) {
return CircularProgressIndicator();//or what you want
}
return ListView(
children: [
ListTile(title: Text(snapshot.data)),
]
);
},
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.