Johnykutty
Johnykutty

Reputation: 12819

How to create fade transition on push route flutter?

I am trying to create a fade transition for pushing routes, for that created a custom route like

class CustomPageRoute<T> extends MaterialPageRoute<T> {
  CustomPageRoute({WidgetBuilder builder, RouteSettings settings})
      : super(builder: builder, settings: settings);

  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation,
      Animation<double> secondaryAnimation, Widget child) {
    return FadeTransition(opacity:animation, child: child,  );
  }
}

And calling it from a button press like

onPressed: () {
   Navigator.push(context, CustomPageRoute(builder: (context) {
       return FirstScreen();
   }));
}

But this give a weird animation with sliding + fade. How to avoid the sliding animation in this?

Here is the output of my code:

Here is the output

Upvotes: 17

Views: 14525

Answers (2)

Hadiuzzaman
Hadiuzzaman

Reputation: 454

Just create a method that return a Route. As a paremeter pass the new screen widget

Route createRoute(Widget page) {
  return PageRouteBuilder(
    pageBuilder: (context, animation, secondaryAnimation) => page,
    transitionsBuilder: (context, animation, secondaryAnimation, child) {
      return FadeTransition(
        opacity: animation,
        child: child,
      );
    },
  );
}

For calling the route you should use

 Navigator.push(
                context,
                createRoute(
                 AnotherScreen(),
                ),
              );

Upvotes: 1

diegoveloper
diegoveloper

Reputation: 103351

You should extend from PageRoute instead of MaterialPageRoute

    class CustomPageRoute<T> extends PageRoute<T> {
      CustomPageRoute(this.child);
      @override
      // TODO: implement barrierColor
      Color get barrierColor => Colors.black;

      @override
      String get barrierLabel => null;

      final Widget child;

      @override
      Widget buildPage(BuildContext context, Animation<double> animation,
          Animation<double> secondaryAnimation) {
        return FadeTransition(
          opacity: animation,
          child: child,
        );
      }

      @override
      bool get maintainState => true;

      @override
      Duration get transitionDuration => Duration(milliseconds: 500);
    }

Usage:

          final page = YourNewPage();
          Navigator.of(context).push(CustomPageRoute(page));

Upvotes: 34

Related Questions