我发现我无法以简单的方式获取文件的名称:(
飞镖码:
File file = new File("/dev/dart/work/hello/app.dart");
Run Code Online (Sandbox Code Playgroud)
如何获取文件名app.dart?
我找不到这个API,所以我做的是:
var path = file.path;
var filename = path.split("/").last;
Run Code Online (Sandbox Code Playgroud)
有没有更简单的解决方案?
Vil*_*mir 56
如果您不想使用路径 pub 包,您可以使用 dart:io 中的 Uri 类,该类返回文件名及其扩展名:
String fileName = File(localFilePath).uri.pathSegments.last;
Run Code Online (Sandbox Code Playgroud)
Ale*_*uin 34
您可以使用路径包:
import 'dart:io';
import 'package:path/path.dart';
main() {
File file = new File("/dev/dart/work/hello/app.dart");
String filename = basename(file.path);
}
Run Code Online (Sandbox Code Playgroud)
Sam*_*ehi 10
由于 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)
截至 2020 年 4 月的作品
void main() {
var completePath = "/dev/dart/work/hello/app.dart";
var fileName = (completePath.split('/').last);
var filePath = completePath.replaceAll("/$fileName", '');
print(fileName);
print(filePath);
}
Run Code Online (Sandbox Code Playgroud)