Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between initialRoute and home in MaterialApp

Tags:

flutter

dart

Why is there the initialRoute property when home already exists in Flutter?

like image 499
iDecode Avatar asked May 13 '20 01:05

iDecode


People also ask

What is home in MaterialApp flutter?

home. The widget for the default route of the app (Navigator. defaultRouteName, which is / ). This is the route that is displayed first when the application is started normally, unless initialRoute is specified. It's also the route that's displayed if the initialRoute can't be displayed.

What is initialRoute in flutter?

initialRoute. The name of the first route to show, if a Navigator is built.

What is the use of home in flutter?

home: This property takes in widget as the object to show on the default route of the app. initialRoute: This property takes in a string as the object to give the name of the first route in which the navigator is built. locale: It provides a locale for the MaterialApp.


1 Answers

It's more about code readability (but not limited to), see all of them are doing the same job but in different ways:

runApp(
  MaterialApp(
    home: HomePage(),
  ),
);

or

runApp(
  MaterialApp(
    initialRoute: '/',
    routes: {
      '/': (_) => HomePage(),
    },
  ),
);

Use of onGenerateInitialRoute/onGenerateRoute allows you to change navigator animation too.

runApp(
  MaterialApp(
    onGenerateInitialRoutes: (route) {
      return [
        MaterialPageRoute(builder: (_) => HomePage())
      ];
    }
  ),
);

or

runApp(
  MaterialApp(
    initialRoute: '/',
    onGenerateRoute: (settings) {
      if (settings.name == '/') return MaterialPageRoute(builder: (_) => HomePage());
      return MaterialPageRoute(builder: (_) => UnknownPage()); // you can do this in `onUnknownRoute` too
    },
  ),
);
like image 123
iDecode Avatar answered Dec 06 '22 22:12

iDecode