How to get the Current Route Name in Flutter

Last updated on October 23, 2020 The Frog Loading... Post a comment

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:

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

The full code:

import 'package:flutter/material.dart';

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

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

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

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

Hope this helps!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles