跳到正文
教程首页
FlutterCH 07ch07_animation

ch07-animation

动画与动效:隐式动画、显式动画、AnimationController。完整工程共 100 个文件,其中 60 个文本源文件可在下面在线阅读。

60

在线文本文件

3,586

源码行数

dart / c / yaml

语言

275 KB

打包体积

在线阅读源码

左侧按目录浏览,点击文件切换。右上角可复制代码、复制路径或单独下载文件。在线视图只覆盖文本源码,完整工程请下载 zip。

textxmldartjsonkotlin

60 text files · 3,586 lines

dartlib/src/animation_gallery.dart
// 三类动画,从"最省事"到"最可控":
//   1. AnimatedXxx / TweenAnimationBuilder —— 隐式动画:只给目标值
//   2. AnimationController + Tween —— 显式动画:拿到 0..1 的进度自己画
//   3. AnimatedSwitcher —— 子级切换时的交叉淡入淡出
import 'dart:math' as math;

import 'package:flutter/material.dart';

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('动画与动效')),
      body: ListView(
        padding: const EdgeInsets.all(16),
        children: const [
          ImplicitCard(),
          SizedBox(height: 12),
          TweenBuilderCard(),
          SizedBox(height: 12),
          ExplicitCard(),
          SizedBox(height: 12),
          SwitcherCard(),
        ],
      ),
    );
  }
}

// ===========================================================================
// 1. 隐式动画:AnimatedContainer
// ===========================================================================
//
// 你只说"目标状态"(尺寸、颜色),框架用内部的 AnimationController
// 在旧值和新值之间插值。没有 controller 要管,也没有 dispose 要写。
class ImplicitCard extends StatefulWidget {
  const ImplicitCard({super.key});

  @override
  State<ImplicitCard> createState() => _ImplicitCardState();
}

class _ImplicitCardState extends State<ImplicitCard> {
  bool _expanded = false;

  @override
  Widget build(BuildContext context) {
    return DemoCard(
      title: '隐式动画:AnimatedContainer',
      subtitle: '改的是"目标值",补帧是框架的事',
      children: [
        Center(
          child: AnimatedContainer(
            key: const Key('implicit-box'),
            duration: const Duration(milliseconds: 400),
            curve: Curves.easeInOut,
            width: _expanded ? 220 : 80,
            height: _expanded ? 120 : 80,
            decoration: BoxDecoration(
              color: _expanded ? const Color(0xFFAD1457) : const Color(0xFF4DB6AC),
              borderRadius: BorderRadius.circular(_expanded ? 24 : 8),
            ),
            alignment: Alignment.center,
            child: Text(
              _expanded ? '展开' : '收起',
              style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w600),
            ),
          ),
        ),
        const SizedBox(height: 12),
        Center(
          child: FilledButton(
            key: const Key('implicit-toggle'),
            onPressed: () => setState(() => _expanded = !_expanded),
            child: Text(_expanded ? '收起' : '展开'),
          ),
        ),
      ],
    );
  }
}

// ===========================================================================
// 2. TweenAnimationBuilder:给"数字"加动画
// ===========================================================================

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

  @override
  State<TweenBuilderCard> createState() => _TweenBuilderCardState();
}

class _TweenBuilderCardState extends State<TweenBuilderCard> {
  double _target = 0;

  @override
  Widget build(BuildContext context) {
    return DemoCard(
      title: 'TweenAnimationBuilder:数字补间',
      subtitle: '目标值一变,自动从旧值补到新值',
      children: [
        TweenAnimationBuilder<double>(
          key: const Key('tween-value'),
          tween: Tween<double>(begin: 0, end: _target),
          duration: const Duration(milliseconds: 800),
          curve: Curves.easeOutCubic,
          builder: (BuildContext context, double value, Widget? child) {
            return Text(
              key: const Key('tween-text'),
              value.toStringAsFixed(1),
              style: Theme.of(context).textTheme.displaySmall,
            );
          },
        ),
        const SizedBox(height: 8),
        Wrap(
          spacing: 8,
          children: [
            OutlinedButton(
              key: const Key('tween-100'),
              onPressed: () => setState(() => _target = 100),
              child: const Text('→ 100'),
            ),
            OutlinedButton(
              key: const Key('tween-0'),
              onPressed: () => setState(() => _target = 0),
              child: const Text('→ 0'),
            ),
          ],
        ),
      ],
    );
  }
}

// ===========================================================================
// 3. 显式动画:AnimationController
// ===========================================================================
//
// controller 就是 ch05 讲的"外部事件源":它由 Ticker(垂直同步信号)驱动,
// 必须 dispose,否则 Ticker 会一直跑(Flutter 会在 debug 模式报 "Ticker was still active")。
class ExplicitCard extends StatefulWidget {
  const ExplicitCard({super.key});

  @override
  State<ExplicitCard> createState() => _ExplicitCardState();
}

class _ExplicitCardState extends State<ExplicitCard> with SingleTickerProviderStateMixin {
  late final AnimationController _controller = AnimationController(
    vsync: this, // vsync 需要一个 TickerProvider,Mixin 提供
    duration: const Duration(seconds: 1),
  );

  /// 把线性的 0..1 进度映射成"先快后慢"的曲线。
  late final Animation<double> _curved = CurvedAnimation(
    parent: _controller,
    curve: Curves.easeOutBack,
  );

  @override
  void dispose() {
    _controller.dispose(); // 必须:释放 Ticker
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return DemoCard(
      title: '显式动画:AnimationController',
      subtitle: '拿 0..1 的进度,自己决定画什么',
      children: [
        // AnimatedBuilder 只重建它的 builder,不重建整个卡片。
        AnimatedBuilder(
          animation: _curved,
          builder: (BuildContext context, Widget? child) {
            return Column(
              children: [
                Transform.rotate(
                  angle: _curved.value * math.pi / 2,
                  child: Container(
                    key: const Key('explicit-box'),
                    width: 72,
                    height: 72,
                    decoration: BoxDecoration(
                      color: Theme.of(context).colorScheme.primary,
                      borderRadius: BorderRadius.circular(12 + 12 * _curved.value),
                    ),
                  ),
                ),
                const SizedBox(height: 8),
                LinearProgressIndicator(value: _controller.value),
                const SizedBox(height: 4),
                Text(
                  '${(_controller.value * 100).round()}%',
                  key: const Key('progress-text'),
                  style: const TextStyle(fontFamily: 'monospace'),
                ),
              ],
            );
          },
        ),
        const SizedBox(height: 8),
        Wrap(
          spacing: 8,
          children: [
            FilledButton(
              key: const Key('play'),
              onPressed: () => _controller.forward(),
              child: const Text('播放'),
            ),
            OutlinedButton(
              key: const Key('reverse'),
              onPressed: () => _controller.reverse(),
              child: const Text('倒放'),
            ),
            TextButton(
              key: const Key('reset'),
              onPressed: () => _controller.value = 0,
              child: const Text('重置'),
            ),
          ],
        ),
      ],
    );
  }
}

// ===========================================================================
// 4. AnimatedSwitcher:子级切换时的交叉淡入
// ===========================================================================

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

  @override
  State<SwitcherCard> createState() => _SwitcherCardState();
}

class _SwitcherCardState extends State<SwitcherCard> {
  int _index = 0;

  static const List<String> _faces = <String>['😀', '😎', '🤖', '🦊'];

  @override
  Widget build(BuildContext context) {
    return DemoCard(
      title: 'AnimatedSwitcher:切换子级',
      subtitle: '旧子级淡出、新子级淡入,靠 Key 区分身份',
      children: [
        Center(
          child: AnimatedSwitcher(
            duration: const Duration(milliseconds: 300),
            transitionBuilder: (Widget child, Animation<double> animation) =>
                ScaleTransition(scale: animation, child: FadeTransition(opacity: animation, child: child)),
            child: Text(
              _faces[_index],
              // 没有 key 的话,AnimatedSwitcher 认为是"同一个 child 换内容",不会做过渡
              key: ValueKey<int>(_index),
              style: const TextStyle(fontSize: 56),
            ),
          ),
        ),
        const SizedBox(height: 8),
        Center(
          child: FilledButton.tonal(
            key: const Key('switcher-next'),
            onPressed: () => setState(() => _index = (_index + 1) % _faces.length),
            child: const Text('换一个'),
          ),
        ),
      ],
    );
  }
}

/// 卡片外壳(与 ch06 同款,故意复制一份保持章节独立)。
class DemoCard extends StatelessWidget {
  const DemoCard({
    super.key,
    required this.title,
    required this.subtitle,
    required this.children,
  });

  final String title;
  final String subtitle;
  final List<Widget> children;

  @override
  Widget build(BuildContext context) {
    final ThemeData theme = Theme.of(context);
    return Card(
      margin: EdgeInsets.zero,
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(title, style: theme.textTheme.titleMedium),
            Text(
              subtitle,
              style: theme.textTheme.bodySmall?.copyWith(color: theme.colorScheme.onSurfaceVariant),
            ),
            const Divider(height: 16),
            ...children,
          ],
        ),
      ),
    );
  }
}

代码构成:text 60 KB · xml 41 KB · dart 17 KB · json 4 KB

本地运行

zip → 解压 → 执行
$cd examples/ch07-animation && flutter run -d macos

这个 zip 里有什么

  • • 完整工程目录(含 Android / iOS / 桌面平台脚手架)
  • • lib / bin / test / native 全部源码与测试
  • • pubspec.yaml、锁文件与平台配置文件
  • • 已排除 .dart_tool / build / target / ephemeral 等构建产物

已验证

  • flutter analyze 0 告警、flutter test 9 个用例全绿、flutter build macos --debug 真实构建并启动成功
查看全部示例