CCP
CCP

Reputation: 1236

How to receive arguments from pushNamed

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;

Upvotes: 0

Views: 3773

Answers (2)

Md. Yeasin Sheikh
Md. Yeasin Sheikh

Reputation: 63749

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.

Upvotes: 0

Roslan Amir
Roslan Amir

Reputation: 1346

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);

Upvotes: 2

Related Questions