Flutter: Is the file an image or not?

4.7k views Asked by At

I want to load all the images that are in a given directory and exclude all files that are not images.

I don't want to simply check for extensions because different conventions exist like ".jpg" and "jpeg" and because I don't want to manually add new extensions if Flutter supports more image formats in the future. Also I want the user to be able to load image files even if they don't have the correct extension-name.

How can I detect if a file is a (supported) image or not?

When Flutter tries to display a non-image file in the Image widget, it prints this error in the console: "Another exception was thrown: Exception: Invalid image data". Unfortunatly this error seems to be only thown when Flutter is already building the widget, so trying to detect non-images during loading like this:

  void getFiles(path) async {
    //asyn function to get list of files
    var currentDir = Directory(path);

    files = [];

    await for (var entity
        in currentDir.list(recursive: false, followLinks: false)) {
      if (entity is File) {
        try {
          var image = Image(image: FileImage(entity));
          files.add(entity.path);
        } catch (e) {
          print(e);
        }
      }
    }
  }

dosn't work.

The target plattform for the app is desktop, that is why I am not simply accessing the gallery.

0

There are 0 answers