title: Flutter: Keep user logged in after app closes and reopen
body: <p>I'm a beginner and requesting help. I tried to find the answer but sadly cannot find the answer that I'm looking for. I'm building an app where users can see the homepage and other parts of the app when they are not logged in. This part I have working but only when I close the app and restart it I need to log in again. This is of course not ideal. I tried to look for the <code>SharedPreferences</code> but all examples I can find are with a login function for the whole app and I can't figure out how to get it working in my app. Below is the code I have so far. All help is appreciated and thank you all in advance!</p>
  
  <p>(Apologies for posting so much code but it might help!)</p>
  
  <blockquote>
    <p>Main.dart</p>
  </blockquote>
  
  <pre><code>import 'package:flutter/material.dart';
  import 'package:provider/provider.dart';
  import 'package:reboo1/services/firebaseauthservice.dart';
  import 'package:reboo1/services/users.dart';
  
  void main() =&gt; runApp(new MyApp());
  
  class MyApp extends StatelessWidget {
    // This widget is the root of your application.
    @override
    Widget build(BuildContext context) {
      return StreamProvider&lt;User&gt;.value(
        value: AuthService().user,
             child: MaterialApp(
              title: 'Rèboo',
              theme: new ThemeData(
                primarySwatch: Colors.blue,
              ),
                home:HomePage(),
            ),
          );
        }
      } 
  </code></pre>
  
  <blockquote>
    <p>HomePage.dart</p>
  </blockquote>
  
  <pre><code>import 'package:firebase_auth/firebase_auth.dart';
  import 'package:flutter/material.dart';
  import 'package:provider/provider.dart';
  import 'package:reboo1/authenticate/signin.dart';
  import 'package:reboo1/authenticate/signout.dart';
  import 'package:reboo1/models/drawerlogin.dart';
  import 'package:reboo1/models/drawerlogout.dart';
  import 'package:reboo1/services/firebaseauthservice.dart';
  import 'package:reboo1/services/users.dart';
  
  class DrawerItem {
    String title;
    IconData icon;
    DrawerItem(this.title, this.icon);
  }
  
  class HomePage extends StatefulWidget {
    final drawerItems = [
      new DrawerItem("Rèboo", Icons.home),
      new DrawerItem("Inbox", Icons.mail_outline),
      new DrawerItem("Profile", Icons.person_outline),
      new DrawerItem("Reservations", Icons.event_note),
      new DrawerItem("Favorites", Icons.favorite_border),
      new DrawerItem("Vouchers", Icons.card_giftcard),
      new DrawerItem("Invite Friends", Icons.person_add),
      new DrawerItem("Settings", Icons.settings),
      new DrawerItem("FAQ", Icons.help_outline),
      new DrawerItem("Terms &amp; Conditions", Icons.assignment),
      new DrawerItem("Sign out", Icons.exit_to_app),
    ];
  
    @override
    State&lt;StatefulWidget&gt; createState() {
      return new HomePageState();
    }
  }
  
  class HomePageState extends State&lt;HomePage&gt; {
  
    final GlobalKey&lt;ScaffoldState&gt; _scaffoldKey = new GlobalKey&lt;ScaffoldState&gt;();
    int _selectedDrawerIndex = 0;
    var _setIcon = Icons.person;
    var drawer;
    String uid;
  
    _getDrawerItemWidget(int pos) {
      switch (pos) {
        case 0:
          return new Reboo();
        case 1:
          return new Inbox();
        case 2:
          return new Profile();
        case 3:
          return new Reservations();
        case 4:
          return new Favorites();
        case 5:
          return new Vouchers();
        case 6:
          return new InviteFriends();
        case 7:
          return new Settings();
        case 8:
          return new Faq();
        case 9:
          return new TermsAndConditions();
        case 10:
          return new SignOut();
        default:
          return new Text("Error");
      }
    }
  
  
    _onSelectItem(int index) {
      setState(() =&gt; _selectedDrawerIndex = index);
      if (_selectedDrawerIndex == 0) {
        setState(() =&gt; _setIcon = Icons.person);
      } else {
        setState(() =&gt; _setIcon = Icons.arrow_back);
      }
      Navigator.of(context).pop(); // close the drawer
    }
  
    @override
    Widget build(BuildContext context) {
      var drawerOptions = &lt;Widget&gt;[];
      for (var i = 0; i &lt; widget.drawerItems.length; i++) {
        var d = widget.drawerItems[i];
        drawerOptions.add(new ListTile(
          leading: new Icon(
            d.icon,
            color: Color(0xFF008577),
          ),
          title: new Text(d.title),
          selected: i == _selectedDrawerIndex,
          onTap: () =&gt; _onSelectItem(i),
        ));
      }
      final auth = Provider.of&lt;User&gt;(context, listen: false);
      if (auth != null) {
        drawer = DrawerLogin();
      } else {
        drawer = DrawerLogout();
      }
  
      return Scaffold(
        key: _scaffoldKey,
        appBar: AppBar(
          leading: Builder(
            builder: (BuildContext context) {
              return IconButton(
                icon: new Icon(_setIcon),
                onPressed: () {
                  if (_selectedDrawerIndex == 0) {
                    Scaffold.of(context).openDrawer();
                  } else {
                    setState(() =&gt; _selectedDrawerIndex = 0);
                    setState(() =&gt; _setIcon = Icons.person);
                  }
                },
                tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
              );
            },
          ),
          centerTitle: true,
          title: new Text(widget.drawerItems[_selectedDrawerIndex].title),
          backgroundColor: Color(0xFF008577),
          elevation: 0.0,
          actions: &lt;Widget&gt;[
            IconButton(
              icon: Icon(Icons.menu, color: Colors.white),
              onPressed: () {
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) =&gt; Company()),
                );
              },
            )
          ],
        ),
        drawer: new Drawer(
          child: SingleChildScrollView(
            child: new Column(
              children: &lt;Widget&gt;[drawer, new Column(children: drawerOptions)],
            ),
          ),
        ),
        body: _getDrawerItemWidget(_selectedDrawerIndex),
      );
    }
  }
  </code></pre>
  
  <blockquote>
    <p>FirebaseAuthService.dart</p>
  </blockquote>
  
  <pre><code>import 'package:firebase_auth/firebase_auth.dart';
  import 'package:reboo1/services/users.dart';
  import 'package:reboo1/services/database.dart';
  
  class AuthService {
  
    final FirebaseAuth _auth = FirebaseAuth.instance;
  
    // create user obj based on FirebaseUser
    User _userFromFirebaseUser(FirebaseUser user){
      return user != null ? User(uid: user.uid) : null;
    }
  
  
    // auth change user stream
    Stream&lt;User&gt; get user {
      return _auth.onAuthStateChanged
        .map(_userFromFirebaseUser);
    }
  
  
    // sign with email &amp; password
  
  Future signInWithEmailAndPassword(String email, String password) async {
    try {
      AuthResult result = await _auth.signInWithEmailAndPassword(email: email, password: password); 
      FirebaseUser user = result.user;
      return _userFromFirebaseUser(user);
    }catch(e){
      print(e.toString());
      return null;
    }
  }
  
    // register with email &amp; password
  
  Future registerForm(String email, String password, String birthday, String address, String fullName, String phone) async {
    try {
      AuthResult result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
      FirebaseUser user = result.user;
  
      // creat a new document in the database for the user with the uid
      await DatabaseService(uid: user.uid).updateUserData(email, birthday, address, fullName, phone);
  
      return _userFromFirebaseUser(user);
    }catch(e){
      print(e.toString());
      return null;
    }
  }
  
    Stream&lt;String&gt; get onAuthStateChanged =&gt;
        _auth.onAuthStateChanged.map(
              (FirebaseUser user) =&gt; user?.uid,
        );
    // GET UID
    Future&lt;String&gt; getCurrentUID() async {
      return (await _auth.currentUser()).uid;
    }
    Future getCurrentUser() async {
      return await _auth.currentUser();
    }
  
    //sign out
    Future signOut() async{
      try{
        return await _auth.signOut();
      }catch(e){
        print(e.toString());
        return null;
      }
    }
  
  }
  </code></pre>
  
  <p>SignIn.dart</p>
  
  <pre><code>import 'package:flutter/material.dart';
  import 'package:reboo1/authenticate/register.dart';
  import 'package:reboo1/home/homepage.dart';
  import 'package:reboo1/services/constants.dart';
  import 'package:reboo1/services/loading.dart';
  import 'package:reboo1/services/firebaseauthservice.dart';
  import 'package:shared_preferences/shared_preferences.dart';
  
  class SignIn extends StatefulWidget {
    final Function toggleView;
    SignIn({this.toggleView});
  
    @override
    _SignInState createState() =&gt; _SignInState();
  }
  
  class _SignInState extends State&lt;SignIn&gt; {
    final AuthService _auth = AuthService();
    final _formKey = GlobalKey&lt;FormState&gt;(); //global key
    bool loading = false;
  
    // text field state
    String email = '';
    String password = '';
    String error = '';
  
    @override
    Widget build(BuildContext context) {
      return loading
          ? Loading()
          : Scaffold(
              backgroundColor: Colors.brown[50],
              appBar: AppBar(
                backgroundColor: Color(0xFF008577),
                elevation: 0.0,
                title: Text('Sign in to Rèboo'),
                actions: &lt;Widget&gt;[
                  FlatButton.icon(
                    textColor: Colors.white,
                    icon: Icon(Icons.person),
                    label: Text('Register'),
                    onPressed: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) =&gt; Register()),
                      );
                    },
                  )
                ],
              ),
              body: Container(
                padding: EdgeInsets.symmetric(vertical: 20.0, horizontal: 50.0),
                child: Form(
                  key: _formKey, //global key
                  child: Column(children: &lt;Widget&gt;[
                    SizedBox(height: 20.0),
                    TextFormField(
                        decoration: textInputDecoration.copyWith(
                            hintText: 'Email address'),
                        validator: (val) =&gt;
                            val.isEmpty ? 'Enter an email address' : null,
                        onChanged: (val) {
                          setState(() =&gt; email = val);
                        }),
                    SizedBox(height: 20.0),
                    TextFormField(
                      decoration:
                          textInputDecoration.copyWith(hintText: 'Password'),
                      validator: (val) =&gt;
                          val.length &lt; 8 ? 'Enter valid password' : null,
                      obscureText: true,
                      onChanged: (val) {
                        setState(() =&gt; password = val);
                      },
                    ),
                    SizedBox(height: 20.0),
                    RaisedButton(
                      color: Colors.purple[400],
                      child:
                          Text('Sign in', style: TextStyle(color: Colors.white)),
                      onPressed: () async {
                        if (_formKey.currentState.validate()) {
                          setState(() =&gt; loading = true);
                          dynamic result = await _auth.signInWithEmailAndPassword(
                              email, password);
                          if (result == null) {
                            setState(() {
                              error =
                                  'Could not sign in with those credentials. Please register an account.';
                              setState(() =&gt; loading = false);
                            });
                          } else {
  
                            setState(() =&gt; loading = false);
                            Navigator.push(
                              context,
                              MaterialPageRoute(builder: (context) =&gt; HomePage()),
                            );
                          }
                        }
                      },
                    ),
                    SizedBox(height: 12.0),
                    Text(
                      error,
                      style: TextStyle(color: Colors.red, fontSize: 14.0),
                    )
                  ]),
                ),
              ),
            );
    }
  }
  </code></pre>