Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out the validity of a URL in Flutter?

Tags:

flutter

dart

I don't know of the title is completely appropriate, but here's what I actually want to do. I have urls which point to mp3 files, now some are valid and and some are not, as of now, so before I render the controls for playback of those audio files in my UI, I want to check whether the URL will give me the mp3 or result in a 404. How can I do that?

like image 414
Ayush Shekhar Avatar asked Jan 06 '19 13:01

Ayush Shekhar


Video Answer


1 Answers

Make an HTTP request and check the response code

final response =
  await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));

if (response.statusCode == 200) {

See https://flutter.io/docs/cookbook/networking/fetch-data for more details.

A HEAD request will be more efficient though when you only want to check if the URL is valid because it doesn't actually download content.

final response =
  await http.head(Uri.parse('https://jsonplaceholder.typicode.com/posts/1'));

if (response.statusCode == 200) {

See also https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/HEAD

like image 103
Günter Zöchbauer Avatar answered Oct 17 '22 09:10

Günter Zöchbauer