Find File extension from File path in Flutter

Aug 27, 2021 . 2 min Muhammed Mukhthar CM Cover Image

The chances are high that we had to find out the extension of a File. My use case was when I was trying to pick an image from the gallery and save it to Firebase Storage.

In this post, I will show you the simplest way to find out a file’s extension in Flutter.

Flutter has an inbuilt library called path. We can use it to find out the extension easily.

Import lib

First, we need to import the library to our File. This is the recommended way to import the package.

import 'package:path/path.dart' as p;

Find Extension

Let’s assume the myImage is an Image File. We don’t know its extension, it may be png or jpeg` or whatever else.

To find out its extension, we have to pass the File’s path to the extension function in the path library.

File myImage;
String fileExtension = p.extension(myImage.path);

Find Extension with multiple levels

What if our file name is like main.dart.js? (this is the file name of a js file when we build flutter for web)

We can pass an optional level parameter to the extension function.

File myFile = File("/some/path/and/another/dir/main.dart.js");
String fileExtension = p.extension(myFile.path,2);

This will give us .dart.js

Examples

printFileExtension(){
  File myImage = File("/some/doomed/path/on/file/system/myImage.jpeg");
  String fileExtension = p.extension(myImage.path);
  print(fileExtension); // ".jpeg"
}

The above function will print .jpeg

printFileExtension(){
  File myImage = File("/some/doomed/path/on/file/system/myImage.png");
  String fileExtension = p.extension(myImage.path);
  print(fileExtension); // ".png"
}

The above function will print .png

printFileExtension(){
  File myFile = File("/some/path/and/another/dir/main.dart.js");
  String fileExtension = p.extension(myFile.path,2);
  print(fileExtension); // ".dart.js"
}

The above function will print .dart.js

Wrap

Hope you found something useful here.

I’m always open to suggestions!

Let me know your suggestions and opinions on Twitter DM or drop a mail a [email protected].

You can subscribe to my Newsletter to get notified about my new posts!

Finally, if you found this helpful, please share this within your reach so that more people can benefit from this. And Follow me on Twitter for getting more posts like these 😉.