Home > Enterprise >  Staying logged in when updating code on flutter web
Staying logged in when updating code on flutter web

Time:03-13

I am developing an app on flutter which has a login page.

When I run the app on an emulator and then when I do updates which activate the hot reload (I'm using VS Code), the app refresh without asking me to login again.

But when I run the app on the web, each time I have to reload the app I need to enter my login informations.

Do you know how to work around that ?

Thanks.

CodePudding user response:

I didn't find a simple answer to this problem but what I did is that I added some logic in my main and my LoginScreen and used SharedPreferences.

In my LoginScreen, after the authentification is successfully validated I set my login informations in SharedPreferences, and the "isLoggedIn" boolean to true :

SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setString('email', encrypt(data.name, key));
        prefs.setString('password', encrypt(data.password, key));
        prefs.setBool("isLoggedIn", true);

In the initState function of my main I check if I'm supposed to already be logged in and I call my authentification function using the login informations I already stored in SharedPreferences :

if (prefs.getBool("isLoggedIn") == true) {
      await authentification(decrypt(prefs.getString('email').toString(), key), decrypt(prefs.getString('password').toString(), key));
loggedIn = prefs.getBool("isLoggedIn");

I define a displayFunction to choose which screen my app gonna return depending on my loggedIn boolean :

Widget displayPage() {
    Widget widget = CircularProgressIndicator();
    if (isDataLoaded == true) {
      if (loggedIn == true) {
        widget = HomePage();
      } else {
        widget = LoginScreen();
      }
    }
    return widget;
  }

Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        textTheme: Theme.of(context).textTheme.apply(
              bodyColor: LightColors.kDarkBlue,
              displayColor: LightColors.kDarkBlue,
              fontFamily: 'Poppins'
            ),
      ),
      home: displayPage(),
    ); 
  }

In my logout function I set "isLoggedIn" to false :

prefs.setBool("isLoggedIn", false);
  • Related