Flutter 調整動畫速度的 timeDilation

開發 Flutter App 時,搭配動畫效果可以讓 App 更加吸引人,不過開發過程中,有時我們因為某些目的會想放慢或加快動畫的速度,比方為了仔細調整動畫的細節而放慢動畫的速度。

Flutter 的 scheduler.dart 定義了調整動畫速度的 timeDilation,我們只要調整 timeDilation 即可改變整個 App 的動畫速度。

timeDilation 預設為 1,表示標準的動畫速度。當 timeDilation 為 2 時表示動畫時間變成 2 倍,因此速度變慢了,當 timeDilation 為 0.5 時表示動畫時間變成原來的一半,因為速度變快了。

調整 timeDilation 的步驟如下。

  • import scheduler.dart。

建議加入 show timeDilation,表示我們只需加入 timeDilation,不需加入 scheduler.dart 全部的程式。

import 'package:flutter/scheduler.dart' show timeDilation;
  • 在程式裡設定 timeDilation。

比方在 function build 裡設定 timeDilation,以下例子將讓動畫時間變成 10 倍,呈現超級慢的動畫。

class _MyHomePageState extends State<MyHomePage> {
bool _isBigger = false;

@override
Widget build(BuildContext context) {
timeDilation = 10;
return Scaffold(

完整範例。

import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart' show timeDilation;

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

class MyApp extends StatelessWidget {
const MyApp({super.key});

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(),
);
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key});

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
bool _isBigger = false;

@override
Widget build(BuildContext context) {
timeDilation = 10;
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
AnimatedContainer(
duration: const Duration(seconds: 3),
curve: Curves.bounceOut,
width: _isBigger ? 300 : 100,
child: Image.network('https://cataas.com/cat'),
),
ElevatedButton(
onPressed: () {
setState(() {
_isBigger = !_isBigger;
});
},
child: const Text('Click Me'),
),
],
),
),
);
}
}

--

--

彼得潘的 iOS App Neverland
彼得潘的 Flutter App 開發問題解答集

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com