Flutter页面跳转
使用Flutter切换到一个新界面,并且能跳回来
在一个App中一般会有很多页面,这些页面需要相互跳转,传递信息并进行交换。比如列表要跳到详情,活动入口跳转到活动页面等等。Android中的页面可以是Activity;iOS中使用ViewController。在Flutter中,是如何进行页面跳转的呢?
1、使用Navigator来切换页面。
- Navigator.push: 跳到另一个页面
- Navigator.pop: 从当前页面回退到上一个页面
首先需要创建两个页面,FirstPage和SecondPage。代码如下:
class FirstPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(appBar: AppBar(title: Text('First page'),),
body: Center(child: RaisedButton(
child: Text('Go to 2nd page'),
onPressed: () {
print('This is first page');
// 执行想要的操作..........
Navigator.push(context,
MaterialPageRoute(builder: (context) => SecondPage()));
}),),);
}
}
class SecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(appBar: AppBar(title: Text('Second page'),),
body: Center(child: RaisedButton(
child: Text("Go back"),
onPressed: () {
print('This is 2nd page');
// 执行操作........
Navigator.pop(context);
}),),);
}
}
如上面代码用Navigator.push跳转去第二个界面,push方法会向栈中添加一个由Navigator管理的Route。push方法接受一个Route(暂称为路由),这里新建一个Route,使用用MaterialPageRoute。
在第二个页面中用Navigator.pop回到第一个界面Navigator.pop会移除navigator管理的当前的路由(效果是移除当前界面)。
2、 使用路由统一管理跳转
上面只有两个页面,所以直接在代码中实现跳转就可以了。但是实际项目中会有很多页面,如果每个页面都这样跳转,就会显的非常混乱,并且不能统一管理跳转。
步骤:
1 注册程序入口通过onGenerateRoute统一注册路由
2 定义相应的页面对应的路径
3 根据路径跳转到对应的页面
不多说,直接上代码:
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocBuilder<GlobalBloc, GlobalState>(builder: (_, state) {
return MaterialApp(
showPerformanceOverlay: state.showPerformanceOverlay,
title: 'Flutter Widgets',
debugShowCheckedModeBanner: false,
onGenerateRoute: XRouter.generateRoute,
theme: ThemeData(
primarySwatch: state.themeColor,
fontFamily: state.fontFamily,
),
home: XSplash(),
);
});
}
}
自定义XRouter类
class XRouter {
static const String firstpage = 'firstpage';
static const String secondpage = 'secondpage';
static Route<dynamic> generateRoute(RouteSettings settings) {
switch (settings.name) {
//根据名称跳转相应页面
case firstpage:
return Right2LeftRouter(child: FirstPage());
case secondpage:
return Right2LeftRouter(child: SecondPage());
default:
return MaterialPageRoute(
builder: (_) => Scaffold(
body: Center(
child: Text('No route defined for ${settings.name}'),
),
));
}
}
}
最后在页面中使用
class FirstPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(appBar: AppBar(title: Text('First page'),),
body: Center(child: RaisedButton(
child: Text('Go to 2nd page'),
onPressed: () {
print('This is first page');
// 执行想要的操作..........
Navigator.of(context).pushReplacementNamed(XRouter.secondpage);
}),),);
}
}
3、页面间传值
使用第一种方式,传值跳转
//路由跳转 并 传值 固定写法 PageB 为目标页面类名 传值
Navigator.push(context,
MaterialPageRoute(builder: (context) => SecondPage(para: '你好 SecondPage!',)));
在页面SecondPage中接收,
//定义变量
var para;
//重写构造 接收数据
SecondPage({this.para = '没有接收到数据'});
待续。。。