Flutter go router push replacement

Flutter Go Router Push Replacement

The Flutter Go Package offers the ability to navigate between different views or pages in your application using the ‘router’ package. The ‘pushReplacement’ method is used to navigate to a new page while removing the current page from the stack.

Here is an example of how to use the ‘pushReplacement’ method:


import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
      onGenerateRoute: (settings) {
        if (settings.name == '/second') {
          return MaterialPageRoute(builder: (context) => SecondPage());
        }
        return null;
      },
    );
  }
}

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home Page'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Go to Second Page'),
          onPressed: () {
            Navigator.pushReplacementNamed(context, '/second');
          },
        ),
      ),
    );
  }
}

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Second Page'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Go back to Home Page'),
          onPressed: () {
            Navigator.pop(context);
          },
        ),
      ),
    );
  }
}

In the example above, the application starts with the ‘HomePage’ widget as the initial route. The ‘HomePage’ widget contains a raised button that triggers the navigation to the ‘SecondPage’ widget using the ‘pushReplacementNamed’ method.

When the button is pressed, the ‘Navigator.pushReplacementNamed’ method is called, which navigates to the ‘/second’ route and removes the ‘HomePage’ from the stack. This means that if the user presses the back button on the ‘SecondPage’, they will not be able to go back to the ‘HomePage’ since it is no longer in the route stack.

The ‘onGenerateRoute’ property is used to define the route for the ‘/second’ route. In this case, it returns the ‘SecondPage’ widget as the destination for the ‘/second’ route.

Inside the ‘SecondPage’, there is another raised button that triggers the ‘pop’ method of the ‘Navigator’, allowing the user to go back to the previous page, which is the ‘HomePage’.

Leave a comment