0Pricing
Flutter Mobile Development · Lección

Rutas con nombre y argumentos

Utilice rutas con nombre para lograr una navegación más clara y transfiera datos entre pantallas mediante argumentos de ruta de forma eficaz.

Rutas con nombre y argumentos es una lección gratuita de Flutter Mobile Development en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Flutter Mobile Development, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Flutter Mobile Development incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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!

Preguntas frecuentes

¿La lección «Rutas con nombre y argumentos» es gratis?

Sí — el texto completo de «Rutas con nombre y argumentos» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Flutter Mobile Development, actualiza a CoddyKit PRO. El curso de Flutter Mobile Development incluye 4 lecciones en total.

¿Qué aprenderé en «Rutas con nombre y argumentos»?

Utilice rutas con nombre para lograr una navegación más clara y transfiera datos entre pantallas mediante argumentos de ruta de forma eficaz. Practicas Flutter Mobile Development con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Flutter Mobile Development?

No se requiere experiencia previa. Flutter Mobile Development en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.

¿Cuánto tiempo toma la lección «Rutas con nombre y argumentos»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Flutter Mobile Development?

Sí. Cada lección de Flutter Mobile Development incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Navegación básica entre páginas
  2. Rutas con nombre y argumentos
  3. TabBars y Drawers
  4. Deep linking y navegación mediante URL
← Volver a Flutter Mobile Development