Search code examples
stringflutterdarthttpclientresponse

get content of a text file on internet, flutter


when i read the content of a text file that exist on an url on the internet , it's work just inside the function.

this is my function

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

so when i print the content of this file

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

the result will be

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

but as you can see in my function i gave the value of the content to x Field

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

so when i call the Function in initsstate and then print the x , the value will be 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();
  }

so i need to give other Field or Property the Content of the response , or i want to let my Function to return a String not a Future and this String will be really the content of The Response as a String and it's not a null .

thanks in advance


Solution

  • try this,

      @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
      }
    

    use a FutureBuilder if you want to use the response in a widget