Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter change page transition speed/duration in the theme

How do I change the duration/speed on transitions set in app's theme?

I am able to change the transition animation using a theme for a MaterialApp. The example below replaces the default transitions with a FadeTransition. When using the fade transition it feels slow and I cannot figure out how to change the duration on transitions set in the theme.

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

final themeData = ThemeData(
  pageTransitionsTheme: PageTransitionsTheme(builders: {
    TargetPlatform.iOS: FadeTransitionBuilder(),
    TargetPlatform.android: FadeTransitionBuilder(),
  }),
);

class FadeTransitionBuilder extends PageTransitionsBuilder {
  @override
  Widget buildTransitions<T>(_, __, animation, ___, child) => FadeTransition(opacity: animation, child: child);
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Mobile',
      theme: themeData,
      initialRoute: '/',
      routes: routes,
    );
  }
}
like image 242
Your Friend Ken Avatar asked Oct 14 '19 14:10

Your Friend Ken


2 Answers

I could achieve this using named routes which you need to list in your own instance of Navigator provided to the MaterialApp builder. The initialRoute property of MaterialApp must be removed.

class _MyAppState extends State<MyApp> with WidgetsBindingObserver {

  Route<dynamic> generateRoute(RouteSettings settings) {
    switch (settings.name) {
      case '/about':
        return CustomPageRoute(
            builder: (context) => About());
      default:
        return CustomPageRoute(
            builder: (context) => Home());
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Mobile',
      theme: themeData,
      builder: (context, widget) {
        return Navigator(
          onGenerateRoute: generateRoute,
        );
      },
    );
  }
}

class CustomPageRoute extends MaterialPageRoute {
  @override
  Duration get transitionDuration => const Duration(milliseconds: 1000);

  CustomPageRoute({builder}) : super(builder: builder);
}
like image 175
Patrick L Avatar answered Nov 19 '22 10:11

Patrick L


Create this class:

class MyRoute extends MaterialPageRoute {
  MyRoute({WidgetBuilder builder}) : super(builder: builder);

  @override
  Duration get transitionDuration => Duration(seconds: 3);
}

Now, instead of using regular

Navigator.push(context, MaterialPageRoute(builder: (_) => Page2()));

use

Navigator.push(context, MyRoute(builder: (_) => Page2()));
like image 4
CopsOnRoad Avatar answered Nov 19 '22 10:11

CopsOnRoad