Search code examples
flutterflutter-navigation

How to go back to the previous page in flutter upon button press?


Upon pressing the button the below command is executed successfully.

Navigator.push(context, MaterialPageRoute(builder:(context)=>NewForm(stateCheck: widget.state1,)));

But I want this to happen on a certain boolean condition, if the condition is false then the above should be executed else upon pressing the button the navigation should be done to the previous screen.

if (a == b){
    Navigator.push(context, MaterialPageRoute(builder:(context)=>NewForm(stateCheck: widget.state1,)));
} else {
//what command should be written here to move to back to previous screen
}

In clear summary, there are 3 screens, S1, S2 and S3 respectively. Current Screen is S2,upon pressing the button if condition is false user should move to screen S3 and if condition is true user should move to screen S1, How should I achieve it?


Solution

  • If screen S1 is different from the flow like if your flow is S1->S2->S3, then to go back to S1 you can do Navigator.pop(context) this will navigate you to S1 back to S2.

    If your flow is different means you are coming on S2 from other than S1 say S3 but want to go to S1 then use Navigator.push() as you did earlier.

    I think this should solve your issue..