Mesut Tasci
Mesut Tasci

Reputation: 3120

How to open specific screen if user click to back button in flutter?

I have five screens and page routing direction shown as below:

Login -> Home -> Debits -> Payment -> PaymentSuccess

On payment screen if payment success I am opening paymentSuccess screen.

I want to do this:

If user click to back button on PaymentSuccess screen, user should go to HomeScreen.

I used pushAndRemoveUntil shown as below but when user click to back button on PaymentSuccessScreen app closing, not routing to HomeScreen.

    // Payment Screen
    Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(
      builder: (context) {
        return PaymentSuccessScreen(period: period);
      },
    ), ModalRoute.withName('/home-screen'));

Upvotes: 4

Views: 2935

Answers (1)

CopsOnRoad
CopsOnRoad

Reputation: 267404

In Login page, when navigating to Home page, use

Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => HomePage())),

In Home page, when navigating to Debit page, use

Navigator.push(context, MaterialPageRoute(builder: (context) => DebitPage())),

In Debit page, when navigating to Payment page, use

Navigator.push(context, MaterialPageRoute(builder: (context) => PaymentPage())),

And now here in the Payment page, use following:

class PaymentPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Payment")),
      body: WillPopScope(
        onWillPop: () { // this is the block you need
          Navigator.pushAndRemoveUntil(context, MaterialPageRoute(builder: (context) => HomePage()), (route) => false);
          return Future.value(false);
        },
        child: Center(
          child: RaisedButton(
            child: Text("Go to payment success"),
            onPressed: () => Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => PaymentSuccessPage())),
          ),
        ),
      ),
    );
  }
}

Upvotes: 9

Related Questions