Flutter中的路由

首發於個人公衆號前端

Flutter中消息傳遞java

前言

路由是native中應用的比較多,特別是組件化的工程中,更是用來解耦的利器,比較經常使用的有阿里的ARouter等,路由這一思想也是借鑑前端而來,好比web中頁面跳轉就是一個url就到了一個新的頁面,Flutter既然是新一代的跨端方案,並且從RN借鑑了很多思想,路由固然也是必不可少的,本篇將瞭解下Flutter的路由git

同步更新gitpage xsfelvis.github.io/2018/12/15/…github

Flutter的路由

在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壓入路由和彈出路由

入棧:

  • 使用Navigator.of(context).pushName(「path「)或者Navigator.pushName(context,「path「)能夠進行靜態路由的跳轉前提是須要在route屬性裏面註冊
  • 使用push(Route)能夠進行態路由的跳轉,動態路由能夠傳入未知數據

出棧

  • 使用pop()能夠進行路由的出棧而且能夠傳遞參數
  • 可使用Future接收上個頁面返回的值。

代碼在 github.com/xsfelvis/le…

歡迎關注個人公衆號,一塊兒學習,共同提升~
複製代碼

公衆號小.jpg
相關文章
相關標籤/搜索