In the code below, the screens are registered in routes, and then the screen can be navigated to by calling Navigator.pushNamed(context, '/second');
. This works fine if the SecondScreen does not need any parameters. What if the SecondScreen requires parameters paramA and paramB, and these 2 parameters are not available during the app initialization. So the following code will not work because paramA and paramB are not yet available at the time the SecondScreen is registered to the routes.
void main() {
runApp(
MaterialApp(
title: 'Named Routes Demo',
initialRoute: '/',
routes: {
'/': (context) => const FirstScreen(),
'/second': (context) => const SecondScreen(paramA, paramB),
},
),
);
}
How to register widgets to the routes if those widgets require some parameters that are not yet available?
You can define a class ScreenArguments
for argument, after that you get it on widget with this code:
final args = ModalRoute.of(context)!.settings.arguments as ScreenArguments;
Detail: https://docs.flutter.dev/cookbook/navigation/navigate-with-arguments