How keep user logged in flutter

Issue

I posted yesterday this question but i didn’t get any valid answer. My current situation is i can successfully log the user in but when i restart the app i have to login again so i need to save the details of the user in a shared preference so that the user can stay logged for the entire session until logout.But i am unable to do that so please help me with it. Thanks in advance

login.dart :

Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromRGBO(3, 9, 23, 1),
      body: Container(
          padding: EdgeInsets.only(
            top: 100,
            right: 30,
            left: 30,
          ),
          child: SingleChildScrollView(
            child: Form(
              key: _formKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  FadeAnimation(
                      1.2,
                      Container(
                        padding: EdgeInsets.all(70.0),
                        margin: EdgeInsets.only(bottom: 50.0),
                        decoration: BoxDecoration(
                            image: DecorationImage(
                                image: AssetImage(
                                    'assets/images/trakinglogo.png'))),
                      )),
                  SizedBox(
                    height: 30,
                  ),
                  FadeAnimation(
                      1.5,
                      Container(
                        padding: EdgeInsets.all(10),
                        decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                            color: Colors.white),
                        child: Column(
                          children: <Widget>[
                            Container(
                              decoration: BoxDecoration(
                                  border: Border(
                                      bottom:
                                          BorderSide(color: Colors.grey[300]))),
                              child: TextFormField(
                                controller: _emailController,
                                onFieldSubmitted: (_) =>
                                    FocusScope.of(context).nextFocus(),
                                textInputAction: TextInputAction.done,
                                validator: (value) {
                                  if (value.isEmpty) {
                                    return 'Email is required';
                                  }
                                  return null;
                                },
                                decoration: InputDecoration(
                                    border: InputBorder.none,
                                    hintStyle: TextStyle(
                                        color: Colors.grey.withOpacity(.8)),
                                    hintText: "Votre adresse mail"),
                              ),
                            ),
                            Container(
                              decoration: BoxDecoration(),
                              child: TextFormField(
                                controller: _passwordController,
                                validator: (value) {
                                  if (value.isEmpty) {
                                    return 'Password is required';
                                  }
                                  return null;
                                },
                                obscureText: _isHidden,
                                decoration: InputDecoration(
                                  border: InputBorder.none,
                                  hintStyle: TextStyle(
                                      color: Colors.grey.withOpacity(.8)),
                                  hintText: "Mot de passe",
                                  suffix: InkWell(
                                      onTap: _togglePasswordView,
                                      child: Icon(
                                        _isHidden
                                            ? (CommunityMaterialIcons
                                                .eye_outline)
                                            : (CommunityMaterialIcons.eye_off),
                                        color: Color(0xFF939394),
                      
                  SizedBox(
                    height: 40,
                  ),
                  FadeAnimation(
                      1.8,
                      Center(
                          child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Container(
                                child: RaisedButton(
                                  textColor: Colors.white,
                                  color: kPrimaryColor,
                                  child: Text("Se connecter"),
                                  onPressed: () async {
                                    if (_formKey.currentState.validate()) {
                                      showDialog(
                                          context: context,
                                          builder: (BuildContext context) {
                                            return Center(
                                              child:
                                                  CircularProgressIndicator(),
                                            );
                                          });
                                      await loginUser();
                                    }
                                    /*  Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                          builder: (context) => MyWidget()),
                                    );*/
                                    // Navigator.pushNamed(context, 'Mywidget');
                                  },
                                  shape: new RoundedRectangleBorder(
                                    borderRadius:
                                        new BorderRadius.circular(30.0),
                                  ),
                                ),
                                width: 250,
                                padding: EdgeInsets.all(15),
                              )
                            ],
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              AlreadyHaveAnAccountCheck(
                                press: () {
                                  Navigator.push(
                                    context,
                                    MaterialPageRoute(
                                      builder: (context) {
                                        return SignUp();

 void loginUser() async {
    // if (_formKey.currentState.validate()) {
    setState(() {
      _isLoading = true;
    });
    String email = _emailController.text;
    String password = _passwordController.text;

    authentication.login(email, password).then((user) {
      if (user != null)
        Navigator.push(
            context, MaterialPageRoute(builder: (context) => MyWidget()));
    }).catchError((error) {
      ScaffoldMessenger.of(context)
          .showSnackBar(SnackBar(content: Text(error.toString())));
    });

    setState(() {
      _isLoading = false;
    });
  }

and this is login function :

Future<User> login(String email, String password) async {
  await checkInternet();

  Map<String, String> headers = {
    'Content-type': 'application/json',
    'Accept': 'application/json',
  };
  Map<String, String> body = {'email': email, 'password': password};

  var response = await http.post(Uri.parse(ApiUtil.AUTH_LOGIN),
      headers: headers, body: jsonEncode(body));
  switch (response.statusCode) {
    case 200:
      var body = jsonDecode(response.body);
      var data = body['user'];
      User user = User.fromJson(data);
      Track track = Track.fromJson(body);

      if (body['code'] == 0) {
        SharedPreferences localStorage =
        await SharedPreferences.getInstance();
        localStorage.setInt('id', body['user']['id']);
        localStorage.setString('adress', body['user']['adress']);
        localStorage.setString('phone', body['user']['phone']);
        localStorage.setString('access_token', body['access_token']);
        localStorage.setString('user', json.encode(body['user']));
        String user = localStorage.getString('user');

      }
      return user;
    case 500:
      throw ('Erreur serveur');
      break;

    case 400:
      throw LoginFailed();
    default:
      throw ('connection timeout');
      break;
  }
}

Solution

When i do the first login i’m saving the data on the shared preferences

 ApiRepository.get().login(LoginRequest(username: _emailController.text, password: _passwordController.text)).then((response) async {
  if (response != null) {
    //save on the shared preferences that the user is logged in
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.setBool(SHARED_LOGGED, true);
    await prefs.setString(SHARED_USER, _emailController.text);
    await prefs.setString(SHARED_PASSWORD, _passwordController.text);
  }
}).catchError((error) { 
});

Everytime i’m opening the app i have a splashscreen, here i do an implicit login and than i make skip the login page and bring the user on the home page

void checkUserIsLogged() async {
    final prefs = await SharedPreferences.getInstance();
    if ((prefs.getBool(SHARED_LOGGED) != null) && prefs.getBool(SHARED_LOGGED)) {
      ApiRepository.get().login(LoginRequest(username: prefs.getString(SHARED_USER), password: prefs.getString(SHARED_PASSWORD))).then((response) {
        if (response != null) {
          //"do something"
        }
      }).catchError((error) {
        
      });
    } else {

    }
  }

FULL code
SplashPageLoading.dart

class SplashPageLoading extends StatefulWidget {
  @override
  _SplashPageLoadingState createState() => _SplashPageLoadingState();
}

class _SplashPageLoadingState extends State<SplashPageLoading> {
  bool _doLogin = false;

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

    new Future.delayed(const Duration(seconds: 3), () => checkUserIsLogged());
  }

  void checkUserIsLogged() async {
    final prefs = await SharedPreferences.getInstance();
    if ((prefs.getBool(SHARED_LOGGED) != null) && prefs.getBool(SHARED_LOGGED)) {
      setState(() {
        _doLogin = true;
      });
      ApiRepository.get().login(LoginRequest(username: prefs.getString(SHARED_USER), password: prefs.getString(SHARED_PASSWORD))).then((response) {
        if (response != null) {
          Navigator.of(context).pushReplacementNamed(HomePage.routeName);
        }
      }).catchError((error) {
        Navigator.of(context).pushReplacementNamed(LoginPage.routeName);
      });
    } else {
      new Future.delayed(const Duration(seconds: 1), () => Navigator.of(context).pushReplacementNamed(LoginPage.routeName));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(
          _doLogin ? "Login.." : "No data for login",
          style: TextStyle(color: Colors.black),
        ),
      ),
    );
  }
}

Strings.dart

const String SHARED_LOGGED = "USER_IS_LOGGED";
const String SHARED_USER = "USER";
const String SHARED_PASSWORD = "PASSWORD";

shared preferences library

Answered By – Alessandro Cignolini

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *