Flutter pop twice

When using the Flutter framework, the method ‘Navigator.pop(context)’ is used to pop (remove) the current route from the navigation stack and return to the previous route.

If you call the ‘Navigator.pop(context)’ method twice consecutively, it will effectively remove the current route and the previous route from the stack, resulting in returning to the route that is two levels below.

Here’s an example to illustrate the scenario:

// Create a new route with a button
    class MyRoute extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
            return Scaffold(
                appBar: AppBar(title: Text('Route 1')),
                body: Center(
                    child: RaisedButton(
                        child: Text('Go to Route 2'),
                        onPressed: (){
                            Navigator.push(
                                context,
                                MaterialPageRoute(builder: (context) => Route2()),
                            );
                        },
                    ),
                ),
            );
        }
    }
    
    // Route 2
    class Route2 extends StatelessWidget {
        @override
        Widget build(BuildContext context) {
            return Scaffold(
                appBar: AppBar(title: Text('Route 2')),
                body: Center(
                    child: RaisedButton(
                        child: Text('Go back twice'),
                        onPressed: (){
                            // Pop twice to go two levels back
                            Navigator.pop(context);
                            Navigator.pop(context);
                        },
                    ),
                ),
            );
        }
    }
    
    // Run the main app with the initial route
    void main() => runApp(MaterialApp(home: MyRoute()));

    

In the above example, we have two routes: ‘MyRoute’ and ‘Route2’. When the button in ‘MyRoute’ is pressed, it takes you to ‘Route2’. In ‘Route2’, when the button “Go back twice” is pressed, it calls the ‘Navigator.pop’ method twice, removing ‘Route2’ and ‘MyRoute’ from the stack, resulting in going back to the home route (two levels back).

Leave a comment