Get Current Route Name in Flutter
In Flutter, you can obtain the current route name by using the ModalRoute
class and accessing its settings
property.
Here’s an example on how to get the current route name:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => HomeScreen(),
'/details': (context) => DetailsScreen(),
},
);
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
String routeName = ModalRoute.of(context).settings.name;
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Current Route Name:',
),
Text(
routeName,
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.pushNamed(context, '/details');
},
child: Icon(Icons.arrow_forward),
),
);
}
}
class DetailsScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
String routeName = ModalRoute.of(context).settings.name;
return Scaffold(
appBar: AppBar(
title: Text('Details'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Current Route Name:',
),
Text(
routeName,
style: Theme.of(context).textTheme.headline4,
),
],
),
),
);
}
}
In the above example, we have two screens: HomeScreen
and DetailsScreen
. The current route name is obtained using ModalRoute.of(context).settings.name
and displayed on each screen.
When you run the app, the initial route is set to '/'
which is associated with the HomeScreen
. When you tap on the floating action button, it navigates to the DetailsScreen
whose route is '/details'
.
On both screens, the current route name is displayed using the Text
widget.
Note: To use the ModalRoute.of(context)
method, make sure the widget is included in a MaterialApp
or CupertinoApp
widget as it provides the required context.