Search code examples
flutterdartsharedpreferences

Sharedpreference value not being displayed in UI


I'm retrieving User data from the Sharedpreference, but unable to display it in the UI text section, but only if i hit the hot reload the retreived data is showing in the UI text.

 String username = "";

@override
  void initState() {
    getPrefs();
    super.initState();
  }
getPrefs() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    username = prefs.getString('user_name') ?? '';
  }
 @override
  Widget build(BuildContext context) {
    return Scaffold(
 body: Container(
 child: Text(username == "" ? "Username" : username, style: TextStyle(fontWeight: FontWeight.bold,),),
)
);
}

Solution

  • getPrefs is called asynchronously. Therefore the UI is drawn before the username value is retrieved.

    To fix that just call setState once you have the username value, which will force the UI to refresh.

    Here is a quick implementation:

    getPrefs() async {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      setState(() {
        username = prefs.getString('user_name') ?? '';
      });
    }