Get file extension from file name string
178
You're overthinking this solution here. Just use methods already made for you in the String
class. Since you already have the file name, you can find the last instance of the .
character with the preexisting lastIndexOf
method and get the substring with that index:
String fileName = 'Screenshot_2021-06-10_co.com.app.jpg';
String fileExt = fileName.substring(fileName.lastIndexOf('.'));
Comments
-
alonsso over 1 year
I was trying to get file extension with dart code as this,
var url = downloadUrl.toString(); String fileExtension = ''; String fileName = path.split("\/").last; bool fileExt = false; for (var characterUrl = 0; characterUrl < fileName.length; characterUrl++) { if (String.fromCharCode(fileName.codeUnitAt(characterUrl)) == '.' && !fileExt) { fileExt = true; } if (fileExt) { fileExtension += String.fromCharCode(fileName.codeUnitAt(characterUrl)); } }
When having a file named as:
eg: Screenshot_2021-06-10_co.com.app.jpg
It returns me:
".com.app.jpg"
But I would like just to get the .jpg
In other file names it works perfectly.