flutterdart

I want to save token of signIn form in shared preference also retrieve token successful but it did't get saved


For keep user logged in flutter app, I want to save token from API response in SharedPreferences. I am trying to save it, but that doesn't work.

Basically the API response is successfully received and its signin token but how to save in sharedPreference for user loggedIn after reopening the app i work on it but not saved pretty well

Here is my splash screen method whereGoTo initialized in initState hook:

void whereGoTo() async {
    var sharedPref = await SharedPreferences.getInstance();
    var isSignedIn = sharedPref.getString('token');

    Timer(Duration(seconds: 2), () {
      if (isSignedIn != null && isSignedIn.isEmpty) {
        print(isSignedIn);
        Navigator.pushReplacement(
            context, MaterialPageRoute(builder: (context) => HomePage()));
      } else {
        Navigator.pushReplacement(
            context,
            MaterialPageRoute(
                builder: (context) => SafeArea(child: Login_Screen())));
      }
    });
  }

Here my signIn method integrated API and setString method to saved token after response of api:

String? myToken;

loginApi(email, password) async {
    print(email);
    print(password);
    final response = await http
        .post(Uri.parse('https://quotes.limpidsol.com/api/login'), body: {
      'email': email,
      'password': password,
    });
    if (response.statusCode == 200) {
      print('account loggedIn successfully');
      var data = ExtructData.fromJson(jsonDecode(response.body));
      print(data.token);
      setState(() {
        myToken = data.token;
      });

      var pref = await SharedPreferences.getInstance();
      pref.setString('token', myToken!);
      Navigator.pushReplacement(
          context, MaterialPageRoute(builder: (context) => HomePage()));

      String successMessage =
          'Logged in successfully. Status code: ${response.statusCode}';
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(successMessage),
        ),
      );
    } else {
      String errorMessage = 'Login failed. Status code: ${response.statusCode}';
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(errorMessage),
        ),
      );
    }
}

Solution

  • Is there a right token value in isSignedIn parameter after this line var isSignedIn = sharedPref.getString('token');?

    As I see in your code, mistake is in condition: instead of

    if (isSignedIn != null && isSignedIn.isEmpty) {
    

    should be

    if (isSignedIn != null && isSignedIn.isNotEmpty) {
    

    PS it's better to use some secure storage to store tokens - for example flutter_secure_storage package