0Pricing
Flutter Mobile Development · 课时

命名路由与参数

使用命名路由简化导航,并有效地通过路由参数在屏幕之间传递数据。

命名路由与参数 是 CoddyKit 上的免费 Flutter Mobile Development 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Flutter Mobile Development 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Flutter Mobile Development 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Why Named Routes?

In previous lessons, we used MaterialPageRoute for navigation. While effective for simple apps, managing many routes this way can get messy.

  • Each route requires a new MaterialPageRoute instance.
  • Harder to identify screens by a unique name.
  • Can lead to repetitive code.

Named routes offer a cleaner, more structured way to manage your app's navigation.

Defining Named Routes

To use named routes, you define them in your MaterialApp widget. This is done using the routes property.

  • The routes property takes a Map.
  • The key is the route's name (a String, e.g., '/details').
  • The value is a function that builds the widget for that route.

The '/' route is special; it's your app's initial route.

Navigating to Named Routes

Once named routes are defined, you can navigate to them using Navigator.pushNamed(). This method takes the BuildContext and the name of the route.

It's simpler and more readable than creating a new MaterialPageRoute every time you want to go to a specific screen.

Basic Named Route Demo

Let's see how to set up and navigate using named routes. We'll create two simple screens: HomeScreen and DetailScreen.

Tap the 'Run' button to see it in action!

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Named Routes Demo',
      initialRoute: '/',
      routes: {
        '/': (context) => HomeScreen(),
        '/details': (context) => DetailScreen(),
      },
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Home Screen')),
      body: Center(
        child: ElevatedButton(
          child: Text('Go to Details'),
          onPressed: () {
            Navigator.pushNamed(context, '/details');
          },
        ),
      ),
    );
  }
}

class DetailScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Detail Screen')),
      body: Center(
        child: Text('You are on the Detail Screen!',
          style: TextStyle(fontSize: 20)),
      ),
    );
  }
}

Why Pass Arguments?

Often, when navigating to a new screen, you need to pass some data to it. For example:

  • A product ID to a product detail page.
  • User details to a profile editing screen.
  • A message to a confirmation page.

Route arguments allow you to send this information along with your navigation request.

Sending Arguments

You can pass arguments to a named route by using the arguments property in Navigator.pushNamed().

  • The arguments property accepts any Object.
  • It's best practice to pass simple data types (like String, int) or a custom class/map that encapsulates your data.

For example: Navigator.pushNamed(context, '/details', arguments: 'Hello from Home!');

Receiving Arguments

In the destination screen, you can retrieve the arguments using ModalRoute.of(context)!.settings.arguments.

  • ModalRoute.of(context) gets the current route.
  • .settings accesses the route's settings.
  • .arguments retrieves the data that was passed.

Remember to use ! for null safety if you're sure arguments will be present, or handle potential null values.

Type Safety & Casting

The .arguments property returns an Object?. This means you'll usually need to cast it to the expected type.

For example, if you passed a String, you'd retrieve it like this:

final String message = ModalRoute.of(context)!.settings.arguments as String;

It's good practice to add checks (e.g., if (arguments is String)) for robustness, especially with complex argument types.

Named Routes with Arguments Demo

This example demonstrates passing a simple String message from the HomeScreen to the DetailScreen using named routes and arguments.

The DetailScreen then displays this message.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Named Routes with Args',
      initialRoute: '/',
      routes: {
        '/': (context) => HomeScreen(),
        '/details': (context) => DetailScreen(),
      },
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Home Screen')),
      body: Center(
        child: ElevatedButton(
          child: Text('Go to Details with Message'),
          onPressed: () {
            Navigator.pushNamed(
              context,
              '/details',
              arguments: 'Hello from Home Screen!',
            );
          },
        ),
      ),
    );
  }
}

class DetailScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final String? message = 
        ModalRoute.of(context)!.settings.arguments as String?;

    return Scaffold(
      appBar: AppBar(title: Text('Detail Screen')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('You are on the Detail Screen!',
              style: TextStyle(fontSize: 20)),
            SizedBox(height: 20),
            Text('Message: ${message ?? "No message received"}',
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
          ],
        ),
      ),
    );
  }
}

Quick Check: Arguments

You've navigated to a named route called '/settings' and passed a boolean value true as an argument. How would you correctly retrieve and use this boolean in the SettingsScreen widget?

Recap: Named Routes & Arguments

Great job! You've learned how to streamline navigation and pass data efficiently.

  • Named Routes: Use routes in MaterialApp to define routes with unique string names.
  • Navigation: Use Navigator.pushNamed(context, '/routeName') for cleaner navigation.
  • Passing Arguments: Use the arguments property in pushNamed to send data.
  • Receiving Arguments: Access data on the destination screen with ModalRoute.of(context)!.settings.arguments and cast it to the correct type.

This approach makes your app's navigation more organized and easier to maintain!

常见问题解答

「命名路由与参数」课时是免费的吗?

是的 — 「命名路由与参数」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Flutter Mobile Development 课程的其余内容,请升级到 CoddyKit PRO。 Flutter Mobile Development 课程共包含 4 节课。

「命名路由与参数」这节课中我会学到什么?

使用命名路由简化导航,并有效地通过路由参数在屏幕之间传递数据。 你通过在浏览器中直接运行的动手代码来练习 Flutter Mobile Development,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Flutter Mobile Development 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Flutter Mobile Development 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「命名路由与参数」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Flutter Mobile Development 课中编写并运行代码吗?

能。每节 Flutter Mobile Development 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 基础页面导航
  2. 命名路由与参数
  3. TabBars 与抽屉菜单
  4. 深层链接与 URL 导航
← 返回 Flutter Mobile Development