title: Flutter sharedpreferences get data after app restart
body: <p>I have implemented the shared preferences which is used to store the current logged in user, i can get the username in each and every time after the user log in, however after the app is restart, the username is gone but the current user is still logged in. I attached the gif to have better explaination. Below is my code.</p>
  
  <p><a href="https://i.stack.imgur.com/MaMjb.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MaMjb.gif" alt="enter image description here"></a></p>
  
  <p><strong>main.dart</strong></p>
  
  <pre><code>Future&lt;void&gt; main() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  var usernamee = prefs.getString('yourusername');
  print(usernamee);
  runApp(MaterialApp(
    home: usernamee == null
        ? LoginPage()
        : MainPage(
            username: username,
          )));
  }
  
  String username = '';
  </code></pre>
  
  <p><strong>loginpage.dart</strong></p>
  
  <pre><code>class LoginPage extends StatefulWidget {
  @override
  LoginPageState createState() =&gt; LoginPageState();
  }
  
  class LoginPageState extends State&lt;LoginPage&gt; {
  
  TextEditingController user = new TextEditingController();
  TextEditingController pass = new TextEditingController(); 
  
  String txtmsg = '';
  
  @override
  void initState() {
  super.initState();
  }
  
  Future&lt;bool&gt; _onWillPop() {
  return showDialog(
        context: context,
        builder: (context) =&gt; new AlertDialog(
              title: new Text('Are you sure?'),
              content: new Text('Do you want to exit an App'),
              actions: &lt;Widget&gt;[
                new FlatButton(
                  onPressed: () =&gt; Navigator.of(context).pop(false),
                  child: new Text('No'),
                ),
                new FlatButton(
                  onPressed: () =&gt; Navigator.of(context).pop(true),
                  child: new Text('Yes'),
                ),
              ],
            ),
      ) ??
      false;
  }
  
  Future&lt;List&gt; _login() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  
  final response =
      await http.post("http://192.168.1.2/login/login.php", body: {
    "username": user.text,
    "password": pass.text,
  });
  
  var datauser = json.decode(response.body);
  
  if (datauser.length == 0) {
    setState(() {
      txtmsg = "Username or password is wrong, please try again.";
      Fluttertoast.showToast(msg: txtmsg);
    });
  } else {
    if (datauser[0]['level'] == 'admin') {
      prefs.setString('yourusername', '$username');
      Navigator.pushReplacement(
          context,
          MaterialPageRoute(
              builder: (BuildContext ctx) =&gt; MainPage(
                    username: username,
                  )));
    }
  
    setState(() {
      username = datauser[0]['username'];
    });
  }
  print(username);
  return datauser;
  }
  
  final logo = Hero(
  tag: 'hero',
  child: CircleAvatar(
    backgroundColor: Colors.transparent,
    radius: 48.0,
    child: Image.asset('assets/images/ic_launcher.png'),
  ),
  );
  
  final forgotLabel = FlatButton(
  child: Text(
    'Forgot password?',
    style: TextStyle(color: Colors.black54),
  ),
  onPressed: () {},
  );
  
  @override
  Widget build(BuildContext context) {
  ScreenUtil.instance = ScreenUtil.getInstance()..init(context);
  ScreenUtil.instance =
      ScreenUtil(width: 750, height: 1334, allowFontScaling: true);
  
  return WillPopScope(
      onWillPop: _onWillPop,
      child: Scaffold(
          body: Center(
        child: ListView(
          shrinkWrap: true,
          padding: EdgeInsets.only(left: 24.0, right: 24.0),
          children: &lt;Widget&gt;[
            logo,
            SizedBox(height: 48.0),
            Center(
              child: FormUI(),
            )
          ],
        ),
      )));
  }
  
  Widget FormUI() {
  return new Column(
    children: &lt;Widget&gt;[
      TextFormField(
        controller: user,
        decoration: InputDecoration(
          hintText: 'Username',
          contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 20.0),
          border:
              OutlineInputBorder(borderRadius: BorderRadius.circular(20.0)),
        ),
        validator: validateusername,
      ),
      SizedBox(height: 18.0),
      TextFormField(
        controller: pass,
        obscureText: true,
        decoration: InputDecoration(
          hintText: 'Password',
          contentPadding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 20.0),
          border:
              OutlineInputBorder(borderRadius: BorderRadius.circular(20.0)),
        ),
        validator: validatepassword,
      ),
      SizedBox(
        height: ScreenUtil.getInstance().setHeight(40),
      ),
      RaisedButton(
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(24),
        ),
        onPressed: () =&gt; _login(),
        padding: EdgeInsets.all(12),
        color: Colors.lightBlueAccent,
        child: Text('Log In', style: TextStyle(color: Colors.white)),
      ),
      forgotLabel,
    ],
  );
  }
  
  String validateusername(String value) {
  if (value.length == 0) {
    return "Name is Required";
  }
  
  return null;
  }
  
  String validatepassword(String value) {
  if (value.length == 0) {
    return "Password is Required";
  }
  
  return null;
  }
  }
  </code></pre>
  
  <p><strong>mainpage.dart</strong></p>
  
  <pre><code>class MainPage extends StatefulWidget {
  MainPage({this.username});
  final String username;
  
  @override
  MainPageState createState() =&gt; MainPageState();
  }
  
  class MainPageState extends State&lt;MainPage&gt; {
  Future&lt;bool&gt; _onWillPop() {
  return showDialog(
        context: context,
        builder: (context) =&gt; new AlertDialog(
              title: new Text('Are you sure?'),
              content: new Text('Do you want to exit an App'),
              actions: &lt;Widget&gt;[
                new FlatButton(
                  onPressed: () =&gt; Navigator.of(context).pop(false),
                  child: new Text('No'),
                ),
                new FlatButton(
                  onPressed: () =&gt; Navigator.of(context).pop(true),
                  child: new Text('Yes'),
                ),
              ],
            ),
      ) ??
      false;
  }
  
  void showWifiAlert() async {
  var wifiEnabled = await getWifiStatus();
  if (wifiEnabled) {
    //Do stuff
  } else {
    AlertDialog(
      title: Center(
        child: Text('Alert'),
      ),
      content: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: &lt;Widget&gt;[
          Expanded(
            child: Text(
              'Please connect to the internet',
              textAlign: TextAlign.center,
              style: TextStyle(
                color: Colors.red,
              ),
            ),
          )
        ],
      ),
      actions: &lt;Widget&gt;[
        FlatButton(
          child: Text(
            'Ok',
          ),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  }
  }
  
  Future&lt;bool&gt; getWifiStatus() async {
  try {
    final result = await InternetAddress.lookup('google.com');
    if (result.isNotEmpty &amp;&amp; result[0].rawAddress.isNotEmpty) {
      print('connected');
      return true;
    }
  } on SocketException catch (_) {
    print('not connected');
    return false;
  }
  }
  
  @override
  void initState() {
  super.initState();
  
  }
  
  @override
  Widget build(BuildContext context) {
  String username;
  print(username);
  showWifiAlert();
  
  return WillPopScope(
    onWillPop: _onWillPop,
    child: Scaffold(
        appBar: AppBar(
          title: Text('My App'),
        ),
        body: Center(
          child: Text(
            widget.username,
          ),
        ),
        drawer: new DrawerOnly()),
  );
  }
  }
  
  class DrawerOnly extends StatefulWidget {
  @override
  DrawerOnlyState createState() =&gt; DrawerOnlyState();
  }
  
  class DrawerOnlyState extends State&lt;DrawerOnly&gt; {
  @override
  Widget build(BuildContext ctxt) {
  return new Drawer(
      child: new ListView(
    children: &lt;Widget&gt;[
      new UserAccountsDrawerHeader(
        accountName: Text('$username'),
        accountEmail: null,
        currentAccountPicture: CircleAvatar(
          child: FlutterLogo(size: 42.0),
          backgroundColor: Colors.white,
        ),
      ),
      new ListTile(
        leading: Icon(Icons.library_music),
        title: Text('Fragment 1'),
        onTap: () {
          Navigator.pop(ctxt);
          Navigator.push(ctxt,
              new MaterialPageRoute(builder: (ctxt) =&gt; new FirstFragment()));
        },
      ),
      new ListTile(
        leading: Icon(Icons.movie),
        title: Text('Fragment 2'),
        onTap: () {
          Navigator.pop(ctxt);
          Navigator.push(ctxt,
              new MaterialPageRoute(builder: (ctxt) =&gt; new SecondFragment()));
        },
      ),
      new ListTile(
        leading: Icon(Icons.exit_to_app),
        title: Text('Logout'),
        onTap: () async {
          SharedPreferences prefs = await SharedPreferences.getInstance();
          prefs.remove('yourusername');
          Navigator.pushReplacement(ctxt,
              MaterialPageRoute(builder: (BuildContext ctx) =&gt; LoginPage()));
          /* Navigator.pop(ctxt);
          Navigator.pushReplacementNamed(ctxt, '/landingpage'); */
        },
      ),
    ],
  ));
  }
  }
  </code></pre>
  
  <p>How do i able to get the username even the app is restarted?</p>