'http request not executed when run in isolate
Why is the request not executed?
import 'package:http/http.dart' as http;
String req(String x) {
print("$x req");
doReq() async {
final url = Uri.parse("http://google.com");
print("$x $url");
final re = await http.get(url);
print("$x re:");
print(re.body);
}
doReq();
print("$x done");
return "ok";
}
// somewhere in the UI
ElevatedButton(
child: const Text("run"),
onPressed: () {
print("in main isolate");
req("1");
print("in separate isolate");
compute(req, "2");
},
);
Output:
I/flutter (20379): in main isolate
I/flutter (20379): 1 req
I/flutter (20379): 1 http://google.com
I/flutter (20379): 1 done
I/flutter (20379): in separate isolate
I/flutter (20379): 1 re:
I/flutter (20379): <!doctype html>...
I/flutter (20379): 2 req
I/flutter (20379): 2 http://google.com
I/flutter (20379): 2 done
The request is not executed when req runs in an isolate - why and how can I fix this?
Solution 1:[1]
Flutter's compute immediately closes the spawned isolate after the method returns and any returned Future is completed. Since your req function synchronously returns a string, the HTTP request will not have completed by the time the isolate is destroyed.
If you await the doReq() call (and return a Future<String> from req), you will probably see the response body both times.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nitrodon |
