Skip to content

Instantly share code, notes, and snippets.

@epipheus
Last active July 13, 2021 02:18
Show Gist options
  • Save epipheus/58f96f728b7db3019994dd6273ac54bd to your computer and use it in GitHub Desktop.
Save epipheus/58f96f728b7db3019994dd6273ac54bd to your computer and use it in GitHub Desktop.
passing arguments as a map
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Navigation with Arguments',
initialRoute: '/',
routes: {
'/': (context) => HomeScreen(),
ArgScreen.routeName: (context) => ArgScreen(),
});
}
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home Screen'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
child: Text("Navigate to arg passing example screen"),
onPressed: () {
Navigator.pushNamed(
context,
ArgScreen.routeName,
arguments: {
'arg1': 'Random Title',
'arg2': 'This is a random message',
},
);
},
),
],
),
));
}
}
// A Widget that extracts the necessary arguments from the ModalRoute.
class ArgScreen extends StatelessWidget {
static const routeName = '/argExample';
@override
Widget build(BuildContext context) {
final args = ModalRoute.of(context)!.settings.arguments as Map;
return Scaffold(
appBar: AppBar(
title: Text(args['arg1']),
),
body: Center(
child: Text(args['arg2']),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment