routes
is static and doesn't offer functionalities like passing an argument to the widget, implementing a different PageRoute
etc, which is why onGenerateRoute
exists.
In the given code, you'll find that how using onGenerateRoute
property, you can parse an argument and send it over, which isn't possible with simple routes
.
FooPage
is navigated through routes
and BarPage
through onGenerateRoute
.
Initial setup in MaterialApp
.
void main() {
runApp(
MaterialApp(
routes: {
'/': (_) => HomePage(), // You can also use MaterialApp's `home` property instead of '/'
'/foo': (_) => FooPage(), // No way to pass an argument to FooPage.
},
onGenerateRoute: (settings) {
if (settings.name == '/bar') {
final value = settings.arguments as int; // Retrieve the value.
return MaterialPageRoute(builder: (_) => BarPage(value)); // Pass it to BarPage.
}
return null; // Let `onUnknownRoute` handle this behavior.
},
),
);
}
home.dart
:
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('HomePage')),
body: Center(
child: Column(
children: [
ElevatedButton(
onPressed: () => Navigator.pushNamed(context, '/foo'),
child: Text('Go to FooPage'),
),
ElevatedButton(
onPressed: () => Navigator.pushNamed(context, '/bar', arguments: 42), // Passing argument
child: Text('Go to BarPage'),
),
],
),
),
);
}
}
foo.dart
class FooPage extends StatelessWidget {
@override
Widget build(_) => Scaffold(appBar: AppBar(title: Text('FooPage')));
}
And bar.dart
:
class BarPage extends StatelessWidget {
final int value;
BarPage(this.value);
@override
Widget build(_) => Scaffold(appBar: AppBar(title: Text('BarPage, value = $value')));
}
Screenshot (for reference)