示例工程 ch09-navigation
ch09-navigation/lib/src/routes.dart
// 页面与路由常量。
//
// 路由的三种写法都在这里出现:
// 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,
],
),
),
);
}
}