跳到主內容

交錯動畫

如何在 Flutter 中編寫交錯動畫。

交錯動畫是一個簡單的概念:視覺變化以一系列操作發生,而不是一次性發生。動畫可能是純粹的順序的,一個變化在下一個變化之後發生,或者它可能是部分或完全重疊的。它也可能存在間隙,在此期間不發生任何變化。

本指南演示如何在 Flutter 中構建交錯動畫。

以下影片演示了 basic_staggered_animation 執行的動畫

在 YouTube 上以新標籤頁觀看:“交錯動畫示例”

在影片中,您會看到單個小部件的以下動畫,它從一個帶有略微圓角的藍色邊框的正方形開始。正方形按以下順序執行變化

  1. 淡入
  2. 變寬
  3. 在向上移動的同時變得更高
  4. 轉換為帶邊框的圓形
  5. 顏色變為橙色

動畫向前執行後,會反向執行。

交錯動畫的基本結構

#

下圖顯示了 basic_staggered_animation 示例中使用的 Interval。您可能會注意到以下特徵

  • 不透明度在時間線的最初 10% 期間變化。
  • 不透明度的變化和寬度的變化之間出現了一個微小的間隙。
  • 時間線的最後 25% 期間沒有任何動畫。
  • 增加內邊距會使小部件看起來向上移動。
  • 將邊框半徑增加到 0.5,會將帶有圓角的正方形轉換為圓形。
  • 內邊距和高度的變化發生在完全相同的間隔內,但不必如此。

Diagram showing the interval specified for each motion

設定動畫

  • 建立一個 AnimationController 來管理所有 Animations
  • 為正在進行動畫處理的每個屬性建立一個 Tween
    • Tween 定義一個值範圍。
    • Tweenanimate 方法需要 parent 控制器,並生成該屬性的 Animation
  • Animationcurve 屬性上指定間隔。

當控制動畫的值發生變化時,新的動畫值會發生變化,從而觸發 UI 更新。

以下程式碼為 width 屬性建立一個 tween。它構建了一個 CurvedAnimation,指定了一個緩動曲線。有關其他可用的預定義動畫曲線,請參閱 Curves

dart
width = Tween<double>(
  begin: 50.0,
  end: 150.0,
).animate(
  CurvedAnimation(
    parent: controller,
    curve: const Interval(
      0.125,
      0.250,
      curve: Curves.ease,
    ),
  ),
),

beginend 值不必是雙精度數。以下程式碼構建了 borderRadius 屬性的 tween(控制正方形角落的圓度),使用 BorderRadius.circular()

dart
borderRadius = BorderRadiusTween(
  begin: BorderRadius.circular(4),
  end: BorderRadius.circular(75),
).animate(
  CurvedAnimation(
    parent: controller,
    curve: const Interval(
      0.375,
      0.500,
      curve: Curves.ease,
    ),
  ),
),

完整的交錯動畫

#

與所有互動式小部件一樣,完整的動畫由一對小部件組成:一個無狀態小部件和一個有狀態小部件。

無狀態小部件指定 Tween,定義 Animation 物件,並提供一個負責構建動畫小部件樹部分的 build() 函式。

有狀態小部件建立控制器,播放動畫,並構建非動畫小部件樹部分。當在螢幕上的任何位置檢測到點選時,動畫開始。

basic_staggered_animation 的 main.dart 的完整程式碼

無狀態小部件:StaggerAnimation

#

在無狀態小部件 StaggerAnimation 中,build() 函式例項化一個 AnimatedBuilder——一個用於構建動畫的通用小部件。AnimatedBuilder 構建一個小部件,並使用 Tweens 的當前值對其進行配置。該示例建立了一個名為 _buildAnimation() 的函式(執行實際的 UI 更新),並將其分配給其 builder 屬性。AnimatedBuilder 偵聽來自動畫控制器的通知,在值發生變化時將小部件樹標記為“髒”。對於動畫的每次刻度,都會更新值,從而呼叫 _buildAnimation()

dart
class StaggerAnimation extends StatelessWidget {
  StaggerAnimation({super.key, required this.controller}) :

    // Each animation defined here transforms its value during the subset
    // of the controller's duration defined by the animation's interval.
    // For example the opacity animation transforms its value during
    // the first 10% of the controller's duration.

    opacity = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(
      CurvedAnimation(
        parent: controller,
        curve: const Interval(
          0.0,
          0.100,
          curve: Curves.ease,
        ),
      ),
    ),

    // ... Other tween definitions ...
    );

  final AnimationController controller;
  final Animation<double> opacity;
  final Animation<double> width;
  final Animation<double> height;
  final Animation<EdgeInsets> padding;
  final Animation<BorderRadius?> borderRadius;
  final Animation<Color?> color;

  // This function is called each time the controller "ticks" a new frame.
  // When it runs, all of the animation's values will have been
  // updated to reflect the controller's current value.
  Widget _buildAnimation(BuildContext context, Widget? child) {
    return Container(
      padding: padding.value,
      alignment: Alignment.bottomCenter,
      child: Opacity(
        opacity: opacity.value,
        child: Container(
          width: width.value,
          height: height.value,
          decoration: BoxDecoration(
            color: color.value,
            border: Border.all(
              color: Colors.indigo[300]!,
              width: 3,
            ),
            borderRadius: borderRadius.value,
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      builder: _buildAnimation,
      animation: controller,
    );
  }
}

有狀態小部件:StaggerDemo

#

有狀態小部件 StaggerDemo 建立 AnimationController(那個統治所有者),指定 2000 毫秒的持續時間。它播放動畫,並構建非動畫小部件樹部分。當在螢幕上檢測到點選時,動畫開始。動畫向前,然後向後執行。

dart
class StaggerDemo extends StatefulWidget {
  @override
  State<StaggerDemo> createState() => _StaggerDemoState();
}

class _StaggerDemoState extends State<StaggerDemo>
    with TickerProviderStateMixin {
  late AnimationController _controller;

  @override
  void initState() {
    super.initState();

    _controller = AnimationController(
      duration: const Duration(milliseconds: 2000),
      vsync: this,
    );
  }

  // ...Boilerplate...

  Future<void> _playAnimation() async {
    try {
      await _controller.forward().orCancel;
      await _controller.reverse().orCancel;
    } on TickerCanceled {
      // The animation got canceled, probably because it was disposed of.
    }
  }

  @override
  Widget build(BuildContext context) {
    timeDilation = 10.0; // 1.0 is normal animation speed.
    return Scaffold(
      appBar: AppBar(
        title: const Text('Staggered Animation'),
      ),
      body: GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          _playAnimation();
        },
        child: Center(
          child: Container(
            width: 300,
            height: 300,
            decoration: BoxDecoration(
              color: Colors.black.withValues(alpha: 0.1),
              border: Border.all(
                color: Colors.black.withValues(alpha: 0.5),
              ),
            ),
            child: StaggerAnimation(controller:_controller.view),
          ),
        ),
      ),
    );
  }
}