Home > Software design >  Why the auto login does not work in flutter
Why the auto login does not work in flutter

Time:02-23

I do not want to use accesstoken or refreshtoken but it is not working. Does anyone help me to handle this situation? Here is my future =>

Future<bool> autoLogin() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  var user = prefs.getString('username');
  var pwd = prefs.getString('password');
  debugPrint(user.toString());
  debugPrint(pwd.toString());
  UserResponse account = await LoginApi().login(user, pwd);
  // debugPrint(account.toString());
  bool acc = prefs.containsKey('userInfo');
  return acc;
}

This is my usage part =>

home: FutureBuilder<bool>(
          future: autoLogin(),
          builder: (context, snapshot){
            if(snapshot.data == null){
              Future.delayed(Duration(milliseconds: 1000), () {
                setState(() {
                  snapshot.data == false;
                });
              });
              return LoadingScreen();
            }
            return snapshot.data == true ? MainWidget() : LoginScreen();
          },
        ),

When i first time to try login it stays on loading screen, snapshot.data stays null. It does not change.

CodePudding user response:

Create an instance at widget that is int ctr=0; Then you can change there like this:

home: FutureBuilder<bool>(
          future: autoLogin(),
          builder: (context, snapshot){
            if(snapshot.data == null) {
              ctr  ;
              if(ctr>1) {
                return LoginScreen();
              }
              else {
                return LoadingScreen();
              }
            }
            return snapshot.data == true ? MainWidget() : LoginScreen();

CodePudding user response:

Your Future.delayed() is not being awaited, so the time delay is effectively a no-op except to push that setState later.

When the layers start to be complicated with a series of async operations, it's time to look at something like RiverPod (which I prefer over Provider and BLoC) to give you wrappers around those async operations, which properly cascade the dependencies in a readable format.

  • Related