示例工程 ch06-state
ch06-state/lib/src/state_demo_page.dart
// 演示页面:把"状态"的几种典型来源放在一起——
// 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,
],
),
),
);
}
}