【问题标题】:Why the function will Future return type can return a object not a Future type?为什么Future返回类型的函数可以返回一个对象而不是Future类型?
【发布时间】:2021-10-14 17:16:46
【问题描述】:

在我的测试代码中,函数 fetchExchangeRates 将返回一个列表对象,而不是 Future 声明为它的返回类型,但此代码将构建良好,但如果我删除 async 关键字,编译将抱怨类型不匹配.

那么为什么使用 async 关键字构建是可以的?

class Rate{
  String baseCurrency = '';
  String quoteCurrency = '';
  double exchangeRate = 0;
  
  Rate({required this.baseCurrency,required this.quoteCurrency,required this.exchangeRate});
} 

Future<List<Rate>> fetchExchangeRates() async{
    List<Rate> list = [];
    list.add(Rate(
      baseCurrency: 'USD',
      quoteCurrency: 'EUR',
      exchangeRate: 0.91,
    ));
    list.add(Rate(
      baseCurrency: 'USD',
      quoteCurrency: 'CNY',
      exchangeRate: 7.05,
    ));
    list.add(Rate(
      baseCurrency: 'USD',
      quoteCurrency: 'MNT',
      exchangeRate: 2668.37,
    ));
    print('fetchExchangeRates returns');
    return list;
  }


void main() {
  fetchExchangeRates();
      print('after fetchExchangeRates');
}

【问题讨论】:

标签: flutter dart


【解决方案1】:

因为async 使您的函数异步并返回没有async Future 而不是FutureFuture 类型

当你想用await获得异步响应时,使用async

喜欢

Future<void> _foo () async {
  await yourAsynchronousRequest();
}

【讨论】:

  • 谢谢@novol,你的意思是每个带有 async 关键字的函数都会被编译器自动返回一个 Future 对象?
  • 是的,我就是这个意思
【解决方案2】:

如果没有 await 你可以删除 Future & async 两者

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多