7

如何更改应用主题中设置的过渡持续时间/速度?

我可以使用主题更改过渡动画MaterialApp。下面的示例将默认转换替换为FadeTransition. 使用淡入淡出过渡时感觉很慢,我无法弄清楚如何更改主题中设置的过渡持续时间。

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,
    );
  }
}
4

2 回答 2

8

我可以使用命名路由来实现这一点,您需要在提供给 MaterialApp 构建器的您自己的 Navigator 实例中列出这些路由。MaterialApp 的 initialRoute 属性必须被移除。

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);
}
于 2020-06-21T09:36:22.007 回答
3

创建这个类:

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

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

现在,而不是使用常规

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

利用

Navigator.push(context, MyRoute(builder: (_) => Page2()));
于 2021-05-09T13:43:53.120 回答