Flutter初步探索(六)使用命名路由導(dǎo)航

In the Navigate to a new screen and back recipe, we learned how to Navigate to a new screen by creating a new route and pushing it to the Navigator.

However, if we need to navigate to the same screen in many parts of our apps, this can result in code duplication. In these cases, it can be handy to define a “named route,” and use the named route for Navigation.

To work with named routes, we can use the Navigator.pushNamed function. This example will replicate the functionality from the original recipe, demonstrating how to use named routes instead.

Directions

  1. Create two screens
  2. Define the routes
  3. Navigate to the second screen using Navigator.pushNamed
  4. Return to the first screen using Navigator.pop

1. Create two screens

First, we’ll need two screens to work with. The first screen will contain a button that navigates to the second screen. The second screen will contain a button that navigates back to the first.

class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Screen'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Launch screen'),
          onPressed: () {
            // Navigate to second screen when tapped!
          },
        ),
      ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Second Screen"),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            // Navigate back to first screen when tapped!
          },
          child: Text('Go back!'),
        ),
      ),
    );
  }
}

2. Define the routes

Next, we’ll need to define our routes by providing additional properties to the MaterialApp constructor: the initialRoute and the routes themselves.

The initialRoute property defines which route our app should start with. The routes property defines the available named routes and the Widgets that should be built when we navigate to those routes.

MaterialApp(
  // Start the app with the "/" named route. In our case, the app will start
  // on the FirstScreen Widget
  initialRoute: '/',
  routes: {
    // When we navigate to the "/" route, build the FirstScreen Widget
    '/': (context) => FirstScreen(),
    // When we navigate to the "/second" route, build the SecondScreen Widget
    '/second': (context) => SecondScreen(),
  },
);

Note: When using initialRoute, be sure you do not define a home property.

3. Navigate to the second screen

With our Widgets and routes in place, we can begin navigating! In this case, we’ll use theNavigator.pushNamed function. This tells Flutter to build the Widget defined in our routes table and launch the screen.

In the build method of our FirstScreen Widget, we’ll update the onPressed callback:

// Within the `FirstScreen` Widget
onPressed: () {
  // Navigate to the second screen using a named route
  Navigator.pushNamed(context, '/second');
}

4. Return to the first screen

In order to navigate back to the first page, we can use the Navigator.pop function.

// Within the SecondScreen Widget
onPressed: () {
  // Navigate back to the first screen by popping the current route
  // off the stack
  Navigator.pop(context);
}

Complete example

import 'package:flutter/material.dart';

void main() {
  runApp(MaterialApp(
    title: 'Named Routes Demo',
    // Start the app with the "/" named route. In our case, the app will start
    // on the FirstScreen Widget
    initialRoute: '/',
    routes: {
      // When we navigate to the "/" route, build the FirstScreen Widget
      '/': (context) => FirstScreen(),
      // When we navigate to the "/second" route, build the SecondScreen Widget
      '/second': (context) => SecondScreen(),
    },
  ));
}

class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('First Screen'),
      ),
      body: Center(
        child: RaisedButton(
          child: Text('Launch screen'),
          onPressed: () {
            // Navigate to the second screen using a named route
            Navigator.pushNamed(context, '/second');
          },
        ),
      ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Second Screen"),
      ),
      body: Center(
        child: RaisedButton(
          onPressed: () {
            // Navigate back to the first screen by popping the current route
            // off the stack
            Navigator.pop(context);
          },
          child: Text('Go back!'),
        ),
      ),
    );
  }
}

[圖片上傳中...(image-694d6f-1546008951542-0)]

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末瞻惋,一起剝皮案震驚了整個濱河市灸眼,隨后出現(xiàn)的幾起案子喻奥,更是在濱河造成了極大的恐慌朱庆,老刑警劉巖塌鸯,帶你破解...
    沈念sama閱讀 211,042評論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡注整,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,996評論 2 384
  • 文/潘曉璐 我一進(jìn)店門度硝,熙熙樓的掌柜王于貴愁眉苦臉地迎上來肿轨,“玉大人,你說我怎么就攤上這事蕊程〗放郏” “怎么了?”我有些...
    開封第一講書人閱讀 156,674評論 0 345
  • 文/不壞的土叔 我叫張陵藻茂,是天一觀的道長驹暑。 經(jīng)常有香客問我,道長辨赐,這世上最難降的妖魔是什么岗钩? 我笑而不...
    開封第一講書人閱讀 56,340評論 1 283
  • 正文 為了忘掉前任,我火速辦了婚禮肖油,結(jié)果婚禮上兼吓,老公的妹妹穿的比我還像新娘。我一直安慰自己森枪,他們只是感情好视搏,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,404評論 5 384
  • 文/花漫 我一把揭開白布审孽。 她就那樣靜靜地躺著,像睡著了一般浑娜。 火紅的嫁衣襯著肌膚如雪佑力。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,749評論 1 289
  • 那天筋遭,我揣著相機(jī)與錄音打颤,去河邊找鬼。 笑死漓滔,一個胖子當(dāng)著我的面吹牛编饺,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播响驴,決...
    沈念sama閱讀 38,902評論 3 405
  • 文/蒼蘭香墨 我猛地睜開眼透且,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了豁鲤?” 一聲冷哼從身側(cè)響起秽誊,我...
    開封第一講書人閱讀 37,662評論 0 266
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎琳骡,沒想到半個月后锅论,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,110評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡楣号,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,451評論 2 325
  • 正文 我和宋清朗相戀三年棍厌,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片竖席。...
    茶點(diǎn)故事閱讀 38,577評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖敬肚,靈堂內(nèi)的尸體忽然破棺而出毕荐,到底是詐尸還是另有隱情,我是刑警寧澤艳馒,帶...
    沈念sama閱讀 34,258評論 4 328
  • 正文 年R本政府宣布憎亚,位于F島的核電站,受9級特大地震影響弄慰,放射性物質(zhì)發(fā)生泄漏第美。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,848評論 3 312
  • 文/蒙蒙 一陆爽、第九天 我趴在偏房一處隱蔽的房頂上張望什往。 院中可真熱鬧,春花似錦慌闭、人聲如沸别威。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,726評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽省古。三九已至粥庄,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間豺妓,已是汗流浹背惜互。 一陣腳步聲響...
    開封第一講書人閱讀 31,952評論 1 264
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留琳拭,地道東北人训堆。 一個月前我還...
    沈念sama閱讀 46,271評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像臀栈,于是被迫代替她去往敵國和親蔫慧。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,452評論 2 348

推薦閱讀更多精彩內(nèi)容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,306評論 0 10
  • 單詞總是背不下來怎么辦……聽力題原文全部能看懂黍析,怎么就是聽不懂……不會的單詞查詞典,竟然發(fā)現(xiàn)連音標(biāo)都看不懂……老外...
    零瓏心閱讀 332評論 0 0
  • 后裔的位置比較好確認(rèn)屎开,就是1:1阐枣,因為頭比較大,直接畫個大概就可以了 草稿比想象中復(fù)雜一點(diǎn)(位置還是偏了) 依然是...
    沙曼德閱讀 7,638評論 33 23
  • 用一句流行語形容我的四月值月生歷程奄抽,就是“本以為是開始蔼两,可實際上是巔峰”。 三月底逞度,三月值月生额划,也是和我同一批的組...
    終身學(xué)習(xí)站閱讀 265評論 3 0
  • 我和他俊戳,在一起879天,異地戀879天馆匿。 上了大學(xué)之后抑胎,我在丹東,他在沈陽渐北。每隔半個月阿逃,他都會坐一個小時的...
    愛藍(lán)色的豬豬閱讀 332評論 0 13