第一步配置路由
1 新建routes_mamager.dart文件
//第一步配置路由
final routes = {
//无参数传递
'/': (context) => MainContent(),
//有参数传递,ProductList构造
//final Map arguments;
//ProductList({Key key, this.arguments}) : super(key: key) {}
'/product': (context, {arguments}) => ProductList(arguments: arguments)
};
//固定写法
// ignore: strong_mode_top_level_function_literal_block
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;
}
}
};
2 在Flutter的入口出初始化路由:
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
initialRoute: '/', //初始化的时候加载的路由
onGenerateRoute: onGenerateRoute,
);
}
3 使用
传参有返回值,arguments是传到下一级的参数,then((value))接收上级返回传回的参数
Navigator.pushNamed(context, '/product', arguments: {'pid': 456})
.then((value) {//"this is data"
setState(() {
name = value;
});
});
返回上级界面有返回值
Navigator.pop(context, "this is data");
无参数返回值
Navigator.pushNamed(context, '/product');
替换路由
Navigator.pushReplacementNamed(context, '/');
返回根
Navigator.of(context).pushAndRemoveUntil(new MaterialPageRoute(builder: (context)=> new Tabs()), (route)=> route==null );