Bird
Raised Fist0
Fluttermobile~20 mins

Named routes in Flutter - Mini App: Build & Ship

Choose your learning style10 modes available
Build: Named Routes Demo
A simple Flutter app demonstrating navigation using named routes between two screens.
Target UI
Home Screen
+---------------------+
|                     |
|   Welcome Home!      |
|                     |
| [Go to Details]      |
+---------------------+

Details Screen
+---------------------+
|                     |
|   Details Page       |
|                     |
| [Back to Home]       |
+---------------------+
Use named routes for navigation.
Create two screens: HomeScreen and DetailsScreen.
HomeScreen has a button labeled 'Go to Details' that navigates to DetailsScreen.
DetailsScreen has a button labeled 'Back to Home' that navigates back to HomeScreen.
Define routes in MaterialApp's routes property.
Starter Code
Flutter
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Named Routes Demo',
      // TODO: Define routes here
      home: const HomeScreen(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Home Screen')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // TODO: Navigate to DetailsScreen using named route
          },
          child: const Text('Go to Details'),
        ),
      ),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Details Screen')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            // TODO: Navigate back to HomeScreen using named route
          },
          child: const Text('Back to Home'),
        ),
      ),
    );
  }
}
Task 1
Task 2
Task 3
Task 4
Solution
Flutter
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Named Routes Demo',
      initialRoute: '/home',
      routes: {
        '/home': (context) => const HomeScreen(),
        '/details': (context) => const DetailsScreen(),
      },
    );
  }
}

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

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

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Details Screen')),
      body: Center(
        child: ElevatedButton(
          onPressed: () {
            Navigator.pushNamed(context, '/home');
          },
          child: const Text('Back to Home'),
        ),
      ),
    );
  }
}

This Flutter app uses named routes to navigate between two screens: HomeScreen and DetailsScreen.

In MaterialApp, we define the routes map with keys '/home' and '/details' pointing to their respective screen widgets.

The initialRoute is set to '/home' so the app starts on the HomeScreen.

On HomeScreen, pressing the button calls Navigator.pushNamed(context, '/details') to go to DetailsScreen.

On DetailsScreen, pressing the button calls Navigator.pushNamed(context, '/home') to go back to HomeScreen.

This approach keeps navigation organized and easy to manage, especially as apps grow larger.

Final Result
Completed Screen
Home Screen
+---------------------+
|                     |
|   Welcome Home!      |
|                     |
| [Go to Details]      |
+---------------------+

Details Screen
+---------------------+
|                     |
|   Details Page       |
|                     |
| [Back to Home]       |
+---------------------+
Tap 'Go to Details' button on Home Screen navigates to Details Screen.
Tap 'Back to Home' button on Details Screen navigates back to Home Screen.
Stretch Goal
Add a third screen named 'AboutScreen' accessible from HomeScreen using a named route '/about'.
💡 Hint
Define '/about' in routes and add a button on HomeScreen that calls Navigator.pushNamed(context, '/about').

Practice

(1/5)
1. What is the main purpose of using named routes in a Flutter app?
easy
A. To handle user input events
B. To style the app's theme
C. To manage app state globally
D. To give each screen a simple name for easy navigation

Solution

  1. Step 1: Understand named routes concept

    Named routes assign simple string names to screens for easier navigation instead of using widget instances directly.
  2. Step 2: Identify the main purpose

    This helps developers navigate between screens by referring to route names, making code cleaner and navigation simpler.
  3. Final Answer:

    To give each screen a simple name for easy navigation -> Option D
  4. Quick Check:

    Named routes = simple screen names for navigation [OK]
Hint: Named routes are simple screen names for navigation [OK]
Common Mistakes:
  • Confusing named routes with app theming
  • Thinking named routes manage app state
  • Mixing named routes with event handling
2. Which of the following is the correct way to define named routes in a Flutter MaterialApp?
easy
A. MaterialApp(routeNames: {'/home': HomeScreen()})
B. MaterialApp(routes: {'/home': (context) => HomeScreen()})
C. MaterialApp(navigation: {'/home': HomeScreen()})
D. MaterialApp(namedRoutes: {'/home': () => HomeScreen()})

Solution

  1. Step 1: Recall MaterialApp named routes syntax

    Named routes are defined using the 'routes' property with a map of route names to builder functions.
  2. Step 2: Check each option

    MaterialApp(routes: {'/home': (context) => HomeScreen()}) correctly uses 'routes' with a map where the value is a function returning the widget. Other options use incorrect property names or values.
  3. Final Answer:

    MaterialApp(routes: {'/home': (context) => HomeScreen()}) -> Option B
  4. Quick Check:

    Use 'routes' with map of name to builder function [OK]
Hint: Use 'routes' property with map of names to builder functions [OK]
Common Mistakes:
  • Using wrong property names like routeNames or navigation
  • Assigning widget instance instead of builder function
  • Missing context parameter in builder function
3. Given the following code snippet, what screen will be shown when Navigator.pushNamed(context, '/profile') is called?
MaterialApp(
  routes: {
    '/': (context) => HomeScreen(),
    '/profile': (context) => ProfileScreen(),
    '/settings': (context) => SettingsScreen(),
  },
)
medium
A. ProfileScreen
B. Error: Route not found
C. SettingsScreen
D. HomeScreen

Solution

  1. Step 1: Check the routes map for '/profile'

    The routes map defines '/profile' as a key with ProfileScreen() as its widget builder.
  2. Step 2: Understand Navigator.pushNamed behavior

    Calling Navigator.pushNamed with '/profile' will navigate to the ProfileScreen widget.
  3. Final Answer:

    ProfileScreen -> Option A
  4. Quick Check:

    Navigator.pushNamed('/profile') shows ProfileScreen [OK]
Hint: Match route name to widget in routes map [OK]
Common Mistakes:
  • Confusing route names or mistyping them
  • Assuming default screen shows instead of named route
  • Expecting error when route exists
4. What is wrong with this code snippet for navigating to a named route?
Navigator.pushNamed('/settings');
medium
A. Navigator.pushNamed does not exist
B. Route name is incorrect
C. Missing BuildContext parameter
D. Should use Navigator.pop instead

Solution

  1. Step 1: Check Navigator.pushNamed method signature

    Navigator.pushNamed requires a BuildContext as the first argument, then the route name as a string.
  2. Step 2: Identify the error in the code

    The code calls Navigator.pushNamed with only the route name string, missing the required context parameter.
  3. Final Answer:

    Missing BuildContext parameter -> Option C
  4. Quick Check:

    Navigator.pushNamed needs context first [OK]
Hint: Navigator.pushNamed requires context and route name [OK]
Common Mistakes:
  • Omitting the BuildContext argument
  • Passing route name as first argument without context
  • Confusing pushNamed with pop
5. You want to navigate from HomeScreen to DetailsScreen using named routes and pass an ID parameter. Which approach correctly passes the argument using Navigator.pushNamed?
hard
A. Navigator.pushNamed(context, '/details', arguments: 42);
B. Navigator.pushNamed(context, '/details/42');
C. Navigator.pushNamed('/details', arguments: 42);
D. Navigator.pushNamed(context, '/details', params: 42);

Solution

  1. Step 1: Recall how to pass arguments with named routes

    Navigator.pushNamed accepts an optional 'arguments' parameter to pass data to the new screen.
  2. Step 2: Analyze each option

    Navigator.pushNamed(context, '/details', arguments: 42); correctly passes context, route name, and arguments. Navigator.pushNamed(context, '/details/42'); tries to encode ID in route string (not standard). Navigator.pushNamed('/details', arguments: 42); misses context. Navigator.pushNamed(context, '/details', params: 42); uses wrong parameter name 'params'.
  3. Final Answer:

    Navigator.pushNamed(context, '/details', arguments: 42); -> Option A
  4. Quick Check:

    Use 'arguments' parameter to pass data [OK]
Hint: Pass data with 'arguments' parameter in pushNamed [OK]
Common Mistakes:
  • Omitting context parameter
  • Passing data in route string instead of arguments
  • Using wrong parameter name like 'params'
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard