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.

There can be two cases 📝
- User entered wrong URL.
- User entered a non-image URL. (eg: www.google.com)
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:
- Complete Guide to ValueNotifier in Flutter
- Null Safety in Dart, Flutter Essentials
- Complete Guide to Futures and Future Builder in Flutter
- Create Custom Snippets in Flutter
- What are Streams, Flutter Essesentials
- Complete Guide to StreamBuilder in Flutter
If you are new to flutter check my post on how to install flutter on windows?