【问题标题】:How to call one async function inside another async function in flutter如何在颤动中调用另一个异步函数中的一个异步函数
【发布时间】:2020-09-18 22:31:18
【问题描述】:

我有两个未来的功能,一个用于使用 API 验证 OTP,另一个用于使用 API 设置密码。

当 OTP 验证成功后,必须调用设置密码 API。我该怎么做?

我的代码是:

    () async {

var status = await registrationService.verifyOtp(registrationData.mobileNumber,otpController.text);
                                if(status == 'approved'){
                                  print('success');
                                      () async {
                                    var passwordStatus = await registrationService.setPassword(registrationData.name, registrationData.number, passController.text);
                                    if(passwordStatus == 'approved'){
                                      print('approved');
                                      Navigator.pushNamed(context, StudMainPage.id);
                                    }
                                    else{
                                      WidgetsBinding.instance.addPostFrameCallback((timeStamp) => _showNewVersionAvailableDialog(context));
                                    }
                                  };
                                 }

    }

它显示错误或函数没有被调用。我现在该怎么办? 提前致谢。

【问题讨论】:

    标签: android ios google-chrome flutter flutter-layout


    【解决方案1】:

    使用then回调

    registrationService.verifyOtp(registrationData.mobileNumber,otpController.text).then((status) {
    
    if(status == 'approved'){
       print('success');
    
    registrationService.setPassword(registrationData.name, registrationData.number, passController.text).then((response) {
    
    //....
    })))
    

    }

    【讨论】:

      【解决方案2】:

      创建第二个异步函数
      Future<PasswordStatus> getPasswordStatus() async {
      await registrationService.setPassword(registrationData.name, registrationData.number, passController.text);
      }
      

      并将该函数称为;

      if(status == 'approved'){
         var passwordStatus = await getPasswordStatus();
      }
      

      然后只需使用 passwordStatus 值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-07
        • 2022-07-11
        • 2021-02-21
        • 1970-01-01
        • 2020-03-04
        相关资源
        最近更新 更多