Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set different transition animations on Navigator.pop() in Flutter, according to user action?

Tags:

flutter

In my Flutter project, that has multiple screens, I want to create one screen with 2 buttons:

  • the first button closes the current screen with Navigator.pop() with a transition where the current screen disappears to the right
  • the second button also closes the current screen with Navigator.pop(), but this time the screen disappears to the bottom

Every example I've found so far allows me to set only one possible transition when I pop my screen.

Also, I use named routes to navigate in my app.

How can I customize the pop animation according to the button clicked by the user?

Thanks.

like image 674
matteoh Avatar asked Nov 16 '22 02:11

matteoh


1 Answers

whatever you define as a route animation it would be reverse and use as pop navigation .
in your case you can use different animations for pushing each one .
you can create your custom one and define the animation and use it instead of material page router

   import 'package:flutter/material.dart';
class MyCustomRoute extends PageRouteBuilder {
  final Widget widget;
  MyCustomRoute({this.widget})
    : super(
        pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
          return widget;
        },
        transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
          return new ScaleTransition(
            scale: new Tween<double>(
              begin: 0.0,
              end: 1.0,
            ).animate(
                CurvedAnimation(
                  parent: animation,
                  curve: Interval(
                    0.00,
                    0.50,
                    curve: Curves.bounceIn,
                  ),
                ),
              ),
            child: ScaleTransition(
                     scale: Tween<double>(
                       begin: 1.5,
                       end: 1.0,
                     ).animate(
                       CurvedAnimation(
                         parent: animation,
                         curve: Interval(
                           0.50,
                           1.00,
                           curve: Curves.easeIn,
                         ),
                       ),
                     ),
                     child: child,
                   ),
           );
         }
      );
}

to implement

onPressed: () {
  Navigator.push(context,
      new MyCustomRoute (widget: Secondpage()));
},

to pop

 onPressed: () {
                  Navigator.pop();// will reverse the animation
                },
like image 88
Yahya Parvar Avatar answered Jun 11 '23 10:06

Yahya Parvar