How can I use the argument value at the new page initState in Flutter?



If I pass some argument while rotating from one page to another page, how can I use the argument value at the new page initState in Flutter?

Assume I have two Flutter page, and I would like to navigate to another pages as following:

        arguments: {

Then I can display the argument at the page2 by replacing the following code inside the build function:

final Map<String, dynamic>? args =
    ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>?;

var name= args!["name"];
var id = args["id"];

print("name:" + name);
print("id" + id);

Now, I would like to do some API call by passing the arguments to the initState.

void initState() {
   // how can I pass the argument id and argument name to the function?
   callApi(id, name);

callApi(id, name) async {
   var response = await api(id, name);


You should define the routes into your app main.dart file like this.

      routes: {
        "/page1": (context) => const Homepage(),
        "/page2": (context) => SecondPage(
            ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>),
      initialRoute: "/page1",

And then define the parameters into the second page class

class SecondPage extends StatefulWidget {
  final Map<String, dynamic>? args;

  const SecondPage(this.args, {Key? key}) : super(key: key);

  SecondPageState createState() => SecondPageState();

And can use it into the init state like this.

class SecondPageState extends State<SecondPage> {
  void initState() {
    callApi(widget.args["name"], widget.args["id"]);

Answered By – Sparsh Jain

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More