Search code examples
flutterdartflutter-navigationflutter-widget

How to replace page animated with Navigator 2.0?


I'm navigating to another page by change of an item in the pages collection.

final page = ...
return Scaffold(
            body: Navigator(
              onPopPage: (Route<dynamic> route, dynamic result) {
                return route.didPop(result);
              },
              pages: [
                MaterialPage(child: page),
              ],
            ),
...

And there is no a transition animation in this case (on IOS at least). When I'm adding a page to the collection - animation present. But I don't need a pages stack. How to fix?


Solution

  • Change the key parameter when you change the page.

    Example:

    final page = condition 
      ? MaterialPage(key: ValueKey('page1'), child: page1)
      : MaterialPage(key: ValueKey('page2'), child: page2);
    
    return Scaffold(
                body: Navigator(
                  onPopPage: (Route<dynamic> route, dynamic result) {
                    return route.didPop(result);
                  },
                  pages: [
                    page,
                  ],
                ),