Flutter navigator get current route

To get the current route in Flutter, you can use the Navigator class along with the ModalRoute.
Below is an example code that demonstrates how to get the current route in Flutter:

    
import 'package:flutter/material.dart';

class MyNavigatorPage extends StatefulWidget {
  @override
  _MyNavigatorPageState createState() => _MyNavigatorPageState();
}

class _MyNavigatorPageState extends State {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Current Route Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            ElevatedButton(
              child: Text('View Route Name'),
              onPressed: () {
                Navigator.pushNamed(context, '/second');
              },
            ),
          ],
        ),
      ),
    );
  }
}

class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Second Page'),
      ),
      body: Center(
        child: ElevatedButton(
          child: Text('Get Current Route'),
          onPressed: () {
            var currentRoute = ModalRoute.of(context).settings.name;
            print('Current Route: $currentRoute');
          },
        ),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    initialRoute: '/',
    routes: {
      '/': (context) => MyNavigatorPage(),
      '/second': (context) => SecondPage(),
    },
  ));
}
    
  

In the above example, we have two pages: the first page is called MyNavigatorPage and the second page is called SecondPage.
When the user presses the ElevatedButton on MyNavigatorPage, it navigates to the second page SecondPage.
On the second page, when the user presses the ElevatedButton, it calls the ModalRoute.of(context).settings.name to get the current route name.
The name of the current route is then printed in the console using print().

Remember to define the routes in the MaterialApp using initialRoute and routes.
In this example, the initial route is set to ‘/’ and the routes map the route names to their corresponding pages.

Leave a comment