Flutter Named Routes with Example

In Flutter, named routes allow you to navigate between screens in your app by giving each screen a unique name. This makes it easier to navigate your app and allows you to reuse the same screen in multiple places.

Here's an example of how to use named routes in Flutter

Define your named routes in your MaterialApp widget in main.dart:

import 'package:flutter/material.dart';
import 'package:flutter_blog/screens/home_screen.dart';
import 'package:flutter_blog/screens/post_screen.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Blog',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: '/',
      routes: {
        '/': (context) => HomeScreen(),
        '/post': (context) => PostScreen(),
      },
    );
  }
}

In this example, we have defined two named routes: '/' for the home screen and '/post' for the post screen.

Navigate to a named route using Navigator.pushNamed():

Navigator.pushNamed(context, '/post');

In this example, we are navigating to the post screen using the '/' route.

Receive arguments from a named route using ModalRoute.of() and settings.arguments

class PostScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final args = ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>;
    final post = args['post'];
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Blog'),
      ),
      body: Center(
        child: Text(post.title),
      ),
    );
  }
}

In this example, we are receiving a post object as an argument from the '/' route and displaying its title in the post screen.

Navigate back to the previous screen using Navigator.pop()

Navigator.pop(context);

In this example, we are navigating back to the home screen from the post screen.

Pass arguments to a named route using Navigator.pushNamed() and arguments

Navigator.pushNamed(
  context,
  '/post',
  arguments: {'post': post},
);

In this example, we are passing a post object as an argument to the post screen using the '/post' route.

Run your app and test the named routes

flutter run