首页 文章

从另一个方法中的方法获取当前结果

提问于
浏览
2

我试图调用一个方法调用另一个方法..并取决于该方法结果我将继续我的方法..这样的事情:

void submit() async{
if (login) {
  ....
  bool result = await Login("966" + phone, _data.code);
  if (result) {
    successpage();
  } else {
    .....
  }

并登录:

bool Login(String phone, String SMScode) {
http.post(baseUrl + loginURL + "?phone=" + phone + "&smsVerificationCode="+ SMScode,
  headers: {
    'content-type': 'application/json'
  }).then((response) {
final jsonResponse = json.decode(Utf8Codec().decode(response.bodyBytes));
print("LOGIN: " + jsonResponse.toString());
Map decoded = json.decode(response.body);
print(decoded['success']);
if (decoded['success']) {
  globals.token = decoded['token'];
  globals.login = true;
}else{
  globals.login = false;
}
});
return globals.login;
}

但这不起作用,并没有给我我需要的最后一个bool的结果..如何解决这个问题?

1 回答

  • 2

    程序中的异步处理不正确 . 基本上你的 Login 函数返回而不等待http帖子 .

    以下更新应该有效 .

    Future<bool> Login(String phone, String SMScode) async {
      final response = await http.post('$baseUrl$loginURL?phone=$phone&smsVerificationCode=$SMScode',
          headers: {'content-type': 'application/json'});
      final jsonResponse = json.decode(Utf8Codec().decode(response.bodyBytes));
      print("LOGIN: " + jsonResponse.toString());
      Map decoded = json.decode(response.body);
      print(decoded['success']);
      if (decoded['success']) {
        globals.token = decoded['token'];
        globals.login = true;
      } else {
        globals.login = false;
      }
      return globals.login;
    }
    

相关问题