You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Main方法中获取异步Future方法返回的变量值

异步Future方法返回值丢失的解决办法

问题原因

你调用的test()是异步方法,返回Future<String>类型。直接执行method.test()时,程序不会等待这个异步操作完成,就立刻往下执行print(result),这时候结果还没返回,变量自然是null。

解决方式1:用await等待结果返回

把main改成异步方法,用await关键字等待test()执行完毕,再把结果赋值给变量:

// file_1 -----------:
void main(List<String> args) async {
  var result = await method.test();
  print(result); // 这里会正确输出'1'
}

// file_2 -----------:
class method {
  static Future<String> test() async{
    var result = '1';
    return result;
  }
}

解决方式2:用.then()处理回调

要是不想改动main的异步状态,可以通过then方法,在Future完成后再处理结果:

// file_1 -----------:
void main(List<String> args) {
  method.test().then((value) {
    var result = value;
    print(result); // 异步完成后输出'1'
    // 所有依赖这个结果的后续逻辑都要放在这里面
  });
}

// file_2 -----------:
class method {
  static Future<String> test() async{
    var result = '1';
    return result;
  }
}

额外提醒

你实际场景里是和PHP做网络请求,这类操作本身就是异步的,必须用上述两种方式之一等待结果返回后再处理后续逻辑,不然一定会出现变量为空的情况。

内容的提问来源于stack exchange,提问作者Matheus Duarte

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 03:14:56