1

I have this login function and it's working like charm , but the problem that the user can press the back button and return to the login screen and I want to disable that.

void _login() async {
setState(() {
  _isLoading = true;
});
var data = {'email': email, 'password': password};
print("Data =" + data.toString());
var res = await Network().authData(data, '/login');
var body = json.decode(res.body);
print(body);
if (body['success']) {
  SharedPreferences localStorage = await SharedPreferences.getInstance();
  localStorage.setString('access_token', json.encode(body['access_token']));
  localStorage.setString('user', json.encode(body['user']));
  if (body['user']['verified'] == 1) {
  // OPEN THE HOME PAGE AND BLOCK THE BACK ACTION 
    Navigator.push(
      context,
      MaterialPageRoute(builder: (context) => HomeScreen()),
    );
  } else {
    showAnimatedDialog(
      context: context,
      barrierDismissible: true,
      builder: (BuildContext context) {
        return AlertDialog(
            backgroundColor: Colors.white,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(10),
            ),
            content: Container(
              width: 100,
              height: 50,
              child:
                  Center(child: Text("Your account isn't verified yet!")),
            ));
      },
      animationType: DialogTransitionType.fadeScale,
      curve: Curves.fastOutSlowIn,
      duration: Duration(seconds: 1),
    );
  }
} else {
  _showMsg(body['message']);
}

setState(() {
  _isLoading = false;
});
}

Plus , is there a way also to keep him logged even after closing the app once the login is done ? (Until the user press a logout button).

NewbieDeveloper
  • 408
  • 1
  • 10
  • use pushReplacement https://api.flutter.dev/flutter/widgets/Navigator/pushReplacement.html or pushReplacementNamed https://api.flutter.dev/flutter/widgets/Navigator/pushReplacementNamed.html – anggadaz Apr 29 '22 at 01:09

4 Answers4

5

Firstly: Let us understand how Screens are organized in Flutter Framework:

The screens in Flutter are organized in a Stack fashion, so if you are on Screen A and you pushed the Screen B, then from Screen B you pushed Screen C, your stack would look like the following:

After Pushing Screen B:

  1. Screen A
  2. Screen B (Current Screen)

After Pushing Screen C:

  1. Screen A
  2. Screen B
  3. Screen C (Current Screen)

So let's say Screen B is your Login Screen, and you want to block the user from going back, Then you don't have to just Push the screen into the stack, instead, you should Replace the screen in the stack with your Home Screen.

Secondly: Now after understanding the flow, let us talk about the code:

In your scenario, instead of using Navigator.push() you have to use Navigator.pushReplacement() to replace the screen in the stack as mentioned above.

Bounce: If you are in a scenario that needs all the screens to be removed from the stack and keep only the screen that would be pushed, as an example, if you have a multi-step registration flow, and after successful registration, you want to pop all the screens of the process from the stack and pushing the home screen, then you may use the following trick:

Navigator.popUntil((route) => route.isFirst); // Execute it before pushing the screen in order to keep only one route (screen) in the stack. Navigator.pushReplacement(); // Now you are replacing the only screen in the stack with the new one so the stack will only contain your wanted screen.

Moaz El-sawaf
  • 2,306
  • 1
  • 16
  • 33
0

I kind of find a way to do it , I don't know if it's the good way to do it but this did the job .

Wrapping the scaffold with WillPopScope like this :

WillPopScope(
  onWillPop: () async => false,
)

I got it from here

NewbieDeveloper
  • 408
  • 1
  • 10
  • But what if user wants to exit app? That thing will result into bad user experience\ – Nux Apr 28 '22 at 18:59
0

Here first you need to check whether the user is authenticated....

You have to check this condition's into material app's home : parameter.

if (snapShot.connectionState == ConnectionState.waiting) {
            return const SplashScreen(); // If it's in waiting state it will show splash screen
          }
          if (snapShot.hasData) {
            return const homeScreen(); // If user is authenticated it will show home screen
          }
          return const LoginScreen(); // If user is not authenticated then it will show login screen

here, snapShot is all about user data. Thanks in advance.

Meet Patel
  • 189
  • 9
-1

To block the user from moving back to the previous screen, try Navigator.pushReplacement instead of Navigator.push.

l984_451
  • 1
  • 2