Sub topic 2
Named routes and when they fall short
This chapter assumes you know Dart async and await, basic widgets such as Scaffold and AppBar, what BuildContext is, and how to call Navigator.push and Navigator.pop.
Named routes
A named route is a string, such as '/details', that points to a screen. You register the names on MaterialApp:
MaterialApp(
initialRoute: '/',
routes: {
'/': (context) => const HomeScreen(),
'/details': (context) => const DetailScreen(),
},
);Navigate with Navigator.of(context).pushNamed('/details');.
Named routes fall short in two cases. The routes map builds each screen without arguments, so a screen that needs an ID has no clean way to receive it. The map also cannot check names or build screens on demand.
Building routes dynamically with onGenerateRoute
onGenerateRoute receives a RouteSettings object with the name and arguments, and returns a Route or null.
MaterialApp(
initialRoute: '/',
onGenerateRoute: (settings) {
switch (settings.name) {
case '/':
return MaterialPageRoute<void>(
builder: (_) => const HomeScreen(),
settings: settings,
);
case '/details':
final id = settings.arguments as int;
return MaterialPageRoute<void>(
builder: (_) => DetailScreen(id: id),
settings: settings,
);
}
return null;
},
);Handling the back button with PopScope
PopScope decides whether a pop may proceed. Set canPop to false to block the system back button, then handle the pop yourself.
class DraftScreen extends StatelessWidget {
const DraftScreen({super.key});
@override
Widget build(BuildContext context) {
return PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, result) {
if (didPop) return;
Navigator.of(context).pop('discarded');
},
child: const Scaffold(body: Center(child: Text('Draft'))),
);
}
}Customizing page transitions
PageRouteBuilder lets you replace the default slide with your own animation.
Route<void> fadeRoute(Widget page) {
return PageRouteBuilder<void>(
pageBuilder: (context, animation, secondaryAnimation) => page,
transitionsBuilder: (context, animation, secondaryAnimation, child) {
return FadeTransition(opacity: animation, child: child);
},
transitionDuration: const Duration(milliseconds: 300),
);
}Observing navigation with NavigatorObserver
A NavigatorObserver receives a callback for each push and pop, which is useful for analytics and logging.
class LoggingObserver extends NavigatorObserver {
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
debugPrint('Pushed ${route.settings.name}');
}
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) {
debugPrint('Popped ${route.settings.name}');
}
}
// In MaterialApp: navigatorObservers: [LoggingObserver()],Declarative navigation and the Router API
Imperative navigation changes the stack when your code calls push or pop. Declarative navigation describes the screens that should exist for a given URL or state, and the framework builds the stack from that description. The Router API provides this model. The go_router package is the common way to use it. Choose declarative routing when you need web URLs, deep links, or redirects such as login guards. Stay with imperative navigation for simple apps with a few screens.
Exercise
Exercise
In onGenerateRoute, what happens if you return null for an unknown name?
Show answer
Flutter reports an error for the unknown route. Returning null tells the Navigator that this callback cannot build the route, so you should also provide a fallback route, such as a not-found screen.