How to display SharedPreferences value in Text widget in flutter?

Viewed 654

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 {
   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";
  }
2 Answers

You should use setState to update the ui when the data is loaded.

getUserCurrencySymbol().then((value) {
  setState((){
    _userCurrency = value.toString();
  });
});

You can use FutureBuilder to load data and handle loading/error states

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)),
        ]
        );
    },
)

And try to change getUserCurrencySymbol();

Future<String> getUserCurrencySymbol() {
   return MySharedPreferences.instance.getUserCurrencyValue('userCurrency');
}
Related