本篇转载于
https://blog.csdn.net/ww897532167/article/details/125680502
1 匿名方式 实现页面跳转与返回
1.1 跳转下一页
Android风格
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const Page1()),
);
iOS风格
Navigator.push(
context,
CupertinoPageRoute(builder: (context) => const Page1()),
);
从下到上弹出页面
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const Page1(),
// 全屏弹窗效果,从下往上出现
fullscreenDialog: true,
),
);
1.2 返回上一页
Navigator.of(context).pop()
1.3 传参跳转下一页并获取返回值
传参跳转下一页,并获取返回值
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const Page1(param: 'param'),
),
);
print(result);
携带参数返回上一页
Navigator.of(context).pop('result value');
2 路由的方式 实现页面跳转与返回
2.1 路由配置
在MaterialApp或CupertinoApp中配置路由名称和页面的对应关系:
initialRoute
onGenerateRoute
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(primaryColor: Colors.red),
// 默认展示的页面路由
initialRoute: "/",
onGenerateRoute: (settings) {
final routeName = settings.name;
dynamic arguments = settings.arguments;
switch (routeName) {
case "/":
return CupertinoPageRoute(builder: (context) => const RootPage());
case "/page1":
// 可接收参数
String? param = arguments as String?;
return CupertinoPageRoute(
builder: (context) => Page1(param: param));
default:
return CupertinoPageRoute(
builder: (_) => Scaffold(
body: Center(
child: Text('UnknownScreen $routeName'),
),
),
);
}
},
);
}
}
2.2 携带参数跳转页面 并获取返回值
普通跳转
Navigator.pushNamed(context, '/page1');
传参
Navigator.pushNamed(context, '/page1',arguments: 'param');
获取返回值
var result = await Navigator.pushNamed(context, '/page1', arguments: 'param');
2.3 跳转或返回指定页面并清空栈
销毁当前页面并跳转新的页面
Navigator.popAndPushNamed(context, '/page2');
返回指定页面
// 返回指定页面
Navigator.popUntil(context, (route) => route.settings.name == '/');
// 返回根页面
Navigator.popUntil(context, (route) => route.isFirst);
跳转至某页面,并销毁之前的页面
Navigator.pushNamedAndRemoveUntil(
context, '/page2', (route) => route.settings.name == '/');
3 返回指定页面(跨多个页面)并传递返回值
配置路由时 添加一个参数 Map()
switch (routeName) {
case "/":
return CupertinoPageRoute(
settings: RouteSettings(
name: "/",
arguments: Map(), //用于 popUntil 返回传值
),
builder: (context) => const RootPage(),
);
...
}
返回指定页面 ’/’
Navigator.popUntil(context, (route) {
if (route.settings.name == '/') {
(route.settings.arguments as Map)['result'] = '返回值';
return true;
} else {
return false;
}
});
‘/’ 页面 获取返回值
await Navigator.of(context).pushNamed('/page2');
if (mounted) {
final arguments =
ModalRoute.of(context)?.settings.arguments as Map;
final result = arguments['result'];
}
网友评论