Irbisa · Cheatsheet
Navigation & Routing
Navigator, named routes, go_router, passing data between screens
What is the
Navigator, what is a route, and how dopushandpopwork?// Open a screen on top of the current oneNavigator.of(context).push( MaterialPageRoute(builder: (_) => const DetailsPage()),); // Close the top screen…What is the difference between
push,pushReplacement,pushAndRemoveUntilandpopUntil, and which one do you use after login?// Swap only the top routeNavigator.pushReplacement( context, MaterialPageRoute(builder: (_) => const HomePage()),);…How do you pass data to a new screen and get a result back?
// Forward: constructorNavigator.push( context, MaterialPageRoute(builder: (_) => DetailsPage(userId: '123')),);…ColorPickerPagepops withNavigator.pop(context, 'red'), but the user leaves with the system back button. What does this code print?Future<void> pickColor(BuildContext context) async { final color = await Navigator.push<String>( context, MaterialPageRoute(builder: (_) => const ColorPickerPage()), ); print('picked: $color');}How do named routes work, and how do you handle a parameterised route like
/product/42withonGenerateRoute?MaterialApp( routes: { '/': (_) => const HomePage(), '/settings': (_) => const SettingsPage(), }, onGenerateRoute: (settings) {…Tapping this button throws "Navigator operation requested with a context that does not include a Navigator": why?
class App extends StatelessWidget { const App({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: ElevatedButton( onPressed: () => Navigator.of(context).push( MaterialPageRoute(builder: (_) => const NextPage()), ), child: const Text('Go'), ), ), ); }}How do
showDialog,showModalBottomSheetandshowMenufit into the navigation stack?final confirmed = await showDialog<bool>( context: context, barrierDismissible: false, builder: (dialogContext) => AlertDialog( title: const Text('Delete account?'), actions: […How do you intercept the back button to confirm leaving a screen with unsaved changes (
PopScope, formerlyWillPopScope)?class _EditProfileState extends State<EditProfilePage> { bool _dirty = false; @override Widget build(BuildContext context) { return PopScope(…What is Navigator 2.0 (the Router API), how does it differ from Navigator 1.0, and why was it introduced?
class _AppState extends State<App> { Order? _selected; // the stack is a function of this state @override Widget build(BuildContext context) { return Navigator(…In
go_router, what is the difference betweencontext.go()andcontext.push()?final router = GoRouter( routes: [ GoRoute( path: '/orders', builder: (context, state) => const OrdersPage(), routes: […How do you build bottom navigation where each tab keeps its state and its own back stack?
final router = GoRouter( initialLocation: '/home', routes: [ StatefulShellRoute.indexedStack( builder: (context, state, shell) => Scaffold( body: shell, // keeps every branch alive…Find the bug: after
OrderPagemoved into a bottom-nav tab, tapping No closes the order screen and leaves this dialog open.Future<bool?> confirmCancel(BuildContext context) => showDialog<bool>( context: context, builder: (_) => AlertDialog( title: const Text('Cancel this order?'), actions: [ TextButton( onPressed: () => Navigator.pop(context, false), child: const Text('No'), ), TextButton( onPressed: () => Navigator.pop(context, true), child: const Text('Yes'), ), ], ), );How do you guard routes for authentication with
go_router?class AuthController extends ChangeNotifier { AuthStatus status = AuthStatus.loading; // loading, signedIn, signedOut void update(AuthStatus s) { status = s; notifyListeners(); }} GoRouter buildRouter(AuthController auth) => GoRouter(…Find the bug: after switching to dark mode on the settings screen, the app jumps back to the home screen.
class App extends StatelessWidget { const App({super.key, required this.theme}); final ValueNotifier<ThemeMode> theme; @override Widget build(BuildContext context) => ValueListenableBuilder( valueListenable: theme, builder: (context, mode, _) => MaterialApp.router( themeMode: mode, routerConfig: GoRouter(routes: [ GoRoute(path: '/', builder: (_, __) => const HomePage()), GoRoute(path: '/settings', builder: (_, __) => const SettingsPage()), ]), ), );}What is the stack after this code runs, which screen is on top, and what does the next Back show?
// the stack starts as [Home]final nav = Navigator.of(context);nav.pushNamed('/a');nav.pushNamed('/b');nav.pushNamed('/c');nav.pushReplacementNamed('/d');nav.pop();How do you set up deep links, Android App Links and iOS Universal Links in a Flutter app?
<!-- android/app/src/main/AndroidManifest.xml, inside the main activity --><intent-filter android:autoVerify="true"> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data…A push notification is tapped and you must open a specific screen. How do you navigate with no
BuildContextat hand?final navigatorKey = GlobalKey<NavigatorState>(); MaterialApp(navigatorKey: navigatorKey, home: const HomePage()); // From a service: no context neededvoid openOrder(String id) {…Your Flutter web app shows URLs like
example.com/#/orders/42, and after switching to clean paths a page refresh returns 404: what is going on?How do you build a custom page transition, and what are
animationandsecondaryAnimation?Route<T> fadeScaleRoute<T>(Widget page) { return PageRouteBuilder<T>( transitionDuration: const Duration(milliseconds: 280), reverseTransitionDuration: const Duration(milliseconds: 220), pageBuilder: (context, animation, secondaryAnimation) => page, transitionsBuilder: (context, animation, secondaryAnimation, child) {…How do Hero animations work, and what are the common pitfalls?
// List screenListTile( leading: Hero( tag: 'product-${product.id}', // unique per item child: Image.network(product.thumbUrl, width: 56, height: 56), ),…How does a screen find out that another route was pushed on top of it, for example, to pause a video?
final routeObserver = RouteObserver<PageRoute<void>>();// MaterialApp(navigatorObservers: [routeObserver], ...) class _PlayerPageState extends State<PlayerPage> with RouteAware { late final VideoPlayerController _controller = widget.controller;…On a slow phone a user double-taps a list row and two identical detail screens land on the stack: how do you prevent it?
class _OrderListState extends State<OrderList> { bool _navigating = false; Future<void> _open(Order order) async { if (_navigating) return; // second tap is ignored _navigating = true;…A deep link to a product opens the product screen, but Back closes the app instead of going to the catalog. How do you rebuild a proper back stack?
final router = GoRouter( routes: [ GoRoute( path: '/', builder: (_, __) => const HomePage(), routes: […Android kills your app in the background, and when the user returns the three-screen-deep stack is gone. How do you restore it?
void main() => runApp(const MaterialApp( restorationScopeId: 'app', // without this nothing is restored home: OrderListPage(), )); // Top-level and annotated: saved as a reference plus its arguments…