Hello i want to send my model class object to next screen previously i do it like this first i declare object in the second screen where i want to naviagte
class ContactsDetail extends StatelessWidget {
ContactModel contactDetail;
ContactsDetail({Key? key, required this.contactDetail}) : super(key: key);
Then in navigator i passed the argument
onTap: () async {
Navigator.of(context).push(MaterialPageRoute<void>(builder: (BuildContext context) {
return ContactsDetail(
contactDetail: contactlist[index],);
},
));
},`enter code here`
Which works perfectly, Now i am working with name routes and i want to send the whole model of current index data same as i do above but i am unable to do this Now here is my routes .
Route<dynamic> generateRoute(RouteSettings settings){
switch(settings.name)
{
case LoginScreen.routeName:
return MaterialPageRoute(builder: (context) => const LoginScreen());
case TourDetailScreen.routeName:
return MaterialPageRoute(builder: (context) => TourDetailScreen());
default:
return errorRoute();
}
}
And here is the class to which i want to send data
class TourDetailScreen extends StatelessWidget {
static const routeName = 'tourist_detail_screen';
TourModel tourDetails;
TourDetailScreen({Key? key,required this.tourDetails}) : super(key: key);
and this is main
MaterialApp(
debugShowCheckedModeBanner: false,
initialRoute: TouristHomeScreen.routeName,
onGenerateRoute: (settings) => generateRoute(settings),
),
CodePudding user response:
You can pass data in named route as well, using arguments
parameter of the Navigator.pushNamed()
method.
Navigator.pushNamed(
context,
ExtractArgumentsScreen.routeName,
arguments: ScreenArguments(
'Extract Arguments Screen',
'This message is extracted in the build method.',
),
);
// A Widget that extracts the necessary arguments from
// the ModalRoute.
class ExtractArgumentsScreen extends StatelessWidget {
const ExtractArgumentsScreen({super.key});
static const routeName = '/extractArguments';
@override
Widget build(BuildContext context) {
// Extract the arguments from the current ModalRoute
// settings and cast them as ScreenArguments.
final args = ModalRoute.of(context)!.settings.arguments as ScreenArguments;
return Scaffold(
appBar: AppBar(
title: Text(args.title),
),
body: Center(
child: Text(args.message),
),
);
}
}
ref: https://docs.flutter.dev/cookbook/navigation/navigate-with-arguments
CodePudding user response:
create class like this:
class ContactsDetailArguments {
final ContactModel contactDetail;
ContactsDetailArguments({
@required this.contactDetail,
});
}
and change your ContactsDetail like this:
class ContactsDetail extends StatelessWidget {
ContactsDetailArguments arguments;
ContactsDetail({Key? key, required this.arguments}) : super(key: key);
...
}
then in your route confige do this:
var arg = settings.arguments as ContactsDetailArguments;
return MaterialPageRoute(builder: (context) => const LoginScreen(arguments: arg));