Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/flutter/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 在internet上获取文本文件的内容,颤振_String_Flutter_Dart_Httpclient_Response - Fatal编程技术网

String 在internet上获取文本文件的内容,颤振

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)

当我读取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) {
      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
  }