简体   繁体   中英

How to open different screens according to login status in Flutter?

I'm trying to write a function on Flutter that will open the required screen based on the value it returns. The service I have returns true if the person is logged in, false otherwise. According to the response of this service, I want to open the necessary screen. If true, the main screen; If false I wanted it to show the login screen.

My code is like this:

Future<dynamic> checkLoginService(String username, String ticket) async {
  var loginCheckJsonData = null;

  var loginCheckResponse = await http.get(
    Uri.parse(
        'http:...logincheck/?username=${username}&ticket=${ticket}&appType=3'),
  );
  if (loginCheckResponse.statusCode == 200) {
    loginCheckJsonData = json.decode(loginCheckResponse.body);
    print('login Check Json DATA is: ${loginCheckJsonData}');
    return loginCheckJsonData;
  }
}

And on the main.dart

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  firebaseMessaging = FirebaseMessaging.instance;
  SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

  

  String? ticket = sharedPreferences.getString('token');
  String? username = sharedPreferences.getString('email');
  if (ticket == null && username == null) {
    print('ticket or username is null');
  } else {
    checkLoginService(username!, ticket!);
  }

  runApp(MaterialApp(
      debugShowCheckedModeBanner: false,
      home: loginCheckJsonData == null ? TabsScreen() : LoginScreen()));
}

Username and ticket come from loginscreen textformfield and login service response. Help please.

You could create a variable of type bool that indicates wether the current user is logged in or not. I assume that your function returns null when the user is not logged in.

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  firebaseMessaging = FirebaseMessaging.instance;
  SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

  

  String? ticket = sharedPreferences.getString('token');
  String? username = sharedPreferences.getString('email');
  
  bool isLoggedIn = false;

  if (ticket == null && username == null) {
    print('ticket or username is null');
  } else {
    isLoggedIn = (await checkLoginService(username!, ticket!)) != null;
  }

  runApp(MaterialApp(
      debugShowCheckedModeBanner: false,
      home: isLoggedIn ? TabsScreen() : LoginScreen()));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM