Home > Software design >  sharedPreference as future in FutureBuilder not working
sharedPreference as future in FutureBuilder not working

Time:08-16

In this code I want to check if user is logged in or not. so, reading data from sharedPreference, if it is true then it should build homepage() else build LoginPage().

But output shows circularProgressIndicator, which means snap has no data. please help, why that happend.

class Authentication {
Future<bool> LoginChecker() async {
var pref = await SharedPreferences.getInstance();
var v = pref.getBool('LoggedIn')as bool;
return v;
}
}




FutureBuilder(
          future: Authentication().LoginChecker(),
          builder: (context, snap) {
            if (snap.hasData) {
              var pref = snap.data;
             
              if (pref == true) {
                return HomePage();
              } else
                return LoginPage();
            } else {
              return Container(
                  alignment: Alignment.center,
                  height: 50,
                  width: 50,
                  child: CircularProgressIndicator());
            }
          }),

CodePudding user response:

One thing i can see as a problem is, SharedPref might not always have that key named 'LoggedIn'. Unless you are assigning it each and every time the app runs. So if the app is running for the very first time, it might not have the key. And can cause null. So just for better code you can make it like this...

class Authentication {
Future<bool> LoginChecker() async {
var pref = await SharedPreferences.getInstance();

if(pref.containsKey("LoggedIn")) {
     return pref.getBool('LoggedIn')as bool;
} else 
   {
     return false;
    }
  }
}

CodePudding user response:

Not sure what this line means but it has to look like the following

if (pref == true ) {
 return HomePage();
 } else {
 return LoginPage();
}

By mistake the pref is assigned with the snap data and its not true ao it always displays circular indicator..

var pref = snap.data;

This line caused the issue i believe

CodePudding user response:

The Authentication class needs to be changed because when you check data from SharedPreferences, it is null, so you need to specify false.

class Authentication {
      Future<bool> LoginChecker() async {
        var pref = await SharedPreferences.getInstance();
        var v = pref.getBool('LoggedIn')??false;
        return v;
      }
    }

CodePudding user response:

The problem was my php backend which cause an exception due to one some reasons, which hinders my the following code to execute and create the pref.setbool('LoggedIn',true), so it was null. Now fixed

  • Related