在互联网上获取文本文件的内容,flutter

get content of a text file on internet, flutter

当我读取存在于 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
});
      });
    });
  }

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

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

结果会是

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

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

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

所以当我调用 initsstate 中的函数然后打印 x 时,该值将为空!

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

所以我需要给其他字段或 属性 响应的内容,或者我想让我的函数 return 一个字符串而不是未来,这个字符串将是真正的内容作为字符串的响应,它不是 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