Search code examples
flutterdartsharedpreferences

How can SharedPreferences value be showed in Flutter/Dart?


I want to set sharedPreferences variables in that page.But When I call functions (ex. _getUsername) , I got error like 'Flutter: 'Future' is not a subtype of type 'String''.

How can I get and set values in that page ? Why can not show string values in widget ? This sould be my 'Edit Settings' page. I want to edit three variables username,password and url. Thanks for help.

      class ThirdRoute extends StatefulWidget {
  @override
  _ThirdRouteState createState() => _ThirdRouteState();
}

class _ThirdRouteState extends State<ThirdRoute> {
  String username = '';
  String password = '';
  String url = '';

  @override
  void initState() {
    super.initState();
    username = _getUsername();
    password = _getPassword();
    url = _getUrl();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("edit page")),
      body: Center(
        child: ListView(
          children: [
            Container(
              child: Text(username),
            ),
            Container(
              child: Text(password),
            ),
            Container(
              child: Text(url),
            ),
            FlatButton(
              onPressed: () {
                setState(() {
                  _setUsername("new username");
                  _setPassword("new password");
                  _setUrl("new url");
                });
              },
            )
          ],
        ),
      ),
    );
  }
}

_getUsername() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.getString('username');
}

_getPassword() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.getString('password').toString();
}

_getUrl() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  return prefs.getString('url').toString();
}

_setUsername(newUsername) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setString("username", newUsername);
}

_setPassword(newPassword) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setString("password", newPassword);
}

_setUrl(newUrl) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  await prefs.setString("url", newUrl);
}

Solution

  • In the initstate, run the code like this

      @override
      void initState() {
        super.initState();
        _getUsername().then((v){
          setState((){username = v});
        };
        _getPassword().then((v){
          setState((){password= v});
        };
        _getUrl().then((v){
          setState((){url= v});
        }; 
      }
    

    Now we update the value of the text fields after sharedpreferences has fetched us the value