Navigate to a new screen and back 教學中, 你已學會如何透過建立新的 Route 並將其推送到 Navigator 來導覽至新螢幕。

然而,如果你需要在應用程式的多個地方導覽至相同的螢幕,這種做法可能會導致程式碼重複。 解決方法是定義一個 命名路由(named route), 並在導覽時使用該命名路由。

要使用命名路由, 請使用 Navigator.pushNamed() 函式。 本範例重現原始教學的功能, 並透過以下步驟展示如何使用命名路由:

  1. 建立兩個螢幕。
  2. 定義路由。
  3. 使用 Navigator.pushNamed() 導覽至第二個螢幕。
  4. 使用 Navigator.pop() 返回第一個螢幕。

1. 建立兩個螢幕

#

首先,建立兩個要操作的螢幕。第一個螢幕包含一個 按鈕,可導覽至第二個螢幕。第二個螢幕則包含一個 按鈕,可返回第一個螢幕。

dart
import 'package:flutter/material.dart';

class FirstScreen extends StatelessWidget {
  const FirstScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('First Screen')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // Navigate to the second screen when tapped.
          },
          child: const Text('Launch screen'),
        ),
      ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  const SecondScreen({super.key});

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

2. 定義路由

#

接下來,透過在 MaterialApp 建構函式中提供額外的屬性,來定義路由:initialRoute 以及 routes 本身。

initialRoute 屬性用來定義應用程式啟動時應該從哪個路由開始。 routes 屬性則定義了可用的命名路由(named routes)以及在導向這些路由時要建立的元件(Widgets)。

dart
MaterialApp(
  title: 'Named Routes Demo',
  // Start the app with the "/" named route. In this case, the app starts
  // on the FirstScreen widget.
  initialRoute: '/',
  routes: {
    // When navigating to the "/" route, build the FirstScreen widget.
    '/': (context) => const FirstScreen(),
    // When navigating to the "/second" route, build the SecondScreen widget.
    '/second': (context) => const SecondScreen(),
  },
)

3. 導航到第二個螢幕

#

當元件(Widgets)與命名路由(routes)都已設定好後,可以透過 Navigator.pushNamed() 方法來觸發導航。 這會告訴 Flutter 去建立在 routes 表格中定義的元件,並顯示該螢幕。

FirstScreen 元件的 build() 方法中,更新 onPressed() 回呼函式(callback):

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

4. 返回第一個螢幕

#

若要導覽回到第一個螢幕,請使用 Navigator.pop() 函式。

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

互動範例

#
import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      title: 'Named Routes Demo',
      // Start the app with the "/" named route. In this case, the app starts
      // on the FirstScreen widget.
      initialRoute: '/',
      routes: {
        // When navigating to the "/" route, build the FirstScreen widget.
        '/': (context) => const FirstScreen(),
        // When navigating to the "/second" route, build the SecondScreen widget.
        '/second': (context) => const SecondScreen(),
      },
    ),
  );
}

class FirstScreen extends StatelessWidget {
  const FirstScreen({super.key});

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

class SecondScreen extends StatelessWidget {
  const SecondScreen({super.key});

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