咱们知道移动应用页面跳转是很是重要的一部分,几乎咱们的程序和用户打交道的就是页面,或者叫view,咱们Android基本都是Activity和Fragment。并且Flutter当中叫作Route,它就是与用户打交道的页面。本文详细探索一下Flutter当中页面之间是怎么交互的。git
Route相似Android中Activity,因此Flutter中的页面跳转相似Android中Activity之间跳转,Intent携带传递的数据。github
咱们如今看看Flutter中是怎么进行页面交互的,也就是页面之间的跳转。less
从上一个页面A跳转下一个页面B,有两种方式:async
返回上一个页面:Navigator.pop();ui
提示: 经过Navigator.pushNamed()跳转的,记住必定要注册routeName
!!!this
提示: 经过Navigator.pushNamed()跳转的,记住必定要注册routeName
!!!spa
提示: 经过Navigator.pushNamed()跳转的,记住必定要注册routeName
!!!code
重要的事情说三遍😏😏😏!!!router
代码以下:cdn
//第一种:经过Navigator.push()跳转,相似Android中的startActivity(),指定Activity类名这种方式;
Navigator.push(context, MaterialPageRoute(builder: (context) {
return ThirdRoute();
}));
//第二种方式:经过Navigator.pushName(),相似Android中的startActivity(),指定class全路径这种方式;
//先在MaterialApp里面注册Route
routes: { SecondRoute.routeName: (context) => SecondRoute(),}
Navigator.pushNamed(context, SecondRoute.routeName);
//返回上一个页面,相似Activity的finish();
Navigator.pop(context);
复制代码
基于上面的两种跳转方式,对应有两种
经过Navigator.push()跳转,将参数传到B页面的构造方法中,代码以下:
//A页面跳转,直接将参数传到B页面的构造方法里面
Navigator.push(context,
MaterialPageRoute(
builder:(context) => BRouter(string)
))
//BRouter构造方法
class BRouter extends StatelessWidget{
final String str;
BRouter(this.str);
}
复制代码
经过Navigator.pushNamed()
跳转,使用ModalRoute.of()
或者MaterialApp(CupertinoApp)
构造器中的onGenerateRouter()
获取参数,建议使用ModalRouter.of()
。代码以下:
//A页面跳转,arguments就是须要传递的数据,这里的arguments是一个可需参数
Navigator.pushName(context,routerName,arguments);
//B页面提取参数,传的是什么类型,就用什么类型接值,这里用String演示
//第一种用ModalRouter接值
String arg = ModalRouter.of(context).setting.arguments;
//第二种在onGenerateRouter里面接值
MaterialApp(
onGenerateRoute: (settings) {
// 先根据setting里面的name判断是哪一个Router
if (settings.name == PassArgumentsScreen.routeName) {
// 而后取出setting里面的arguments
final ScreenArguments args = settings.arguments;
// 而后再经过具体Router的构造方法穿过,相似上面的第一种方式接值方式
return MaterialPageRoute(
builder: (context) {
return PassArgumentsScreen(
title: args.title,
);
},
);
}
},
);
复制代码
从当前页面B返回上一个页面A回传数据:
通常都是点击B页面某个控件,关闭当前页面,把须要的数据回传,相似Android中的SetResult(Result.ok,intent)
//当前页面B中的按钮
RaisedButton(
onPressed: () {
// 点击button,关闭页面,回到上一个页面,回传数据
Navigator.pop(context, '回传的数据');
// 这个方法经过方法名也能看出来,关闭当前页面,跳转到具体的页面,也能够回传数据。
// tips:参数加[]说明是非必传参数
Navigator.popAndPushNamed(context, routeName,[T result])
},
child: Text('返回'),
);
//回到上一个页面A,须要接值的话,在点击去下一个页面的须要使用到async延迟接收
//当BuildContext在Scaffold以前时,调用Scaffold.of(context)会报错。因此这里经过Builder Widget来解决
Builder(builder: (context){
return RaisedButton(
onPressed: () async {
//2: 经过Navigator.push方式携带跳转
String str = "我是第一个页面的数据";
//疑问为何只能用var接值,不能用String?
var result = await Navigator.pushNamed(context, SecondRoute.routeName,
arguments: str);
if (result != null) {
//经过snackBar将接收到的数据show出来。
Scaffold.of(context).showSnackBar(SnackBar(
content: Text(result),
backgroundColor: Colors.blue,
duration: Duration(milliseconds: 500),
));
}
},
child: Text("携带数据跳转"),
);
}),
复制代码
下面咱们来看看最终的演示效果:
这样咱们就把Flutter当中最基础的页面跳转,以及页面之间数据交互讲解完了,小伙伴能够愉快的去作各类页面交互啦😊😊😊。