【问题标题】:Dart return keyword in an async function异步函数中的 Dart 返回关键字
【发布时间】:2022-02-14 21:40:48
【问题描述】:

有人可以告诉我为什么return "NOK" 代码即使状态为真也会被执行? 这不是 return 关键字停止函数执行并返回值的目的吗?还是我错过了一些关于异步函数或 Dart 语言本身的东西?

static dynamic getUserRef() async {
    // HttpOverrides.global = MyHttpOverrides();
    bool status;
    await InfosHelper.getInfo('testinfo').then((response) {
      InfoModel info = InfoModel.fromJson(response.data);
      status = info.status;
      Map<String, dynamic> otherData = info.data;
      if (status) {
        return "OK";
      }
    });

    return "NOK";
  }

【问题讨论】:

  • 试试这个 >>>>>>>> static Future getUserRef() async { // HttpOverrides.global = MyHttpOverrides();布尔状态;最终任务快照 a = 等待 InfosHelper.getInfo('testinfo'); InfoModel info = InfoModel.fromJson(a.ref.data);状态=信息。状态;地图 otherData = info.data;如果(状态){返回“OK”; }else if (status==false){ return "NOK"; }else{ 打印(状态);返回“挪威克朗”; } }

标签: flutter dart asynchronous async-await


【解决方案1】:

您正在调用 .then 这是一个它自己的方法,因此状态为 true 将停止执行 .then 方法,但主 getUserRef 始终返回“Nok”

 static dynamic getUserRef() async {
    // HttpOverrides.global = MyHttpOverrides();
    bool status;
    var response=await InfosHelper.getInfo('testinfo');
     if (response!=null){
  InfoModel info=InfoModel.fromJson(response.data);
   Map<String, dynamic> otherData = info.data;
  if(info.status){
return 'ok';
}
else{
return 'nok'}
}
}
else{
//Error
}

【讨论】:

  • 嗯,好的。谢谢
【解决方案2】:

试试这个

 static Future<String> getUserRef() async {
        // HttpOverrides.global = MyHttpOverrides();            
        final response = await InfosHelper.getInfo('testinfo');
        InfoModel info = InfoModel.fromJson(response.data);
        bool status = info.status;
        Map<String, dynamic> otherData = info.data;
         
        return status ? "OK" : "NOK";
                
      }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-05
    • 1970-01-01
    • 2023-04-04
    相关资源
    最近更新 更多