作Android/iOS原生開發的時候,要打開一個新的頁面,你得知道你的目標頁面對象,而後初始化一個Intent或者ViewController,再經過startActivity
或者pushViewController
來推出一個新的頁面,不能跟web同樣,直接丟一個連接地址就跳轉到新的頁面。固然,能夠本身去加一箇中間層來實現這些功能。
Flutter裏面是原生支持路由的。Flutter的framework提供了路由跳轉的實現。咱們能夠直接使用這些功能。python
Flutter裏面有路由支持全部的路由場景,push、pop頁面,頁面間的參數傳遞等等。flutter裏面的路由能夠分紅兩種,一種是直接註冊,不能傳遞參數。另外一種要本身構造實例,能夠傳遞參數。咱們暫時把它們規爲靜態路由和動態路由。web
在新建一個MD風格的App的時候,能夠傳入一個routes參數來定義路由。可是這裏定義的路由是靜態的,它不能夠向下一個頁面傳遞參數。ide
return new MaterialApp( title: 'Flutter Demo', theme: new ThemeData( primarySwatch: Colors.blue, ), home: new MyHomePage(title: 'Flutter實例'), routes: <String, WidgetBuilder> { // 這裏能夠定義靜態路由,不能傳遞參數 '/router/second': (_) => new SecondPage(), '/router/home': (_) => new RouterHomePage(), }, );
push一個新頁面,pushNamed方法是有一個Future的返回值的,因此靜態路由也是能夠接收下一個頁面的返回值的。可是不能向下一個頁面傳遞參數。動畫
Navigator.of(context).pushNamed('/router/second'); // 帶返回值 Navigator.of(context).pushNamed('/router/second').then((value) { // dialog顯示返回值 _showDialog(context, value); })
pop回上一個頁面ui
Navigator.of(context).pop('這個是要返回給上一個頁面的數據');
當須要向下一個頁面傳遞參數時,要用到所謂的動態路由,本身生成頁面對象,因此能夠傳遞本身想要的參數。spa
Navigator.of(context).push(new MaterialPageRoute(builder: (_) { return new SecondPage(title: '路由是個好東西,要進一步封裝'); }));
也能夠用PageRouterBuilder來自定義打開動畫code
Navigator.of(context).push(new PageRouteBuilder(pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) { return new RefreshIndicatorDemo(); }, transitionsBuilder: ( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child, ) { // 添加一個平移動畫 return BRouter.createTransition(animation, child); }));
平移的變換router
/// 建立一個平移變換 /// 跳轉過去查看源代碼,能夠看到有各類各樣定義好的變換 static SlideTransition createTransition( Animation<double> animation, Widget child) { return new SlideTransition( position: new Tween<Offset>( begin: const Offset(1.0, 0.0), end: const Offset(0.0, 0.0), ).animate(animation), child: child, // child is the value returned by pageBuilder ); }