首發於個人公衆號前端
Flutter中消息傳遞java
路由是native中應用的比較多,特別是組件化的工程中,更是用來解耦的利器,比較經常使用的有阿里的ARouter等,路由這一思想也是借鑑前端而來,好比web中頁面跳轉就是一個url就到了一個新的頁面,Flutter既然是新一代的跨端方案,並且從RN借鑑了很多思想,路由固然也是必不可少的,本篇將瞭解下Flutter的路由git
同步更新gitpage xsfelvis.github.io/2018/12/15/…github
在Flutter中支持全部路由場景,push、pop頁面,頁面間的參數傳遞等等。flutter裏面的路由能夠分紅兩種,web
在建立時就已經明確知道了要跳轉的頁面和值,在新建一個MD風格的App的時候,能夠傳入一個routes參數來定義路由。可是這裏定義的路由是靜態的,它不能夠向下一個頁面傳遞參數ide
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
//註冊路由表
routes: {
"router/static_page": (context) => StaticRoute(),
},
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
複製代碼
經過routes這個屬性註冊好跳轉的頁面即key-value,上面的代碼中組件化
key:router/static_page value: StaticRouter 而後使用的時候使用學習
FlatButton(
child: Text("open static router"),
textColor: Colors.blue,
onPressed: () {
Navigator.pushNamed(context, "router/static_page");
},
)
複製代碼
當須要向下一個頁面傳遞參數時,要用到所謂的動態路由,本身生成頁面對象,因此能夠傳遞本身想要的參數。ui
FlatButton(
child: Text("open dynamic router"),
textColor: Colors.blue,
onPressed: () {
Navigator.push(context, MaterialPageRoute(
builder: (context) {
return new EchoRoute("傳入跳轉參數");
}));
或者
Navigator.of((context).push(MaterialPageRoute(
builder: (context) {
return new EchoRoute("傳入跳轉參數");
}));
},
)
複製代碼
new RaisedButton(
child: new Text("點我返回"),
onPressed: () {
Navigator.of(context).pop();
},
color: Colors.blue,
highlightColor: Colors.lightBlue,
)
複製代碼
咱們能夠在前一個頁面接受第二個頁面的返回值 在第一個頁面跳轉時候加上futrue來接收url
FlatButton(
child: Text("open dynamic router"),
textColor: Colors.blue,
onPressed: () {
Future future = Navigator.push(context,
MaterialPageRoute(builder: (context) {
return new EchoRoute("傳入跳轉參數");
}));
//接收動態頁面返回時傳回的值
future.then((value) {
showDialog(
context: context,
child: new AlertDialog(
title: new Text(value),
));
});
},
複製代碼
在EchoRoute頁面 返回時使用帶參數的pop方法
new RaisedButton(
child: new Text("點我返回"),
onPressed: () {
// Navigator.of(context).pop();
Navigator.of(context).pop("我是來自dymamic 關閉的返回值");
},
color: Colors.blue,
highlightColor: Colors.lightBlue,
)
複製代碼
這樣就會在關閉EchoRoute回到跳轉前頁面時彈出dialog收到EchoRoute傳來的參數
Navigator的職責是負責管理Route的,管理方式就是利用一個棧不停壓入彈出,固然也能夠直接替換其中某一個Route。而Route做爲一個管理單元,主要負責建立對應的界面,響應Navigator壓入路由和彈出路由
入棧:
出棧
歡迎關注個人公衆號,一塊兒學習,共同提升~
複製代碼