Reputation: 303
In a Flutter app I have the following code in main.dart
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(),
initialRoute: '/login',
onGenerateRoute: Router.generateRoute,
);
My Router.dart has the below code
class Router {
static Route<dynamic> generateRoute(RouteSettings settings) {
print('setting.name: ${settings.name}');
switch (settings.name) {
case '/':
return MaterialPageRoute(builder: (_) => HomeView());
case '/login':
return MaterialPageRoute(builder: (_) => LoginView());
case '/post':
return MaterialPageRoute(builder: (_) => PostView());
default:
return MaterialPageRoute(
builder: (_) {
return Scaffold(
body: Center(
child: Text('No Route for ${settings.name}'),
),
);
},
);
}
}
}
and my home_view.dart has the below code
class HomeView extends StatelessWidget {
@override
Widget build(BuildContext context) {
print('homeview');
return Scaffold();
}
I am printing the value of settings.name in router.dart. When I start the app I get the below output in debug console:
Launching lib\main.dart on Android SDK built for x86 in debug mode...
√ Built build\app\outputs\apk\debug\app-debug.apk.
Connecting to VM Service at ws://127.0.0.1:56463/QrArHr5Zg54=/ws
D/EGL_emulation(13000): eglMakeCurrent: 0xd5f1a540: ver 3 1 (tinfo 0xd5f0f880)
I/flutter (13000): setting.name: /
I/flutter (13000): setting.name: /login
I/flutter (13000): homeview
Since initialRoute is set to '/login', I am not sure why am I getting
I/flutter (13000): setting.name: / and
I/flutter (13000): homeview
I expected it to directly go to '/login' case and render LoginView. Can someone explain what's happening here?
Upvotes: 3
Views: 5859
Reputation: 1565
This happening because you have use slash in initialRoute.For example, if the route /stocks/HOOLI
was used as the [initialRoute], then the [Navigator] would push the following routes on startup: /
, /stocks
, /stocks/HOOLI
. This is done for deep-linking. https://api.flutter.dev/flutter/widgets/WidgetsApp/initialRoute.html. Just remove the slash from initial route, it will directly push that route.
Upvotes: 6