We have FileSystemEntity.path, but it would be nice to have a FileSystemEntity.name as well. I've often wanted to do a File.name or Directory.name, and have had to import and use package:path instead.
I came here to add the exact same request. It gets ugly when trying to do something which is very common and should be simple e.g.
if (type == FileSystemEntityType.FILE) {
Uri uri = entity.uri;
files.add(uri.pathSegments[uri.pathSegments.length-1]);
}
if (type == FileSystemEntityType.DIRECTORY) {
Uri uri = entity.uri;
files.add(uri.pathSegments[uri.pathSegments.length-2]);
}
Hey there :)
With the power of dart extensions and the comment from @Rockvole i wrote something:
extension FileExtension on FileSystemEntity {
String get name {
var stat = statSync();
if(stat.type == FileSystemEntityType.file){
return uri.pathSegments.elementAt(uri.pathSegments.length - 1);
} else if(stat.type == FileSystemEntityType.directory){
return uri.pathSegments.elementAt(uri.pathSegments.length - 2);
}
else {
return 'Could not be resolved';
}
}
}
Just paste this snippet somwhere in your code and you'll be able to call .name on a FileSystemEntity.
I will write some more extension, if you're interested just leave a comment.
(Currently in my mind --> fast checking if the Entity is a directory or a file)
Most helpful comment
Hey there :)
With the power of dart extensions and the comment from @Rockvole i wrote something:
Just paste this snippet somwhere in your code and you'll be able to call .name on a FileSystemEntity.
I will write some more extension, if you're interested just leave a comment.
(Currently in my mind --> fast checking if the Entity is a directory or a file)