Navigator 1.0 详细信息可以查看官网 给特定的 route 传参
一.定义路由名称
创建 routate_name.dart文件存储路由名称
///定义路由名字
class RotateName {
static const String rootPage = "/";
static const String loginPage = "LOGIN_PAGE";
}
二.定义路由
创建routate_map.dart
///存储路由关系的Map 将路由名称和页面对应
Map rotateMap = {
RotateName.rootPage: (context) => const RootPage(),
RotateName.loginPage: (context, {arguments}) =>
LoginPage(arguments: arguments),
};
三.定义onGenerateRoute
有关onGenerateRoute的定义 查看onGenerateRoute
Route<dynamic> generateRoute(RouteSettings settings) {
//获取rotateName
final String? rotaName = settings.name;
//找到对应的页面
final Function? buildPage = rotateMap[rotaName];
//如果对应的页面是空的就返回一个空页面
//MaterialPageRoute:页面切换方式为从下往上,
//CupertinoPageRoute:页面切换方式从左往右 还可以自定义切换方式
if (buildPage == null) {
return MaterialPageRoute(
builder: (_) => const Scaffold(
body: Center(
child: Text("Page Not Found!!!!"),
),
));
}
//查看携带的参数
Map? args = settings.arguments as Map<dynamic, dynamic>?;
if (args != null) {
return MaterialPageRoute(
builder: (context) => buildPage(context, args));
}
return MaterialPageRoute(builder: (context) => buildPage(context));
}
四.封装路由跳转方法 统一管理
class NavigatorUtils {
//用 Navigator.pop() 回退到第一个路由
static pop(BuildContext context, {Object? arguments}) {
if (arguments == null) {
Navigator.pop(context);
} else {
Navigator.pop(context, arguments);
}
}
//用 Navigator.push() 跳转到第二个路由
static push(BuildContext context, String routeName, {arguments}) async {
final Function? buildPage = rotateMap[routeName];
if (arguments != null) {
return await Navigator.push(
context,
CupertinoPageRoute(
builder: (context) => buildPage!(context, arguments: arguments),
settings: RouteSettings(name: routeName)));
} else {
return await Navigator.push(
context,
CupertinoPageRoute(
builder: (context) => buildPage!(context),
settings: RouteSettings(name: routeName)));
}
}
//....还有其他方法都可以加进来
}
五.在Main.dart中修改
return MaterialApp(
title: 'Flutter Navigator1.0 Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
//之前定义的generateRoute
onGenerateRoute: generateRoute,
//初始页面页面名称为"/"
initialRoute: RotateName.rootPage,
);
六.使用
TextButton(
onPressed: () {
NavigatorUtils.push(context, RotateName.loginPage,arguments: {"name":"1122"});},
child: const Text("这里叫跳转"))
网友评论