How do I read the name of a File or a Directory?
There is a property 'path' but that returns the entire file path.
Would be nice to have a property like 'name' that just returns the last part of the path.
In Java there is a method called File.name();
Click the Start button and then click Computer, click to open the location of the desired file, hold down the Shift key and right-click the file. Copy As Path: Click this option to paste the full file path into a document. Properties: Click this option to immediately view the full file path (location).
How to list the contents of a directory in Dart. final dir = Directory('path/to/directory'); final List<FileSystemEntity> entities = await dir. list(). toList();
You can use the path package to do that :
import 'package:path/path.dart' as path;
main() {
path.basename('path/to/foo.dart'); // -> 'foo.dart'
path.basename('path/to'); // -> 'to'
}
See the path package documentation for more explanations.
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';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With