Challenge - 5 Problems
Named Routes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
intermediate
What screen does this named route navigate to?
Given this Flutter code snippet, which screen will be shown when navigating to '/profile'?
Flutter
MaterialApp( initialRoute: '/', routes: { '/': (context) => HomeScreen(), '/profile': (context) => ProfileScreen(), '/settings': (context) => SettingsScreen(), }, ); Navigator.pushNamed(context, '/profile');
Attempts:
2 left
💡 Hint
Check the routes map for the key '/profile'.
✗ Incorrect
The routes map defines '/profile' to show ProfileScreen. So Navigator.pushNamed with '/profile' shows ProfileScreen.
❓ ui_behavior
intermediateWhat happens if you navigate to an undefined named route?
Consider this Flutter app with routes defined only for '/' and '/home'. What happens if you call Navigator.pushNamed(context, '/about')?
Flutter
MaterialApp( initialRoute: '/', routes: { '/': (context) => SplashScreen(), '/home': (context) => HomeScreen(), }, ); Navigator.pushNamed(context, '/about');
Attempts:
2 left
💡 Hint
Check what happens when a route is missing in the routes map.
✗ Incorrect
If a named route is not found in the routes map and no onGenerateRoute is provided, Flutter throws a runtime error.
❓ lifecycle
advancedWhich lifecycle method is called when navigating to a new named route?
When you navigate from ScreenA to ScreenB using Navigator.pushNamed, which lifecycle method of ScreenB's stateful widget is called first?
Attempts:
2 left
💡 Hint
Think about widget creation lifecycle before build.
✗ Incorrect
initState() is called once when the state object is inserted into the widget tree, before build().
📝 Syntax
advancedIdentify the correct syntax for defining named routes in MaterialApp
Which option correctly defines named routes in a Flutter MaterialApp widget?
Flutter
MaterialApp( initialRoute: '/', routes: { '/': (context) => HomeScreen(), '/details': (context) => DetailsScreen(), }, );
Attempts:
2 left
💡 Hint
routes expects a Map.
✗ Incorrect
The routes property requires a map with string keys and functions returning widgets. Option B matches this.
🔧 Debug
expertWhy does this named route navigation fail at runtime?
Given this code, why does Navigator.pushNamed(context, '/profile') cause a runtime error?
Flutter
MaterialApp( initialRoute: '/', routes: { '/': (context) => HomeScreen(), '/profile': ProfileScreen(), }, ); Navigator.pushNamed(context, '/profile');
Attempts:
2 left
💡 Hint
Check the type of values in the routes map.
✗ Incorrect
The routes map values must be functions returning widgets, not widget instances. Here '/profile' maps to a widget instance, causing a runtime error.
