Home > Software design >  Is there a way to make my loggedIn variable reference my isLoggedIn varianble in a statefulwidget?
Is there a way to make my loggedIn variable reference my isLoggedIn varianble in a statefulwidget?

Time:03-10

I am new to flutter and I currently experimenting with how I can limit access to pages that are of limit to users who are not logged in.

router:

final router = GoRouter(
  redirect: (state) {
    //Need the actual value from loginpage
    final loggedIn = ;

    final isLoggingIn = state.location == '/loginpage';

    if (!loggedIn && !isLoggingIn) return '/loginpage';

    if (loggedIn && isLoggingIn) return '/menupage';

    return null;
  },

LoginPage:

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool isProgressing = false;
  bool isLoggedIn = false;
  String errorMessage = '';
  String? name;
  String? auth0Id;
  String? accessToken;
  String? tokenValid;}

Is there anyway for me to take the value of isLoggedIn from loginpage and reference it in loggedIn from router?

CodePudding user response:

I think you should learn Shared Preference for save isLogged info to phone storage. After that you can check on router function your isLogged info.

Sample:

if(Prefs.isLoggedIn)
return "/loginpage"
else 
return "/menupage"

CodePudding user response:

You Should use Shared Preferences plugin to achieve this functionality for example :

void isLoggedIn() async {
  var prefs = await SharedPreferences.getInstance();

  if (prefs.getBool("isLoggedIn")!) {
    Navigator.pushReplacementNamed(context, "/menupage");
    //prefs.setBool("isLoggedIn", true);
  } else {
    Navigator.pushReplacementNamed(context, "/loginpage");
    //prefs.setBool("isLoggedIn", false);
  }
}
  • Related