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

Question

Asked by alexlee11111 on December 17, 2021 (source).

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:

      Navigator.pushNamed(
        context,
        '/page2',
        arguments: {
          'name': widget.name,
          "id": widget.id,
        },
      );

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.

@override
void initState() {
   super.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);
}

Answer

Question answered by Sparsh J (source).

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

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

  @override
  SecondPageState createState() => SecondPageState();
}

And can use it into the init state like this.

class SecondPageState extends State<SecondPage> {
  @override
  void initState() {
    callApi(widget.args["name"], widget.args["id"]);
    super.initState();
  }
}
FLUTTER
SHARE: