Flutter学习笔记 -- 路由管理
简介
Flutter的路由是用于管理一组居右某种进出规制的界面组件,以便实现各个界面之间有规律的跳转,而遵循这一规制并存放路由信息的事物称为路由栈。
熟悉Android开发的都知道Intent,Android中的界面跳转可以通过Intent来实现,在项目中我们通过Intent可以轻松实现自己路由管理。而在Flutter中,这个路由就是Navigator,跳转到某个界面可以用Navigator.push()
、返回上一个界面可以用Navigator.pop()
。
一、静态路由
静态路由就是在明确知道跳转哪个界面时使用的。routes
就是定义路由表的属性,eg:
class MyApp extends StatelessWidget {@overrideWidget build(BuildContext context) {return MaterialApp(title: 'Flutter Demo',theme: ThemeData(primarySwatch: Colors.blue),home: const MyHomePage(title: '静态路由',),routes: <String, WidgetBuilder>{'/page1': (BuildContext context) => FirstPage(),'/page2': (BuildContext context) => SecondPage()},onUnknownRoute: (RouteSettings settings) {return new MaterialPageRoute(builder: (context) {return new ErrorPage();});},);}
}
routes属性定义的是路由表信息,相当于注册,在实际项目中为了保证健硕性,需要使用onUnknowRoute
属性定义路由跳转出错界面。
注册完需要跳转的界面后,如何跳转呢,代码如下:
@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text(widget.title),),body: Center(child: OutlinedButton(child: const Text('跳转到page1'),onPressed: () {Navigator.pushNamed(context, '/page1');},),),);}
直接调用Navigator.pushNamed()
方法就可以实现界面跳转了,其中第二个参数就是routes路由表中定义的键值对中的key。而Navigator.push()
的方式跳转是不需要定义路由表信息的:
Navigator.push(context, new MaterialPageRoute(builder: (context) {return FirstPage();
});
跳转一个界面调用Navigator.push()
,那么退出一个界面返回上一个界面,调用Navigator.pop()
即可。在Flutter中,路由管理是栈形式的,遵循“先进后出”的顺序,所有会自己找到栈中上一个界面返回。
二、动态路由
既然有静态路由,那么也有动态路由。动态路由主要用于两个界面的参数传递。
Navigator.push(context, new MaterialPageRoute(builder: (context) {return new FirstPage(title: '需要传递的参数');
}));
添加跳转动画:
Navigator.push(context, PageRouteBuilder(transitionDuration: Duration(milliseconds: 500), pageBuilder: (BuildContext context, Animation animation,Animation secondaryAnimation) {return new FadeTransition(opacity: animation,child: FirstPage() );}));
}),