Flutter是借鑑React的開發思想實現的,在子組件的插槽上,React有this.props.children
,Vue有<slot></slot>
。git
固然Flutter也有相似的Widget,那就是Navigator
,不過是以router的形式實現(像<router-view></router-view>
???)。github
Navigator的使用無非3個屬性bash
initialRoute
: 初始路由onGenerateRoute
: 匹配路由onUnknownRoute
: 404在實現層面app
首先:Navigator的高度爲infinity。若是直接父級非最上級也是infinity會產生異常,例如,Scaffold -> Column -> Navigator。因此:Navigator須要附件限制高度,例如:Scaffold -> Column -> Container(height: 300) -> Navigatoride
而後:在onGenerateRoute屬性中,使用第一個BuildContext參數,可以在MaterialApp未設置route的狀況下使用Navigator.pushNamed(nContext, '/efg');
跳到對應的子路由中。ui
最後:Navigator執行尋找路由順序是 initialRoute -> onGenerateRoute -> onUnknownRoute,這個和React的Route是相似的。this
最後附上源碼spa
import 'package:flutter/material.dart';
class NavigatorPage extends StatefulWidget {
@override
_NavigatorPageState createState() => _NavigatorPageState();
}
class _NavigatorPageState extends State<NavigatorPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Navigator'),
),
body: Column(
children: <Widget>[
Text('Navigator的高度爲infinity'),
Text('若是直接父級非最上級也是infinity會產生異常'),
Container(
height: 333,
color: Colors.amber.withAlpha(111),
child: Navigator( // Navigator
initialRoute: '/abc',
onGenerateRoute: (val) {
RoutePageBuilder builder;
switch (val.name) {
case '/abc':
builder = (BuildContext nContext, Animation<double> animation, Animation<double> secondaryAnimation) => Column(
// 並無在 MaterialApp 中設定 /efg 路由
// 由於Navigator的特性 使用nContext 能夠跳轉 /efg
children: <Widget>[
Text('呵呵呵'),
RaisedButton(
child: Text('去 /efg'),
onPressed: () {
Navigator.pushNamed(nContext, '/efg');
},
)
],
);
break;
case '/efg':
builder = (BuildContext nContext, Animation<double> animation, Animation<double> secondaryAnimation) => Row(
children: <Widget>[
RaisedButton(
child: Text('去 /hhh'),
onPressed: () {
Navigator.pushNamed(nContext, '/hhh');
},
)
],
);
break;
default:
builder = (BuildContext nContext, Animation<double> animation, Animation<double> secondaryAnimation) => Center(
child: RaisedButton(
child: Text('去 /abc'),
onPressed: () {
Navigator.pushNamed(nContext, '/abc');
},
)
);
}
return PageRouteBuilder(
pageBuilder: builder,
// transitionDuration: const Duration(milliseconds: 0),
);
},
onUnknownRoute: (val) {
print(val);
},
observers: <NavigatorObserver>[]
),
),
Text('Navigator執行尋找路由順序'),
Text('initialRoute'),
Text('onGenerateRoute'),
Text('onUnknownRoute'),
],
),
);
}
}
複製代碼
擼完代碼記得給顆星哦。code