获取互联网上文​​本文件的内容,扑朔迷离

时间:2020-10-10 07:14:49

标签: string flutter dart httpclient 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
});
      });
    });
  }

所以当我打印此文件的内容时

http://opml.radiotime.com/Tune.ashx?id=s120806

结果将是

https://st03.sslstream.dlf.de/dlf/03/128/mp3/stream.mp3

但是正如您在我的函数中看到的那样,我将内容的值赋予了x Field

setState(() {
  x = content; // value null
});

因此,当我在initstate中调用Function并打印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();
  }

所以我需要给其他字段或属性响应的内容,或者我想让我的函数返回一个字符串而不是一个Future,并且这个字符串实际上是作为字符串的The Response的内容,而不是空。

预先感谢

1 个答案:

答案 0 :(得分:1)

尝试一下

  @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

相关问题