9.4 C
New York
Monday, December 4, 2023

How to get the Current Route Name in Flutter

If you register the routes in your Flutter app like this:

return MaterialApp(
   home: HomePage(),
   routes: {
        'page-a': (BuildContext ctx) => PageA(),
        'page-b': (BuildContext ctx) => PageB(),
        'page-c': (BuildContext ctx) => PageC(),
   },
)

Then you can retrieve the route name of the current page that is being seen by using:Advertisements

ModalRoute.of(context).settings.name

Notes:

  • If you navigate to other pages by using pushNamed(), pushNamedAndRemoveUntil() or pushReplacementNamed(), youÂ’ll get the exact declared route names.
  • If you use push(), pushAndRemoveUntil(), or pushReplacement() for navigating to other pages, the results will be null.

Example

App preview:

The full code:

// main.dart
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // hide the debug banner
      debugShowCheckedModeBanner: false,
      title: "Kindacode.com",
      home: const HomePage(),
      routes: {
        'settings': (BuildContext ctx) => const SettingsPage(),
      },
    );
  }
}

// Home Page
class HomePage extends StatelessWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Home'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(30),
        child: Column(children: [
          Text("Route Name: ${ModalRoute.of(context)?.settings.name}"),
          const SizedBox(
            height: 30,
          ),
          TextButton(
              onPressed: () {
                Navigator.of(context).pushNamed('settings');
              },
              child: const Text('Go To Settings'))
        ]),
      ),
    );
  }
}

// Settings Page
class SettingsPage extends StatelessWidget {
  const SettingsPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Settings'),
      ),
      body: Center(
        child: Text("Route Name: ${ModalRoute.of(context)?.settings.name}"),
      ),
    );
  }
}

AdvertisementsFor simplicityÂ’s sake, I put everything in a single Dart file. If you want to follow good practice and keep your code organized, you can put each class in a separate file.

Futher reading:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Advertisements

Related Articles

Latest Articles