Search code examples
fluttersharedpreferencesflutter-layout

Flutter : How to setText from Sharedpreference data?


I've a small question for you all, I want to showing data from sharepref variable to UI Widget. I just now learn flutter and still confused.

this is my sharedpref to read data.

void loginStatus() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    String user = prefs.getString('username');
    String pasw = prefs.getString('password');
  }

and I want to "user" is set in UI widget Text($user), I hope you guys can give some reference or some code to me, thanks guys for your reason and I hope you well in this condition


Solution

  • You can define your var at top of the class to make them accessible in the class

    String user='';
    

    then call your loginStatus in initState()

    @override
    void initState() {
      super.initState();
      loginStatus(); 
    }
    

    then append your loginstatus as follows

    void loginStatus() async {
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      setState()({
        user = prefs.getString('username');
        pasw = prefs.getString('password');
      }); 
    }
    

    now you can use Text("$user") anywhere.