mak
mak

Reputation: 63

how to make navigation animation that slides out the current page and slides in the other page

How can I make navigation animation that slides out the current page and slides in the other page.

I know how to create a sliding effect, but it only slides in the page over the current page, which is done by this code: Navigator.push(context, _createRoute());

  Route _createRoute() {
    return PageRouteBuilder(
        pageBuilder: (context, animation, secondaryAnimation) => PageTwo(),
        transitionDuration: Duration(milliseconds: 500),
        transitionsBuilder: (context, animation, secondaryAnimation, child) {
          var begin = Offset(1.0, 0.0);
          var end = Offset.zero;
          var curve = Curves.easeOut;

          var tween = Tween(begin: begin, end: end);
          var curvedAnimation = CurvedAnimation(
            parent: animation,
            curve: curve,
            reverseCurve: curve,
          );

          return SlideTransition(
            position: tween.animate(curvedAnimation),
            child: child,
          );
        });
  }

Upvotes: 1

Views: 648

Answers (1)

Elian Ortega
Elian Ortega

Reputation: 98

You can create a new class for the transition animation by extending the PageRouteBuilder, also you avoid repetition and can reuse the transition later.

First create class:

class MyTransition extends PageRouteBuilder {
  final Widget oldScreen;
  final Widget newScreen;
  MyTransition({this.oldScreen, this.newScreen})
      : super(
          pageBuilder: (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
          ) =>
              newScreen,
          transitionsBuilder: (
            BuildContext context,
            Animation<double> animation,
            Animation<double> secondaryAnimation,
            Widget child,
          ) =>
              Stack(
            children: <Widget>[
              SlideTransition(
                position: new Tween<Offset>(
                  begin: const Offset(0.0, 0.0),
                  end: const Offset(-1.0, 0.0),
                ).animate(animation),
                child: oldScreen,
              ),
              SlideTransition(
                position: new Tween<Offset>(
                  begin: const Offset(1.0, 0.0),
                  end: Offset.zero,
                ).animate(animation),
                child: newScreen,
              )
            ],
          ),
        );
}

Note that use stack to manage both animations on same place one on top another. Then just use slideTransition.

After that you just call this wherever you want your transition:

Navigator.push(
            context,
            MyTransition(
              oldScreen: this,
              newScreen: PageTwo(),
            );
          ),

Upvotes: 3

Related Questions