How to check if Image URL is valid in Flutter?

Validate ImageURL in Flutter

In my blog app build using Flutter, I wanted to provide the user an option to either use a gallery image or put an image URL. That is when I found this issue, as users can be very random. So basically we want to check if the Image URL is valid. And if it returns an image type so that we don’t run into runtime errors.

Error caused when Image URL is valid is not checked in Flutter.
Error caused because of wrong image URL

There can be two cases 📝

  1. User entered wrong URL.
  2. User entered a non-image URL. (eg:

Solution ✅

To counter the first case we can check the statusCode and if it is 200 then the URL is correct and also handles the situation if the device does not have an internet connection. For the second case, we check if the content-type is an image format.

This is the validateImage(String) function, which makes an HTTP get request on the URL provided and checks if the status code is 200, if true we pass the data[‘content-type’] to the checkIfImage(String) function.

 import 'package:http/http.dart' as http;

 Future<bool> validateImage(String imageUrl) async {
    http.Response res;
    try {
      res = await http.get(Uri.parse(imageUrl));
    } catch (e) {
      return false;

    if (res.statusCode != 200) return false;
    Map<String, dynamic> data = res.headers;
    return checkIfImage(data['content-type']);

This is the checkIfImage(String) function. I have added only jpeg, png, and gif support. You can add more image formats easily, you can check the equivalent file strings here.

 bool checkIfImage(String param) {
    if (param == 'image/jpeg' || param == 'image/png' || param == 'image/gif') {
      return true;
    return false;

We can now easily check if the image URL provided by the user is valid and if it returns an image type. Similarly, we can check if the data type received is video, audio, text, etc formats. If you have any queries you can comment below and I will be happy to help you.

You might also be interested in:

If you are new to flutter check my post on how to install flutter on windows?

Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
setup flutter on windows

How to setup Flutter on Windows? – Complete Guide

Next Post
How to Create Collection Within Docs Flutter

Flutter: How to add Sub-Collection in Document? Firebase

Related Posts