0
0
FlutterHow-ToBeginner · 3 min read

How to Use Named Routes in Flutter for Easy Navigation

In Flutter, you use named routes by defining a Map of route names to widget builders in MaterialApp under routes. Then, navigate using Navigator.pushNamed(context, '/routeName') to move between screens by their route names.
📐

Syntax

Define named routes in the MaterialApp widget using the routes property, which is a map of route names to builder functions. Use Navigator.pushNamed to navigate to a route by its name.

  • routes: A map where keys are route names (strings) and values are functions returning widgets.
  • Navigator.pushNamed(context, routeName): Pushes the named route onto the navigation stack.
dart
MaterialApp(
  routes: {
    '/': (context) => HomeScreen(),
    '/about': (context) => AboutScreen(),
  },
);

// Navigate to AboutScreen
Navigator.pushNamed(context, '/about');
💻

Example

This example shows a simple app with two screens: Home and About. It uses named routes to switch between them by pressing a button.

dart
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(),
        '/about': (context) => AboutScreen(),
      },
    );
  }
}

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

class AboutScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('About')),
      body: Center(
        child: Text('Welcome to the About Screen!'),
      ),
    );
  }
}
Output
The app starts on the Home screen with a button labeled 'Go to About'. When tapped, it navigates to the About screen showing the text 'Welcome to the About Screen!'.
⚠️

Common Pitfalls

  • Forgetting to define a route in the routes map causes navigation errors.
  • Using incorrect route names (typos) will fail silently or throw exceptions.
  • Not setting initialRoute defaults to '/', so ensure your home route matches.
  • Trying to pass arguments requires a different approach (use onGenerateRoute).
dart
/* Wrong: route not defined */
Navigator.pushNamed(context, '/settings'); // Error if '/settings' not in routes

/* Right: define route */
MaterialApp(
  routes: {
    '/settings': (context) => SettingsScreen(),
  },
);
📊

Quick Reference

Use this cheat sheet to remember key points about named routes in Flutter:

ConceptDescription
routesMap of route names to widget builders in MaterialApp
Navigator.pushNamedNavigate to a named route
initialRouteThe first route shown when app starts
Route namesStrings starting with '/' (e.g., '/home')
onGenerateRouteUse for dynamic routes or passing arguments

Key Takeaways

Define named routes in MaterialApp's routes map with string keys and widget builders.
Navigate between screens using Navigator.pushNamed with the route name string.
Always include the route name in routes to avoid navigation errors.
Set initialRoute to control the app's starting screen.
Use onGenerateRoute for advanced routing needs like passing arguments.