Именованные маршруты и аргументы
Используйте именованные маршруты для более удобной навигации и эффективно передавайте данные между экранами с помощью аргументов маршрутов.
«Именованные маршруты и аргументы» — бесплатный урок Flutter Mobile Development на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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
MaterialPageRouteinstance. - 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
routesproperty takes aMap. - 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
argumentsproperty accepts anyObject. - 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..settingsaccesses the route's settings..argumentsretrieves 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
routesinMaterialAppto define routes with unique string names. - Navigation: Use
Navigator.pushNamed(context, '/routeName')for cleaner navigation. - Passing Arguments: Use the
argumentsproperty inpushNamedto send data. - Receiving Arguments: Access data on the destination screen with
ModalRoute.of(context)!.settings.argumentsand cast it to the correct type.
This approach makes your app's navigation more organized and easier to maintain!
Часто задаваемые вопросы
Урок «Именованные маршруты и аргументы» бесплатный?
Да — полный текст урока «Именованные маршруты и аргументы» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Flutter Mobile Development, подпишись на CoddyKit PRO. Курс Flutter Mobile Development содержит 4 уроков всего.
Чему я научусь в уроке «Именованные маршруты и аргументы»?
Используйте именованные маршруты для более удобной навигации и эффективно передавайте данные между экранами с помощью аргументов маршрутов. Ты практикуешь Flutter Mobile Development с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Flutter Mobile Development?
Предыдущий опыт не требуется. Flutter Mobile Development на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Именованные маршруты и аргументы»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Flutter Mobile Development?
Да. Каждый урок Flutter Mobile Development включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Базовая навигация по страницам
- Именованные маршруты и аргументы
- TabBars и боковые меню
- Глубокие ссылки и навигация по URL