Home > Mobile >  how to call async function with ontap flutter?
how to call async function with ontap flutter?

Time:12-06

hello guys i am new to flutter and i am working with apis so i created a async function as follows:

 signup() async {
      var response = await http.post(Uri.parse(ROOT), body: {
      "email": emailController.text,
      "action":'Sign_Up',
      "phone":phoneController.text,
    });
  }

and calling with inkwell ontap like this:


     InkWell(
                                  highlightColor: Colors.transparent,
                                  splashColor: Colors.transparent,
                                  onTap: (){
                                    signup();
                                    Navigator.push(
                                      context,
                                      MaterialPageRoute(
                                        builder: (context) => PhoneVerification(),
                                      ),
                                    );
                                  },

but nothing is happening I don't know what is the issue maybe I am calling my function in the wrong way? can anyone help me with this?

CodePudding user response:

Try with this

                   onTap: ()async{
                                await signup();
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => PhoneVerification(),
                                  ),
                                );
                              },

CodePudding user response:

Asynchronous operations let your program complete work while waiting for another operation to finish, please read more about it here: https://dart.dev/codelabs/async-await.

if you wish to execute the function and then push to another page you need to make signup() as Future and add wait in the onTap() function.

 Future signup() async {
      var response = await http.post(Uri.parse(ROOT), body: {
      "email": emailController.text,
      "action":'Sign_Up',
      "phone":phoneController.text,
    });
  }

  onTap: ()async{
                                await signup();
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => PhoneVerification(),
                                  ),
                                );
                              },
  • Related