0

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 receive 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;
wohlstad
  • 12,661
  • 10
  • 26
  • 39
CCP
  • 886
  • 1
  • 10
  • 30

2 Answers2

2

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);
Roslan Amir
  • 1,141
  • 8
  • 16
0

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 ?? "did not get any data"),
    ),
  );
}

You can remove languageCode variable from SurveyConsentPage widget and use arguments.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56