import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() async {
print('start api');
for (var i = 1; i < 4; i++) {
print(unawaited(fetchApi(i)));
}
print('end api');
}
Future<String> fetchApi(int idNum) async {
final url = Uri.parse('https://jsonplaceholder.typicode.com/albums/$idNum');
final response = await http.get(url);
final jsonData = jsonDecode(response.body);
return jsonData['title'];
}
Based on documentation, i should just import async package and use unawaited().
However, i noticed that the unawaited() only take Future.
How to make this code works?
thanks.
**The idea is to allow the next code in line triggered while http.get still doing its job.
or should i move to Stream?
fetchApi() need to return string instead of void.
3
Answers
Unawaited is used as a fire and forget method. So you can’t do anything with it’s response because it will continue in the code once the first await has been triggered.
To execute your fetch api do the following:
If you only want to log the string you can do it in your fetchApi function:
But if you want to do something else with your string, use another method and fire and forget that one:
In both my examples, the output will be the following:
If you want to wait for
async
function you can useawait
before it, but if you don’t want to wait for it and let other code runs you don’t need any thing, so your code should looks like this:but this won’t give you what you want. you need to use
Stream
like this:unawaited
is for use when you don’t care about when theFuture
completes. However, you do want to wait for theFuture
complete so that you can callprint
on its result.In your case, you could explicitly use
Future.then
. (Normally you should avoidFuture.then
in favor ofasync
/await
, but this is a case where usingFuture.then
is a bit more straightforward.)Future.then
itself returns aFuture
, so you can useunawaited
on that:That said, I think it’d be even better to wait until all of your
Future
s complete before claiming that you’re done and returning frommain
. For that, useFuture.wait
:The above code won’t print
'end api'
until after allFuture
s complete.