String 在internet上获取文本文件的内容,颤振
当我读取internet上url上存在的文本文件的内容时,它只是函数内部的工作 这是我的职责String 在internet上获取文本文件的内容,颤振,string,flutter,dart,httpclient,response,String,Flutter,Dart,Httpclient,Response,当我读取internet上url上存在的文本文件的内容时,它只是函数内部的工作 这是我的职责 String x=""; Future<String> ip(String url) async { HttpClient client = new HttpClient(); var request = await client.postUrl(Uri.parse(url)); request.close().then((response)
String x="";
Future<String> ip(String url)
async {
HttpClient client = new HttpClient();
var request = await client.postUrl(Uri.parse(url));
request.close().then((response) {
utf8.decoder.bind(response.cast<List<int>>()).listen((content) {
print(content);// output https://st03.sslstream.dlf.de/dlf/03/128/mp3/stream.mp3
setState(() {
x = content; // value null
});
});
});
}
结果将是
https://st03.sslstream.dlf.de/dlf/03/128/mp3/stream.mp3
但正如你在我的函数中看到的,我给了x字段内容的值
setState(() {
x = content; // value null
});
因此,当我在initsstate中调用函数并打印x时,该值将为null
@override
void initState() {
ip("http://opml.radiotime.com/Tune.ashx?id=s120806"); //output https://st03.sslstream.dlf.de/dlf/03/128/mp3/stream.mp3
print(x); // output null
super.initState();
audioStart();
}
所以我需要给其他字段或属性响应的内容,或者我想让我的函数返回一个字符串,而不是未来,这个字符串实际上是响应的内容,作为一个字符串,它不是null
提前感谢试试这个
@override
void initState() {
initAsyncState();
}
void initAsyncState() async {
await ip("http://opml.radiotime.com/Tune.ashx?id=s120806"); //output https://st03.sslstream.dlf.de/dlf/03/128/mp3/stream.mp3
print(x); // output will not be null
}
如果要在小部件中使用响应,请使用
FutureBuilder
,在自定义StatefulWidget
中如何处理该x
?要在一些由build()
方法构建的Widget
中使用它,请使用x为空,因为当print语句打印x时,将来的ip
甚至不会执行,要使x不为空,您必须等待ip
完成,请记住,init不支持异步,要获取字符串,只需使用:var response=wait request.close();返回响应。单个。然后(utf8。解码)使用包时,代码>甚至更好:Future _initFuture()async{var resp=wait http.get('http:/…');return resp.body;}
@override
void initState() {
initAsyncState();
}
void initAsyncState() async {
await ip("http://opml.radiotime.com/Tune.ashx?id=s120806"); //output https://st03.sslstream.dlf.de/dlf/03/128/mp3/stream.mp3
print(x); // output will not be null
}