0Pricing
Flutter Mobile Development · 강의

이름이 지정된 경로 및 인수

더 깔끔하게 화면을 탐색할 수 있도록 이름이 지정된 경로를 사용하고, 경로 인수로 화면 간에 데이터를 효과적으로 전달합니다.

이름이 지정된 경로 및 인수은(는) CoddyKit의 무료 Flutter Mobile Development 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 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!

자주 묻는 질문

“이름이 지정된 경로 및 인수” 강의는 무료인가요?

네 — “이름이 지정된 경로 및 인수” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Flutter Mobile Development 강의 전체를 잠금 해제할 수 있습니다. Flutter Mobile Development 강의에는 총 4개의 강의가 포함되어 있습니다.

“이름이 지정된 경로 및 인수”에서 뭘 배우나요?

더 깔끔하게 화면을 탐색할 수 있도록 이름이 지정된 경로를 사용하고, 경로 인수로 화면 간에 데이터를 효과적으로 전달합니다. 브라우저에서 직접 실행하는 실습 코드로 Flutter Mobile Development을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Flutter Mobile Development을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Flutter Mobile Development은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“이름이 지정된 경로 및 인수” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Flutter Mobile Development 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Flutter Mobile Development 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 기본 페이지 탐색
  2. 이름이 지정된 경로 및 인수
  3. TabBars 및 서랍 메뉴
  4. 딥 링크와 URL 탐색
← Flutter Mobile Development(으)로 돌아가기