I've changed my Navigator.push to Navigator.pushNamed
but I don't understand how to pass data and receive/use it. If we use Navigator.push
, we can just do this and call the constructor to use the data, but if we use Navigator.pushNamed
, it sends arguments.
Now, how to call/use these arguments?
in /surveyPage page how do i call the arguments? in /surveyPage i have constructor languageCode but since i use pushNamed i cannot put languageCode.
this is the widget that i want to recieve the argument, i want to pass the argument to languageCode
class SurveyConsentPage extends StatefulWidget {
SurveyConsentPage({this.languageCode, Key key}) : super(key: key);
final String languageCode;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SurveyConsentPage(
languageCode: 'id',
),
),
);
pushNamed
Navigator.of(context).pushNamed('/surveyPage', arguments: 'id');
routes
case '/surveyPage':
return MaterialPageRoute(builder: (context) => SurveyConsentPage());
break;
CodePudding user response:
In your route case:
case '/surveyPage':
final code = settings.arguments as String;
return MaterialPageRoute(builder: (context) => SurveyConsentPage(languageCode: code));
break;
Make sure you have defined String languageCode
as a required parameter to your SurveyConsentPage
widget.
class SurveyConsentPage extends StatefulWidget {
final String languageCode;
SurveyConsentPage({required this.languageCode, Key key}) : super(key: key);
CodePudding user response:
To pass arguments
onPressed: () {
final String id = "myId is X";
Navigator.of(context).pushNamed('/surveyPage', arguments: id);
},
And to receive arguments it is essential to check null value, also notice that I am passing String
value, if you are using different data type replace it. A better approach is by creating class as shown on cookbook
@override
Widget build(BuildContext context) {
final arguments = ModalRoute.of(context)?.settings.arguments as String?;
return Scaffold(
appBar: AppBar(
title: Text(arguments ?? "didnot get any data"),
),
);
}
You can remove languageCode
variable from SurveyConsentPage
widget and use arguements
.