Flutter: Get the filename of a File

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


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';

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