Flutter: Get the filename of a File

FilenamesFlutter

Filenames Problem Overview


I thought this would be pretty straight-forward, but can't seem to get this. I have a File file and it has a path file.path which spits out something like /storage/emulated/0/Android/data/my_app/files/Pictures/ca04f332.png but I can't seem to find anything to get just ca04f332.png.

Filenames Solutions


Solution 1 - Filenames

You can use the basename function from the dart path library:

import 'package:path/path.dart';

File file = new File("/dir1/dir2/file.ext");
String basename = basename(file.path);
# file.ext

Solution 2 - Filenames

File file = new File("/storage/emulated/0/Android/data/my_app/files/Pictures/ca04f332.png"); 
String fileName = file.path.split('/').last;
    
print(fileName);

output = ca04f332.png

Solution 3 - Filenames

Since Dart Version 2.6 has been announced and it's available for flutter version 1.12 and higher, You can use extension methods. It will provide a more readable and global solution to this problem.

file_extensions.dart :

import 'dart:io';

extension FileExtention on FileSystemEntity{
  String get name {
    return this?.path?.split("/")?.last;
  }
}

and name getter is added to all the file objects. You can simply just call name on any file.

main() {
  File file = new File("/dev/dart/work/hello/app.dart");
  print(file.name);
}

Read the document for more information.

Note: Since extension is a new feature, it's not fully integrated into IDEs yet and it may not be recognized automatically. You have to import your extension manually wherever you need that. Just make sure the extension file is imported:

import 'package:<your_extention_path>/file_extentions.dart';

Solution 4 - Filenames

Easy way to get name or any other file handling operations.I recommend to use this plugin : https://pub.dev/packages/file_support

main() {
  String filename= FileSupport().getFileNameWithoutExtension(<File Object>);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJus10View Question on Stackoverflow
Solution 1 - FilenamesjspcalView Answer on Stackoverflow
Solution 2 - Filenames0917237View Answer on Stackoverflow
Solution 3 - FilenamesSaman SalehiView Answer on Stackoverflow
Solution 4 - FilenamesParmeet SinghView Answer on Stackoverflow