The task is to get value from SharedPrefrences and display it in the Text widget.
Here I tried to store the value in the variable _userCurrency and display it in ListTile. The problem seems that the ListTile loads quickly with the value "null".
Even getUserCurrencySymbol() isn't returning any value. I have already tried return MySharedPreferences.instance.getUserCurrencyValue('userCurrency'); and other possible solutions.
menu.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
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";
}
CodePudding user response:
You should use setState
to update the ui when the data is loaded.
getUserCurrencySymbol().then((value) {
setState((){
_userCurrency = value.toString();
});
});
CodePudding user response:
You can use FutureBuilder to load data and handle loading/error states
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)),
]
);
},
)