示例工程 ch07-animation
ch07-animation/lib/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,
],
),
),
);
}
}