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

标签 string flutter dart httpclient response

当我读取互联网上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
});
因此,当我以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的内容,而不是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

关于string - 获取互联网上文​​本文件的内容, flutter 朔迷离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64290967/

相关文章:

c - 读取未知大小的字符串

ios - 如何将变量从 flutter 传递到 native objective-c

java - 我的数组出现空指针异常?

python - 使用 Numpy 或 Pandas 根据字符计数对字符串进行矢量化分割

flutter - 有没有办法在应用程序被杀死或移动到后台之前调用特定代码?

flutter - 允许 GridView 重叠 SliverAppBar

asynchronous - Dart Pirate教程在构建后不下载JSON(第7步)

flutter - 如何根据背景更改文本颜色,以使两种颜色之间具有良好的对比度

dart - 在文本小部件中使用变量

c++ - 检索字符串的第一个字符并在 C++ 中按字母顺序比较它