FlutterCH 09ch09_navigation
ch09-navigation
Flutter 路由与导航、资源与主题。完整工程共 103 个文件,其中 63 个文本源文件可在下面在线阅读。
63
在线文本文件
3,892
源码行数
dart / c / yaml
语言
280 KB
打包体积
在线阅读源码
左侧按目录浏览,点击文件切换。右上角可复制代码、复制路径或单独下载文件。在线视图只覆盖文本源码,完整工程请下载 zip。
textxmldartjsonkotlin
63 text files · 3,892 lines
dartlib/src/routes.dart378 行 · 12 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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
// 页面与路由常量。
//
// 路由的三种写法都在这里出现:
// 1. Navigator.push(MaterialPageRoute(...)) —— 直接构造,最灵活
// 2. Navigator.pushNamed('/detail', arguments: args) —— 具名 + 参数
// 3. onGenerateRoute 里把 Object? 参数转成强类型
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'profile.dart';
import 'theme.dart';
const String homeRoute = '/';
const String aboutRoute = '/about';
const String detailRoute = '/detail';
/// 强类型路由参数:`settings.arguments` 是 `Object?`,在 onGenerateRoute 里转成它。
@immutable
class DetailArgs {
const DetailArgs({required this.title, this.note = ''});
final String title;
final String note;
}
// ===========================================================================
// 首页
// ===========================================================================
class HomePage extends StatefulWidget {
const HomePage({super.key, required this.onToggleTheme});
final VoidCallback onToggleTheme;
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String? _lastResult;
/// 演示 1:直接构造路由,await 拿到返回值。
Future<void> _pushDetailDirect() async {
final String? result = await Navigator.of(context).push<String>(
MaterialPageRoute<String>(
builder: (BuildContext context) => const DetailPage(
args: DetailArgs(title: '直接构造的路由', note: '返回时把这段文字带回去'),
),
),
);
if (!mounted) return; // await 之后先检查(ch06 的规矩)
setState(() => _lastResult = result ?? '(无返回值)');
}
/// 演示 2:具名路由 + arguments,同样能拿返回值。
Future<void> _pushDetailNamed() async {
final String? result = await Navigator.of(context).pushNamed<String>(
detailRoute,
arguments: const DetailArgs(title: '具名路由 + 参数'),
);
if (!mounted) return;
setState(() => _lastResult = result ?? '(无返回值)');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('路由与导航'),
actions: [
// 桌面端习惯把"暗色模式"开关放右上角。
IconButton(
key: const Key('theme-toggle'),
tooltip: '切换亮/暗主题',
onPressed: widget.onToggleTheme,
icon: Icon(
Theme.of(context).brightness == Brightness.dark
? Icons.light_mode_outlined
: Icons.dark_mode_outlined,
),
),
],
),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
const _BrandBanner(),
const SizedBox(height: 12),
const ProfileCard(),
const SizedBox(height: 12),
_Section(
title: 'Navigator 1.0:页面栈',
children: [
Wrap(
spacing: 8,
runSpacing: 8,
children: [
FilledButton(
key: const Key('push-direct'),
onPressed: _pushDetailDirect,
child: const Text('push 详情页'),
),
FilledButton.tonal(
key: const Key('push-named'),
onPressed: _pushDetailNamed,
child: const Text('pushNamed /detail'),
),
OutlinedButton(
key: const Key('push-about'),
onPressed: () => Navigator.of(context).pushNamed(aboutRoute),
child: const Text('pushNamed /about'),
),
TextButton(
key: const Key('push-unknown'),
onPressed: () => Navigator.of(context).pushNamed('/nope'),
child: const Text('未知路由'),
),
],
),
const SizedBox(height: 8),
Text(
_lastResult == null ? '上次返回值:(还没返回过)' : '上次返回值:$_lastResult',
key: const Key('last-result'),
),
],
),
const SizedBox(height: 12),
const _Section(
title: '路由栈 Depth',
children: [
Text('push 之后按 AppBar 的返回箭头(或桌面端 Alt+←)出栈;'
'详情页有未保存内容时会先弹确认框。'),
],
),
],
),
);
}
}
/// 用 ThemeExtension 取自定义颜色。
class _BrandBanner extends StatelessWidget {
const _BrandBanner();
@override
Widget build(BuildContext context) {
return Container(
key: const Key('brand-banner'),
width: double.infinity,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: context.brand.banner,
borderRadius: BorderRadius.circular(12),
),
child: Text(
'BrandColors 来自 ThemeExtension',
style: TextStyle(color: context.brand.onBanner, fontWeight: FontWeight.w600),
),
);
}
}
// ===========================================================================
// 资源(assets):从打包产物里读 JSON
// ===========================================================================
class ProfileCard extends StatefulWidget {
const ProfileCard({super.key, this.loader = _loadFromBundle});
/// 注入点:默认从 assets 读,测试里可以传一个假的 loader。
/// 这就是"传输层可替换、解析层纯净"的最小实现。
final Future<String> Function() loader;
static Future<String> _loadFromBundle() =>
rootBundle.loadString('assets/data/profile.json');
@override
State<ProfileCard> createState() => _ProfileCardState();
}
class _ProfileCardState extends State<ProfileCard> {
Profile? _profile;
Object? _error;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
try {
// rootBundle 读的是"打进安装包"的资源,不是文件系统路径。
// 桌面端同样如此:assets 在构建时被塞进 AssetManifest。
final String raw = await widget.loader();
if (!mounted) return;
setState(() => _profile = Profile.parse(raw));
} catch (e) {
if (!mounted) return;
setState(() => _error = e);
}
}
@override
Widget build(BuildContext context) {
final Profile? profile = _profile;
return _Section(
title: 'assets:assets/data/profile.json',
children: [
if (_error != null)
Text('加载失败: $_error', key: const Key('profile-error'))
else if (profile == null)
const Text('加载中…', key: Key('profile-loading'))
else ...[
Text('${profile.name} · ${profile.role}', key: const Key('profile-name')),
const SizedBox(height: 4),
Wrap(
spacing: 6,
children: [for (final String tag in profile.tags) Chip(label: Text(tag))],
),
],
],
);
}
}
// ===========================================================================
// 详情页:带返回值的路由 + PopScope 拦截
// ===========================================================================
class DetailPage extends StatefulWidget {
const DetailPage({super.key, required this.args});
final DetailArgs args;
@override
State<DetailPage> createState() => _DetailPageState();
}
class _DetailPageState extends State<DetailPage> {
late final TextEditingController _note = TextEditingController(text: widget.args.note);
bool get _dirty => _note.text.trim().isNotEmpty;
@override
void dispose() {
_note.dispose();
super.dispose();
}
/// 有未保存内容时拦截返回:先弹确认框。
Future<void> _onPopInvoked(bool didPop, Object? result) async {
if (didPop) return; // 已经出栈,什么都不用做
final bool discard = await showDialog<bool>(
context: context,
builder: (BuildContext ctx) => AlertDialog(
title: const Text('放弃编辑?'),
content: const Text('输入框里还有内容,返回会丢失。'),
actions: [
TextButton(
key: const Key('keep-editing'),
onPressed: () => Navigator.of(ctx).pop(false),
child: const Text('继续编辑'),
),
FilledButton(
key: const Key('discard'),
onPressed: () => Navigator.of(ctx).pop(true),
child: const Text('放弃'),
),
],
),
) ??
false;
if (!mounted || !discard) return;
// 关键:先解除拦截并等一帧,再 pop,否则会再次触发本回调形成死循环。
setState(() => _note.clear());
await WidgetsBinding.instance.endOfFrame;
if (!mounted) return;
Navigator.of(context).pop();
}
@override
Widget build(BuildContext context) {
return PopScope<void>(
canPop: !_dirty,
onPopInvokedWithResult: _onPopInvoked,
child: Scaffold(
appBar: AppBar(title: Text(widget.args.title)),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text('当前路由: ${ModalRoute.of(context)?.settings.name ?? '(未命名)'}'),
const SizedBox(height: 12),
TextField(
key: const Key('detail-note'),
controller: _note,
onChanged: (_) => setState(() {}), // 只是为了更新 canPop
decoration: const InputDecoration(
labelText: '要带回首页的文字',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 12),
FilledButton(
key: const Key('pop-with-result'),
onPressed: () => Navigator.of(context).pop(_note.text.trim()),
child: const Text('返回并带回结果'),
),
const SizedBox(height: 8),
OutlinedButton(
key: const Key('pop-empty'),
onPressed: () => Navigator.of(context).pop(),
child: const Text('返回不带结果'),
),
],
),
),
),
);
}
}
class AboutPage extends StatelessWidget {
const AboutPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('关于')),
body: const Center(child: Text('具名路由表 routes: 里的一页', key: Key('about-text'))),
);
}
}
class UnknownPage extends StatelessWidget {
const UnknownPage({super.key, this.name});
final String? name;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('404')),
body: Center(child: Text('没有这个路由: $name', key: const Key('unknown-text'))),
);
}
}
class _Section extends StatelessWidget {
const _Section({required this.title, required this.children});
final String title;
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),
const Divider(height: 16),
...children,
],
),
),
);
}
}
代码构成:text 60 KB · xml 41 KB · dart 27 KB · json 4 KB
本地运行
zip → 解压 → 执行$cd examples/ch09-navigation && flutter run -d macos这个 zip 里有什么
- • 完整工程目录(含 Android / iOS / 桌面平台脚手架)
- • lib / bin / test / native 全部源码与测试
- • pubspec.yaml、锁文件与平台配置文件
- • 已排除 .dart_tool / build / target / ephemeral 等构建产物
已验证
- flutter analyze 0 告警、flutter test 14 个用例全绿、flutter build macos --debug 真实构建并启动成功