Ammar Al-Wazzan
Ammar Al-Wazzan

Reputation: 115

Android Back Button Keep bring me back to first screen when its pressed and Didn't close the drawer if open

I create multiple screens as separate dart files and in my main screen I have created a drawer. When I choose any screen it navigates me to it, but the problems are:

  1. If I press the hardware back button it brings me back to the first screen of the app which is the Splash screen.

  2. If I press the back button in the app bar it brings me back to the previous screen but the drawer is shown as in open state!

  3. If the drawer open and I press the Hardware Back Button it didn't close it, it brings me back to the first screen (the splash screen) too... like my first point.
    Ex: my main page navigator code:

    onPressed: (){ Navigator.push(context,
        MaterialPageRoute(builder: (context) => Profile(),
        )
    

I've read about WillPopScope and used it, but still the situation as it is.

Upvotes: 0

Views: 2033

Answers (2)

Riyan
Riyan

Reputation: 193

I was able to fix this issue by using Navigator.popAndPushNamed() method.

void main() {
  runApp(MaterialApp(routes: {
    '/': (context) => SplashScreen(),
    '/home': (context) => HomePage(),
    '/signin': (context) => Confirm(),
  }));
}

And in the function which check if the user is already logged in or not, depending on the boolean response we can push the new page on screen. By this if user presses the Hardware Back Button the SplashScreen() will not be shown and the app will Directly close.

Navigator.popAndPushNamed(context, '/home');

Navigator.popAndPushNamed(context, '/signin');

After User Signs In successfully, we can push the same Home() page.

void _signIn(){
if (_success){
Navigator.popAndPushNamed(context, '/home');
}
}

@override
  Widget build(BuildContext context) {
    return MaterialApp(
      routes: {
        '/home': (context) => HomePage(),
      });

Upvotes: 0

Alvin John Babu
Alvin John Babu

Reputation: 2070

I solved this by adding the following code in the splash screen just before it push to the new screen.

Navigator.popUntil(context, ModalRoute.withName('/scrren'));

Have a look at this document

Upvotes: 1

Related Questions