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.dart316 行 · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
// 三类动画,从"最省事"到"最可控":
// 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 真实构建并启动成功