gpt4 book ai didi

dart - 从外部访问http响应体

转载 作者:行者123 更新时间:2023-12-02 18:14:08 32 4
gpt4 key购买 nike

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
}

大家好,

从有一天起,我就开始使用 Dart,想弄清楚它是否适合我的需求。在我附加的代码中,我想访问 http 查询 block 之外的正文结果。这是不可能的。在另一个问题中,有人写道这是因为 Darts 异步概念。

有没有办法从外部访问。这很重要,因为我必须使用结果数据触发多个 tttp 请求,并且不希望将它们全部嵌套在 http block 中。

或者还有其他建议吗?

非常感谢。

最佳答案

这种方式不起作用,因为异步调用 (http.get()) 被安排为稍后执行,然后继续执行下一行。您的 print 会在 http.get() 开始连接之前执行。您需要将所有连续的调用与 then 链接起来。如果您有最新的 Dart 版本,您可以使用 async/await,这使得使用异步调用更容易。

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

异步/等待

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

关于dart - 从外部访问http响应体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29186785/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com