Navigator
基本用法
Navigator.of(context).push(
MaterialPageRoute(
builder: (ctx) {
return Demo();
}
));
参数传递
Future<Result> result = Navigator.of(context).push(
MaterialPageRoute(
builder: (ctx) {
return Demo(title: '传递参数');
}
));
result.then((val) {
print("返回的参数");
})
命名路由
return MaterialApp(
title: 'Flutter Demo',
routes: {
"/home": (ctx) => HomePage(),
"/detail": (ctx) => DetailPage()
},
);
跳转
Navigator.of(context).pushNamed("/detail");
开发中避免使用魔法字符串
class HomePage extends StatefulWidget {
static const String routeName = "/home";
}
class DetailPage extends StatelessWidget {
static const String routeName = "/detail";
}
routes: {
HomePage.routeName: (ctx) => HomePage(),
DetailPage.routeName: (ctx) => DetailPage()
},
参数传递
Navigator.of(context).pushNamed(DetailPage.routeName, arguments: "this is a arguments");
参数获取
Widget build(BuildContext context) {
final message = ModalRoute.of(context).settings.arguments;
}
路由钩子
onGenerateRoute
///页面跳转
Navigator.of(context).pushNamed(routeName, arguments: 'pageParams');
///参数传递
onGenerateRoute: (settings) {
if (settings.name == HomePage.routeName) {
return MaterialPageRoute(
builder: (ctx) {
return HomePage(settings.arguments);
}
);
}
return null;
},
onUnknownRoute
路由地址错误处理
MaterialApp(
...
onGenerateRoute: (setting) {
if (setting.name == 'pageName') {
return MaterialPageRoute(
builder: (ctx) {
return ConstDemo(setting.arguments);
}
);
}
return null;
},
///路由错误页面
onUnknownRoute: (setting) {
return MaterialPageRoute(
builder: (ctx) {
return UnKnowPage();
}
);
},
);
}
路由切换动画
Navigator.of(context).push(PageRouteBuilder(
transitionDuration: Duration(seconds: 3),
pageBuilder: (ctx, animation1, animation2) {
return FadeTransition(
opacity: animation1,
child: Demo());
}
));
如果是pushNames的话在MaterialApp的onGenerateRoute处理
MaterialApp(
...
onGenerateRoute: (setting) {
if (setting.name == 'demo') {
return PageRouteBuilder(
transitionDuration: Duration(seconds: 3),
pageBuilder: (ctx, animation1, animation2) {
return FadeTransition(
opacity: animation1,
child: Demo());
}
);
}
return null;
},
);