一、 路由分离
在lib目录下面创建routers目录,在该目录下创建Routers.dart文件, 内容如下:
//配置路由
//第一步配置路由
final routes = {
'/':(context,{arguments})=>Tabs(),
'/form': (context) => FormPage(),
'/product': (context) => ProductPage(),
'/search': (context, {arguments}) => SearchPage(arguments: arguments),//传参数
'/productinfo': (context, {arguments}) => ProductInfoPage(arguments: arguments),
};
//固定写法
var onGenerateRoute = (RouteSettings settings) {
final String name = settings.name;
final Function pageContentBuilder = routes[name];
if (pageContentBuilder != null) {
if (settings.arguments != null) {
final Route route = MaterialPageRoute(
builder: (context) =>
pageContentBuilder(context, arguments: settings.arguments));
return route;
} else {
final Route route =
MaterialPageRoute(builder: (context) => pageContentBuilder(context));
return route;
}
}
};
在Flutter的入口出初始化路由:
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
initialRoute: '/', //初始化的时候加载的路由
onGenerateRoute: onGenerateRoute,
);
}
使用方法:
带参数:
//路由跳转
Navigator.pushNamed(context, '/productinfo',
arguments: {'pid': 456});
不带参数:
onPressed: (){
//路由跳转
Navigator.pushNamed(context, '/product');
},
二、替换路由
Navigator.pushReplacementNamed(context, '/third');
三、返回跟
//返回根
Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute(builder: (context)=> new Tabs()), (route)=> route==null );
over