How to remove default navigation route animation

Issue

I am below code which given in flutter documentation for page routing

// Within the `FirstRoute` widget
onPressed: () {
  Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => SecondRoute()),
  );
}

But it provides some animation while pushing and poping route.

For Android, the entrance transition for the page slides the page
upwards and fades it in. The exit transition is the same, but in
reverse.

The transition is adaptive to the platform and on iOS, the page slides
in from the right and exits in reverse. The page also shifts to the
left in parallax when another page enters to cover it. (These
directions are flipped in environments with a right-to-left reading
direction.)

Is there any way to route to next page without any animation?

Edit:
Please check the entire code:

class MyApp extends StatelessWidget {
  final routes = <String, WidgetBuilder>{
    SecondRoute.tag: (context) => SecondRoute(),
  };

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Flutter Routes",
      home: new FirstRoute(),
      routes: routes,
      onGenerateRoute: (routeSettings) {
        if (routeSettings.name == SecondRoute.tag)
          return PageRouteBuilder(pageBuilder: (_, a1, a2) => SecondRoute());

        return null;
      },
    );
  }
}

class FirstRoute extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Route'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Open route'),
          onPressed: () {
            Navigator.of(context).pushNamed(SecondRoute.tag);

          },
        ),
      ),
    );
  }
}

class SecondRoute extends StatelessWidget {
  static String tag = 'second-route';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Second Route"),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: Text('Go back!'),
        ),
      ),
    );
  }
}

Solution

  • For Navigator.push(...)

    Navigator.push(
      context,
      PageRouteBuilder(pageBuilder: (_, __, ___) => SecondRoute()),
    )
    
  • For Navigator.pushNamed(...)

    First, add this to your MaterialApp

    MaterialApp(
      onGenerateRoute: (settings) {
        if (settings.name == '/second') 
          return PageRouteBuilder(pageBuilder: (_, __, ___) => SecondRoute());
    
        return null;
      },
    )
    

    And now, you can use:

    Navigator.pushNamed(context, '/second');
    

Answered By – CopsOnRoad

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *