我认为这很简单,但似乎无法得到这个.我有一个File file,它有一个file.path吐出类似的路径,/storage/emulated/0/Android/data/my_app/files/Pictures/ca04f332.png但我似乎无法找到任何东西得到公正ca04f332.png.
091*_*237 40
File file = new File("/storage/emulated/0/Android/data/my_app/files/Pictures/ca04f332.png");
String fileName = file.path.split('/').last;
print(fileName);
Run Code Online (Sandbox Code Playgroud)
输出 = ca04f332.png
jsp*_*cal 27
File file = new File("/dir1/dir2/file.ext");
String basename = basename(file.path);
# file.ext
Run Code Online (Sandbox Code Playgroud)
File file = File('/foo/bar/baz/my_image.jpg');
String fileName = file.path.split(Platform.pathSeparator).last; // my_image.jpg
Run Code Online (Sandbox Code Playgroud)
1. 创建扩展:
extension FileEx on File {
String get name => path.split(Platform.pathSeparator).last;
}
Run Code Online (Sandbox Code Playgroud)
2. 使用方法:
File file = File('/foo/bar/baz/my_image.jpg');
String fileName = file.name; // my_image.jpg
Run Code Online (Sandbox Code Playgroud)
由于 Dart 版本2.6已经发布并且它可用于 flutter 版本1.12及更高版本,您可以使用extension方法。它将为这个问题提供一个更具可读性和全局性的解决方案。
file_extensions.dart :
import 'dart:io';
extension FileExtention on FileSystemEntity{
String get name {
return this?.path?.split("/")?.last;
}
}
Run Code Online (Sandbox Code Playgroud)
并将namegetter 添加到所有文件对象中。您可以简单地调用name任何文件。
main() {
File file = new File("/dev/dart/work/hello/app.dart");
print(file.name);
}
Run Code Online (Sandbox Code Playgroud)
阅读文档了解更多信息。
注意:
由于extension是一项新功能,因此尚未完全集成到 IDE 中,并且可能无法自动识别。您必须extension在需要的任何地方手动导入。只需确保导入扩展文件:
import 'package:<your_extention_path>/file_extentions.dart';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6596 次 |
| 最近记录: |