FlutterCH 06ch06_state
ch06-state
Flutter 交互与状态:StatefulWidget、setState、生命周期。完整工程共 101 个文件,其中 61 个文本源文件可在下面在线阅读。
61
在线文本文件
3,719
源码行数
dart / c / yaml
语言
276 KB
打包体积
在线阅读源码
左侧按目录浏览,点击文件切换。右上角可复制代码、复制路径或单独下载文件。在线视图只覆盖文本源码,完整工程请下载 zip。
textxmldartjsonkotlin
61 text files · 3,719 lines
dartlib/src/state_demo_page.dart343 行 · 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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
// 演示页面:把"状态"的几种典型来源放在一起——
// 1. 纯内存计数(setState)
// 2. 用户输入(TextEditingController)
// 3. 异步结果(Future + mounted 检查)
// 4. 外部事件源(Stream 订阅 + dispose 取消)
import 'dart:async';
import 'package:flutter/material.dart';
class StateDemoPage extends StatelessWidget {
const StateDemoPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('StatefulWidget 与生命周期')),
body: ListView(
padding: const EdgeInsets.all(16),
children: const [
CounterCard(),
SizedBox(height: 12),
TodoCard(),
SizedBox(height: 12),
AsyncCard(),
SizedBox(height: 12),
TickerCard(),
],
),
);
}
}
// ===========================================================================
// 1. setState:状态改变 → 本 State 的 build 重新执行
// ===========================================================================
class CounterCard extends StatefulWidget {
const CounterCard({super.key, this.step = 1});
/// 父级可以改的"配置"。它变化时触发 `didUpdateWidget`,但不会重置 `_count`。
final int step;
@override
State<CounterCard> createState() => _CounterCardState();
}
class _CounterCardState extends State<CounterCard> {
int _count = 0;
/// 仅用于教学:统计 build 次数。
/// 生产代码不要在 build 里改字段——build 必须保持纯函数(ch02 讲过)。
int _builds = 0;
int get count => _count;
void bump(int delta) => setState(() => _count += delta * widget.step);
void reset() => setState(() => _count = 0);
@override
void didUpdateWidget(CounterCard oldWidget) {
super.didUpdateWidget(oldWidget);
// 父级传了新的 step:可以做"配置变化"的副作用,但**不要**在这里 setState。
debugPrint('CounterCard: step ${oldWidget.step} → ${widget.step}');
}
@override
Widget build(BuildContext context) {
_builds++;
return DemoCard(
title: 'setState:最小状态单元',
subtitle: 'State 对象跨 build 存活,字段就是"状态"',
children: [
Text(
'count = $_count',
key: const Key('count-text'),
style: Theme.of(context).textTheme.headlineSmall,
),
Text('build 次数 = $_builds', key: const Key('build-count')),
const SizedBox(height: 8),
Wrap(
spacing: 8,
children: [
FilledButton(key: const Key('inc'), onPressed: () => bump(1), child: const Text('+1')),
FilledButton.tonal(
key: const Key('dec'),
onPressed: () => bump(-1),
child: const Text('-1'),
),
OutlinedButton(key: const Key('reset'), onPressed: reset, child: const Text('归零')),
],
),
],
);
}
}
// ===========================================================================
// 2. 用户输入:TextEditingController 是"有生命周期的资源",必须 dispose
// ===========================================================================
class TodoCard extends StatefulWidget {
const TodoCard({super.key});
@override
State<TodoCard> createState() => _TodoCardState();
}
class _TodoCardState extends State<TodoCard> {
final TextEditingController _controller = TextEditingController();
final List<String> _items = <String>[];
@override
void dispose() {
// controller 持有原生侧的资源(输入法连接、选区、监听器),必须显式释放。
_controller.dispose();
super.dispose();
}
void _add() {
final text = _controller.text.trim();
if (text.isEmpty) return;
setState(() {
_items.add(text);
_controller.clear(); // 清空输入框
});
}
void _removeAt(int index) => setState(() => _items.removeAt(index));
@override
Widget build(BuildContext context) {
return DemoCard(
title: '用户输入:controller + dispose',
subtitle: 'TextField 的值不在 State 字段里,而在 controller 里',
children: [
Row(
children: [
Expanded(
child: TextField(
key: const Key('todo-input'),
controller: _controller,
decoration: const InputDecoration(
labelText: '待办事项',
isDense: true,
border: OutlineInputBorder(),
),
onSubmitted: (_) => _add(),
),
),
const SizedBox(width: 8),
FilledButton(key: const Key('todo-add'), onPressed: _add, child: const Text('添加')),
],
),
const SizedBox(height: 8),
if (_items.isEmpty)
const Text('(空列表)', key: Key('todo-empty'))
else
for (var i = 0; i < _items.length; i++)
ListTile(
key: Key('todo-item-$i'),
dense: true,
contentPadding: EdgeInsets.zero,
title: Text(_items[i]),
trailing: IconButton(
icon: const Icon(Icons.delete_outline),
onPressed: () => _removeAt(i),
),
),
],
);
}
}
// ===========================================================================
// 3. 异步:await 之后必须检查 mounted
// ===========================================================================
class AsyncCard extends StatefulWidget {
const AsyncCard({super.key, this.delay = const Duration(milliseconds: 300)});
final Duration delay;
@override
State<AsyncCard> createState() => _AsyncCardState();
}
class _AsyncCardState extends State<AsyncCard> {
String? _data;
Object? _error;
bool _loading = false;
@override
void initState() {
super.initState();
// initState 里不能 await(它必须是同步的),但可以"发射后不管"。
// 真正的错误处理放在 _load 内部,靠 mounted 兜住"页面已销毁"的情况。
unawaited(_load());
}
Future<void> _load() async {
setState(() {
_loading = true;
_error = null;
});
try {
final String value = await Future<String>.delayed(
widget.delay,
() => '服务器返回: 42',
);
if (!mounted) return; // 关键:await 期间页面可能已被销毁
setState(() {
_data = value;
_loading = false;
});
} catch (e) {
if (!mounted) return;
setState(() {
_error = e;
_loading = false;
});
}
}
@override
Widget build(BuildContext context) {
return DemoCard(
title: '异步结果:await 之后查 mounted',
subtitle: 'setState() called after dispose() 是 Flutter 第一大运行时错误',
children: [
if (_loading)
const Padding(
padding: EdgeInsets.symmetric(vertical: 8),
child: Row(
children: [
SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2)),
SizedBox(width: 12),
Text('加载中…', key: Key('async-loading')),
],
),
)
else if (_error != null)
Text('出错: $_error', key: const Key('async-error'))
else
Text(_data ?? '(无数据)', key: const Key('async-data')),
const SizedBox(height: 8),
OutlinedButton(
key: const Key('async-reload'),
onPressed: _loading ? null : _load,
child: const Text('重新加载'),
),
],
);
}
}
// ===========================================================================
// 4. 外部事件源:Stream 订阅在 dispose 里必取消
// ===========================================================================
class TickerCard extends StatefulWidget {
const TickerCard({super.key, this.period = const Duration(seconds: 1)});
final Duration period;
@override
State<TickerCard> createState() => _TickerCardState();
}
class _TickerCardState extends State<TickerCard> {
StreamSubscription<int>? _sub;
int _ticks = 0;
@override
void initState() {
super.initState();
_sub = Stream<int>.periodic(widget.period, (int i) => i).listen((int i) {
if (!mounted) return;
setState(() => _ticks = i + 1);
});
}
@override
void dispose() {
// 不 cancel → 定时器继续跑,回调继续持有 State,GC 永远回收不了。
unawaited(_sub?.cancel());
super.dispose();
}
@override
Widget build(BuildContext context) {
return DemoCard(
title: '外部事件:订阅必须取消',
subtitle: 'initState 订阅 / dispose 取消,成对出现',
children: [
Text('已过 $_ticks 秒', key: const Key('ticks-text')),
const SizedBox(height: 4),
const Text('每秒推送一次,来自 Stream.periodic'),
],
);
}
}
// ===========================================================================
// 公共卡片壳
// ===========================================================================
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 20 KB · json 4 KB
本地运行
zip → 解压 → 执行$cd examples/ch06-state && flutter run -d macos(Linux/Windows 同理)这个 zip 里有什么
- • 完整工程目录(含 Android / iOS / 桌面平台脚手架)
- • lib / bin / test / native 全部源码与测试
- • pubspec.yaml、锁文件与平台配置文件
- • 已排除 .dart_tool / build / target / ephemeral 等构建产物
已验证
- flutter analyze 0 告警、flutter test 10 个用例全绿、flutter build macos --debug 真实构建并启动成功