Flutter初步探索(六)使用命名路由导航

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)]

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,172评论 0 10
  • 单词总是背不下来怎么办……听力题原文全部能看懂,怎么就是听不懂……不会的单词查词典,竟然发现连音标都看不懂……老外...
    零珑心阅读 2,795评论 0 0
  • 后裔的位置比较好确认,就是1:1,因为头比较大,直接画个大概就可以了 草稿比想象中复杂一点(位置还是偏了) 依然是...
    沙曼德阅读 12,530评论 33 23
  • 用一句流行语形容我的四月值月生历程,就是“本以为是开始,可实际上是巅峰”。 三月底,三月值月生,也是和我同一批的组...
    终身学习站阅读 2,325评论 3 0
  • 我和他,在一起879天,异地恋879天。 上了大学之后,我在丹东,他在沈阳。每隔半个月,他都会坐一个小时的...
    爱蓝色的猪猪阅读 2,767评论 0 13

友情链接更多精彩内容