78 lines
2.9 KiB
Dart
78 lines
2.9 KiB
Dart
import 'package:flutter/material.dart';
|
||
import 'package:flutter_screenutil/flutter_screenutil.dart';
|
||
|
||
import 'package:new_learn/pages/demo/detail_page.dart';
|
||
import 'package:new_learn/pages/demo/picker_page.dart';
|
||
|
||
/// 路由首页
|
||
/// 三个按钮演示三种跳转姿势(push 传参 / 返回结果 / 命名路由)
|
||
class RouterHomePage extends StatelessWidget {
|
||
const RouterHomePage({super.key});
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
return Scaffold(
|
||
appBar: AppBar(title: const Text('路由导航 Demo')),
|
||
body: Padding(
|
||
padding: EdgeInsets.all(16.w),
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||
children: [
|
||
// ---- 方式1:push + 构造函数传参 ----
|
||
FilledButton.icon(
|
||
icon: const Icon(Icons.send),
|
||
label: const Text('方式1:push 构造传参 → 详情页'),
|
||
onPressed: () {
|
||
Navigator.push(
|
||
context,
|
||
MaterialPageRoute(
|
||
builder: (_) => const DetailPage(name: '张三', age: 18),
|
||
),
|
||
);
|
||
},
|
||
),
|
||
SizedBox(height: 12.h),
|
||
// ---- 方式2:push + 等待返回结果 ----
|
||
FilledButton.tonalIcon(
|
||
icon: const Icon(Icons.checklist),
|
||
label: const Text('方式2:push 选择器并接收返回结果'),
|
||
onPressed: () async {
|
||
// 注意:push 返回的是 Future,用 await 接收 pop 带回来的值
|
||
final result = await Navigator.push<String>(
|
||
context,
|
||
MaterialPageRoute(builder: (_) => const PickerPage()),
|
||
);
|
||
if (context.mounted) {
|
||
ScaffoldMessenger.of(context).showSnackBar(
|
||
SnackBar(content: Text('你选择了:${result ?? '未选择'}')),
|
||
);
|
||
}
|
||
},
|
||
),
|
||
SizedBox(height: 12.h),
|
||
// ---- 方式3:pushNamed 命名路由 + arguments 传参 ----
|
||
FilledButton.icon(
|
||
icon: const Icon(Icons.route),
|
||
label: const Text('方式3:pushNamed 命名路由 + arguments'),
|
||
onPressed: () {
|
||
Navigator.pushNamed(
|
||
context,
|
||
'/detail',
|
||
arguments: {'name': '李四', 'age': 25},
|
||
);
|
||
},
|
||
),
|
||
SizedBox(height: 24.h),
|
||
Text(
|
||
'知识点:页面跳转是【入栈/出栈】。'
|
||
'返回页 pop 时带值 → 接收页 await push 拿到值。'
|
||
'命名路由的 arguments 是 dynamic,取值需判空强转。',
|
||
style: TextStyle(fontSize: 13.sp, color: Color(0xFF888888)),
|
||
),
|
||
],
|
||
),
|
||
),
|
||
);
|
||
}
|
||
}
|