Alex
Alex

Reputation: 827

How to navigate to specific screen page based on the type of user logged in?

I'm having a mobile app with many screen (sreen A, screen B, screen C ...)

The requirement in my application to include two types of users. One type of user will have access to all screen and the second type user (not loggin) will only have access to Screen A , Screen B. How can I do that ?

My idea is store token after user loggin by SharedPreferences. And check the token is null or not. If not null, user can access all screen. But I don't know where to put this code ? At the main.dart or each screen ?

getToken() async {
  SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
  String token = sharedPreferences.getString("token");
  //print(token);
  return token;
}

//if token != null { ..can access all Screen } else { ... }

Upvotes: 1

Views: 241

Answers (2)

Abbasihsn
Abbasihsn

Reputation: 2171

you have two options:

  1. create a global.dart file and save getToken() and also a variable for the storedvalue of token (so only check for the value of sharedPref once) in there. then you can access it as follow:
import './globals.dart' as globals;

globals.accessToken // for getting token value
//or
globals.getToken() // for getting token directly from sharedPref
  1. use state managements like provider

Upvotes: 0

Huthaifa Muayyad
Huthaifa Muayyad

Reputation: 12373

Wrap your home screen in a Futurebuilder. use getToken() as the future for this future builder. Based on the data returned from your function, return the screen you want.

Upvotes: 1

Related Questions