Reputation: 152
import 'package:http/http.dart' as http;
main() {
String esearch = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=nucleotide&term=Paenibacillus";
var uidList = [];
http.get(esearch).then((response) {
var pattern = new RegExp(r"<Id>(.*?)</Id>");
var hits = pattern.allMatches(response.body);
hits.forEach((hit) {
print("whole match: " + hit[0] + " first match " + hit[1]);
uidList.add(hit[1]);
});
});
print(uidList.length); // empty, because main thread is faster than query
}
Hello everyone,
I'm playing around with Dart since one day to figure out, whether it's suitable for my needs. In the code I have attached, I want to access the result of the body outside of the http query block. This isn't possible. In another question here, someone writes this is because of Darts async concept.
Is there a way to get access to from outside. This is import because I have to trigger several htttp requests with the resulting data and don't wont to nest them all within the http block.
Or any other suggestions?
Thank you very much.
Upvotes: 3
Views: 137
Reputation: 657308
This doesn't work this way because an async call (http.get()
) is scheduled for later execution and than execution proceeds with the next line. Your print
is executed before http.get()
even started to connect. You need to chain all successive calls with then.
If you have a recent Dart version you can use async/await which makes using async calls easier.
import 'package:http/http.dart' as http;
main() {
String esearch = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=nucleotide&term=Paenibacillus";
var uidList = [];
return http.get(esearch).then((response) {
var pattern = new RegExp(r"<Id>(.*?)</Id>");
var hits = pattern.allMatches(response.body);
hits.forEach((hit) {
print("whole match: " + hit[0] + " first match " + hit[1]);
uidList.add(hit[1]);
});
return uidList;
}).then((uidList) {
print(uidList.length);
});
}
async/await
import 'package:http/http.dart' as http;
main() async {
String esearch = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db=nucleotide&term=Paenibacillus";
var uidList = [];
var response = await http.get(esearch);
var pattern = new RegExp(r"<Id>(.*?)</Id>");
var hits = pattern.allMatches(response.body);
hits.forEach((hit) {
print("whole match: " + hit[0] + " first match " + hit[1]);
uidList.add(hit[1]);
});
print(uidList.length);
}
Upvotes: 2