【问题标题】:how to call async function with ontap flutter?如何使用 ontap flutter 调用异步函数?
【发布时间】:2022-01-11 14:10:26
【问题描述】:

大家好,我是 Flutter 新手,我正在使用 api,所以我创建了一个异步函数,如下所示:

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

并像这样使用inkwell ontap调用:


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

但是什么都没有发生我不知道是什么问题,也许我以错误的方式调用我的函数?谁能帮我解决这个问题?

【问题讨论】:

标签: flutter api dart


【解决方案1】:

异步操作让您的程序在等待另一个操作完成的同时完成工作,请在此处阅读更多信息:https://dart.dev/codelabs/async-await

如果您希望执行该函数然后推送到另一个页面,您需要将 signup() 设置为 Future 并在 onTap() 函数中添加等待。

 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(),
                                  ),
                                );
                              },

【讨论】:

    【解决方案2】:

    试试这个

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

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 2023-03-06
      • 1970-01-01
      • 2018-10-03
      • 1970-01-01
      • 2023-02-10
      • 2020-03-09
      • 2020-06-04
      • 1970-01-01
      相关资源
      最近更新 更多