本篇轉(zhuǎn)載于
https://blog.csdn.net/ww897532167/article/details/125680502
1 匿名方式 實(shí)現(xiàn)頁(yè)面跳轉(zhuǎn)與返回
1.1 跳轉(zhuǎn)下一頁(yè)
Android風(fēng)格
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const Page1()),
);
iOS風(fēng)格
Navigator.push(
context,
CupertinoPageRoute(builder: (context) => const Page1()),
);
從下到上彈出頁(yè)面
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const Page1(),
// 全屏彈窗效果,從下往上出現(xiàn)
fullscreenDialog: true,
),
);
1.2 返回上一頁(yè)
Navigator.of(context).pop()
1.3 傳參跳轉(zhuǎn)下一頁(yè)并獲取返回值
傳參跳轉(zhuǎn)下一頁(yè),并獲取返回值
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const Page1(param: 'param'),
),
);
print(result);
攜帶參數(shù)返回上一頁(yè)
Navigator.of(context).pop('result value');
2 路由的方式 實(shí)現(xiàn)頁(yè)面跳轉(zhuǎn)與返回
2.1 路由配置
在MaterialApp或CupertinoApp中配置路由名稱和頁(yè)面的對(duì)應(yīng)關(guān)系:
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),
// 默認(rèn)展示的頁(yè)面路由
initialRoute: "/",
onGenerateRoute: (settings) {
final routeName = settings.name;
dynamic arguments = settings.arguments;
switch (routeName) {
case "/":
return CupertinoPageRoute(builder: (context) => const RootPage());
case "/page1":
// 可接收參數(shù)
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 攜帶參數(shù)跳轉(zhuǎn)頁(yè)面 并獲取返回值
普通跳轉(zhuǎn)
Navigator.pushNamed(context, '/page1');
傳參
Navigator.pushNamed(context, '/page1',arguments: 'param');
獲取返回值
var result = await Navigator.pushNamed(context, '/page1', arguments: 'param');
2.3 跳轉(zhuǎn)或返回指定頁(yè)面并清空棧
銷毀當(dāng)前頁(yè)面并跳轉(zhuǎn)新的頁(yè)面
Navigator.popAndPushNamed(context, '/page2');
返回指定頁(yè)面
// 返回指定頁(yè)面
Navigator.popUntil(context, (route) => route.settings.name == '/');
// 返回根頁(yè)面
Navigator.popUntil(context, (route) => route.isFirst);
跳轉(zhuǎn)至某頁(yè)面,并銷毀之前的頁(yè)面
Navigator.pushNamedAndRemoveUntil(
context, '/page2', (route) => route.settings.name == '/');
3 返回指定頁(yè)面(跨多個(gè)頁(yè)面)并傳遞返回值
配置路由時(shí) 添加一個(gè)參數(shù) Map()
switch (routeName) {
case "/":
return CupertinoPageRoute(
settings: RouteSettings(
name: "/",
arguments: Map(), //用于 popUntil 返回傳值
),
builder: (context) => const RootPage(),
);
...
}
返回指定頁(yè)面 ’/’
Navigator.popUntil(context, (route) {
if (route.settings.name == '/') {
(route.settings.arguments as Map)['result'] = '返回值';
return true;
} else {
return false;
}
});
‘/’ 頁(yè)面 獲取返回值
await Navigator.of(context).pushNamed('/page2');
if (mounted) {
final arguments =
ModalRoute.of(context)?.settings.arguments as Map;
final result = arguments['result'];
}