Flutter之Route and Navigator

Route and Navigator

Basic usage

The basic use of the Navigator is to jump from one page to another and back to the first page with the back button on the second page.

Creating two pages

First, creating two pages, each containing a button. Clicking the button on the first page will navigate to the second page. Clicking the button on the second page will return to the first page.

The first page:

class FirstScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('First Screen'),
      ),
      body: new Center(
        child: new RaisedButton(
          child: new Text('Launch second screen'),
          onPressed: (){
          //Creating routes by MaterialPageRoute and using Navigator.push() to navigate to second page.
          Navigator.push(
                context,
                new MaterialPageRoute(builder: (context) => new SecondScreen()),
            );

          },
        ),
      ),
    );
  }
}

The second page:

class SecondScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Second Screen'),
      ),
      body: new Center(
        child: new RaisedButton(
          child: new Text('Go back!'),
          onPressed: (){
          //using Navigator.pop() to return last page.
          Navigator.pop(context);
          }),
        ),
      ),
    );
  }
}

MaterialPageRoute params introduction

MaterialPageRoute({
    WidgetBuilder builder,
    RouteSettings settings,
    bool maintainState = true,
    bool fullscreenDialog = false,
  })
  • builder: which is a callback funciton of WidgetBuilder and to build the contents of the route. the return value is a widget. We typically implement the callback to return an instance of the new route.
  • settings: Containing the configuration for the route, such as the route name, whether or not it is the original route (home page).
  • maintainState: By default, when a new route is pushed, the original route is still held in memory, and maintainState can be set to false if you want to free all the resources the route occupies when it is not used.
  • fullscreenDialog: whether the new routing page is a full-screen modal dialog. For iOS, if the fullscreenDialog is true, the new page will slide in from the bottom of the screen (not horizontally).

Using named navigator routes

Mobile apps often manage a large number of routes and it's often easiest to refer to them by name. Route names, by convention, use a path-like structure (for example, '/a/b/c'). The app's home page route is named '/' by default.

The MaterialApp can be created with a Map<String, WidgetBuilder> which maps from a route's name to a builder function that will create it. The MaterialApp uses this map to create a value for its navigator's onGenerateRoute callback.

Registered routing table

void main() {
  runApp(MaterialApp(
    home: MyAppHome(), // becomes the route named '/'
    routes: <String, WidgetBuilder> {
      '/a': (BuildContext context) => MyPage(title: 'page A'),
      '/b': (BuildContext context) => MyPage(title: 'page B'),
      '/c': (BuildContext context) => MyPage(title: 'page C'),
    },
  ));
}

Opening a new routing page with the routing name

Navigator.pushNamed(context, '/b');

or

Navigator.of(context).pushNamed('/b');

Note:In addition to the pushNamed method, the Navigator also has other methods for managing named routing, such as pushReplacementNamed, so you can view the API documentation.

Routes can return a value

When a route is pushed to ask the user for a value, the value can be returned via the pop method's result parameter.

Methods that push a route return a Future. The Future resolves when the route is popped and the Future's value is the pop method's result parameter.

For example if we wanted to ask the user to press 'OK' to confirm an operation we could await the result of Navigator.push:

For example:

 void skipToSelectPage() async{
 //deliver arguments when jump to selectPage.
  final result = await Navigator.pushNamed(context, SelecPage.routeName,
          arguments: argumnets);
 }
GestureDetector(
    onTap: () {
    //return to last page with selectedDataList
    Navigator.pop(context, selectedDataList);
            },
    )

Custom routes

You can create your own subclass of one of the widget library route classes like PopupRoute, ModalRoute, or PageRoute, to control the animated transition employed to show the route, the color and behavior of the route's modal barrier, and other aspects of the route.

The PageRouteBuilder class makes it possible to define a custom route in terms of callbacks. Here's an example that rotates and fades its child when the route appears or disappears. This route does not obscure the entire screen because it specifies opaque: false, just as a popup route does.

Navigator.push(
  context,
  PageRouteBuilder(
    transitionDuration: Duration(milliseconds: 500), //Animation time is 500 milliseconds.
    pageBuilder: (BuildContext context, Animation animation,
        Animation secondaryAnimation) {
      return new FadeTransition(
        //Using the fade in transition.
        opacity: animation,
        child: PageB(),
      );
    },
  ),
);

Nesting Navigators

An app can use more than one Navigator. Nesting one Navigator below another Navigator can be used to create an "inner journey" such as tabbed navigation, user registration, store checkout, or other independent journeys that represent a subsection of your overall application.

for example:

Create a page with two bottomNavigationBar.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/testroute/page_main_navigator.dart';
import 'package:flutter_app/testroute/page_profile.dart';

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new _HomeState();
  }
}

class _HomeState extends State<HomePage> {
  int _currentIndex = 0;
  final List<Widget> _children = [
    new MainNavigatorPage(),
    new ProfilePage(),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: _children[_currentIndex],
      bottomNavigationBar: new BottomNavigationBar(
        onTap: onTabTapped,
        currentIndex: _currentIndex,
        items: [
          new BottomNavigationBarItem(
            icon: new Icon(Icons.home),
            title: new Text('Main'),
          ),
          new BottomNavigationBarItem(
            icon: new Icon(Icons.person),
            title: new Text('Profile'),
          ),
        ],
      ),
    );
  }

  void onTabTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }
}

First page of HomePage and define two routing pages.

class MainNavigatorPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Navigator(
      initialRoute: 'main',
      onGenerateRoute: (RouteSettings settings) {
        WidgetBuilder builder;
        switch (settings.name) {
          case 'main':
            builder = (BuildContext context) => new MainPage();
            break;
          case 'demo':
            builder = (BuildContext context) => new DemoPage();
            break;
          default:
            throw new Exception('Invalid route: ${settings.name}');
        }

        return new MaterialPageRoute(builder: builder, settings: settings);
      },
    );
  }
}
import 'package:flutter/material.dart';

class MainPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Home'),
      ),
      body: new Center(
        child: new RaisedButton(
          child: new Text('demo'),
          onPressed: () {
            Navigator.of(context).pushNamed('demo');
          },
        ),
      ),
    );
  }
}

Routing stack management in Flutter

push()

Insert an element directly into the top of the stack.

Navigator.of(context).pushNamed("/111");
Navigator.of(context).push(route);

pop()

Delete the top element of the stack and returns to the previous page.

Navigator.of(context).pop();

pushReplacementNamed()和popAndPushNamed()

There is a scenario, after jumping to Screen3, we want to jump to Screen4, but we don't want to go back to Screen3 by clicking the back button. That is, while inserting Screen4 into the top of the stack, remove Screen3.

Navigator.of(context).pushReplacementNamed('/screen4');
Navigator.popAndPushNamed(context, '/screen4');
Navigator.of(context).pushReplacement(newRoute);

pushNamedAndRemoveUntil()

Push the route with the given name onto the navigator that most tightly encloses the given context, and then remove all the previous routes until the predicate returns true.

Pop up Screen3 and Screen2, and then push the new Screen4.
Navigator.of(context).pushNamedAndRemoveUntil('/screen4', ModalRoute.withName('/screen1'));

Be sure to delete all routes before pushing new route.
Navigator.of(context).pushNamedAndRemoveUntil('/LoginScreen', (Route<dynamic> route) => false);

popUntil()

popUntil(RoutePredicate predicate);
Navigator.of(context).popUntil(ModalRoute.withName("/XXX"));
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,470评论 6 501
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,393评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,577评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,176评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,189评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,155评论 1 299
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,041评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,903评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,319评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,539评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,703评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,417评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,013评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,664评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,818评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,711评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,601评论 2 353

推荐阅读更多精彩内容