Ayush Shekhar
Ayush Shekhar

Reputation: 1563

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

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?

Upvotes: 12

Views: 15432

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657801

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

Upvotes: 31

Related Questions