'current route name is null on Flutter

Always getting null when I try to find current page. How do I get current page?

print('current page ${ModalRoute.of(context).settings.name}');

my end goal is,

if(ModalRoute.of(context).settings.name == 'homePage'){
showAlert()
}

my MaterialApp

 MaterialApp(
        onGenerateRoute: CustomRouter.generateRoute,
...

class CustomRouter {
  static Route<dynamic> generateRoute(RouteSettings settings) {
    final Arguments arguments = settings.arguments;

    switch (settings.name) {
      case Splash.route:
        return MaterialPageRoute(builder: (_) => Splash());


Solution 1:[1]

Ok, as an answer for the next visitors to this page, passing the RouteSettings parameter is required as mentioned here.


Route<dynamic> generateRoute(RouteSettings settings) {
    return MaterialPageRoute(
      settings: settings,
      builder: (BuildContext context) {
        //some custom code

        return _data[settings.name](context);
      }
    );
  }

Solution 2:[2]

    ...

MaterialPageRoute( settings: settings, // Important!!! ... )

Solution 3:[3]

Also it can related about wrong BuildContext, you must be ensure the given buildcontext must be same as your page buildcontext if it is not, you will get null or wrong route.

ModalRoute.of(currentPageContext)?.settings.name;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Akif
Solution 2 Kevin
Solution 3 leylekseven