flutterdartroutes

How to go back to previous route?


First of all, I'm not setting my routes in the MaterialApp like this

    new MaterialApp(
      home: new Screen1(),
      routes: <String, WidgetBuilder> {
        '/screen1': (BuildContext context) => new Screen1(),
        '/screen2' : (BuildContext context) => new Screen2(),
        '/screen3' : (BuildContext context) => new Screen3(),
        '/screen4' : (BuildContext context) => new Screen4()
      },
    )

Instead, I'm routing from different places in my app by pushing a new route like this:

    Navigator.push(
                    context,
                    MaterialPageRoute(
                        builder: (BuildContext context) =>
                            Screen3(someInputData)));

How I can pop screens from the current one into screen number 2 for example?


Solution

  • Asumming: Screen1 -> Screen2 -> Screen3 -> Screen4

    When you open the Screen2 , you could do something like this:

        Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (context) => Screen2(),
                    settings: RouteSettings(name: '/screen2')),
              );
    

    And when you want to go back from Screen4 to Screen2 :

     Navigator.popUntil(context, ModalRoute.withName("/screen2"));
    

    If you just want to go back to the previous screen use:

     Navigator.of(context).pop();