Home > Enterprise >  Why the function will Future return type can return a object not a Future type?
Why the function will Future return type can return a object not a Future type?

Time:10-15

In my test code , the function fetchExchangeRates will return a list object other than the Future as declared as it's return type , but this code will build well , but if I remove the async keyword , the compile will complains that the type mismatch.

So why the build is OK with the async keyword?

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');
}

CodePudding user response:

because async makes your function asynchronous and returns a Future type without async Future not Future

use async when u want to get asynchronous response with await

like

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

CodePudding user response:

if there is no await you can remove Future & async both

  • Related