Sup*_*ive 7 dart dart-packages
我正在编写一个 Dart 包(不是 Flutter)。我已将一些位图图像作为公共资产,例如lib/assets/empty.png. 当此包作为最终用户的命令行应用程序运行时,如何获取用户系统上这些资产的文件路径?
用例:我的 Dart 包调用 FFMPEG,我需要告诉 FFMPEG 在使用我的包的系统上哪里可以找到这些资源文件。例如,对 FFMPEG 的调用可能如下所示:
ffmpeg -i "path/to/lib/assets/empty.png" ...
Run Code Online (Sandbox Code Playgroud)
访问 Dart 包的资源可以通过两种方式进行:
dart工具运行 Dart CLI 应用程序并访问依赖项的资产,或者这两种情况之间的区别在于,当您使用该dart工具运行 CLI 应用程序时,所有依赖项都可以作为系统上本地缓存中的结构化包提供。但是,当您运行可执行文件时,所有相关代码都会编译为单个二进制文件,这意味着您在运行时不再有权访问依赖项的包,您只能访问依赖项的树摇动的编译代码。
dart以下代码将包资产 URI 解析为文件系统路径。
final packageUri = Uri.parse('package:your_package/your/asset/path/some_file.whatever');
final future = Isolate.resolvePackageUri(packageUri);
// waitFor is strongly discouraged in general, but it is accepted as the
// only reasonable way to load package assets outside of Flutter.
// ignore: deprecated_member_use
final absoluteUri = waitFor(future, timeout: const Duration(seconds: 5));
final file = File.fromUri(absoluteUri);
if (file.existsSync()) {
return file.path;
}
Run Code Online (Sandbox Code Playgroud)
此解析代码改编自 Tim Sneath 的winmd包:https ://github.com/timsneath/winmd/blob/main/lib/src/metadatastore.dart#L84-L106
将客户端应用程序编译为可执行文件时,该客户端应用程序根本无法访问与依赖包一起存储的任何资产文件。然而,有一种解决方法可能对某些人有用(对我来说确实如此)。您可以将资源的 Base64 编码版本存储在包内的 Dart 代码中。
首先,将每个资产编码为 Base64 字符串,并将这些字符串存储在 Dart 代码中的某个位置。
const myAsset = "iVBORw0KGgoAAA....kJggg==";
Run Code Online (Sandbox Code Playgroud)
然后,在运行时,将字符串解码回字节,然后将这些字节写入本地文件系统上的新文件。这是我在我的案例中使用的方法:
/// Writes this asset to a new file on the host's file system.
///
/// The file is written to [destinationDirectory], or the current
/// working directory, if no destination is provided.
String inflateToLocalFile([Directory? destinationDirectory]) {
final directory = destinationDirectory ?? Directory.current;
final file = File(directory.path + Platform.pathSeparator + fileName);
file.createSync(recursive: true);
final decodedBytes = base64Decode(base64encoded);
file.writeAsBytesSync(decodedBytes);
return file.path;
}
Run Code Online (Sandbox Code Playgroud)
这种方法是由@passsy建议的
| 归档时间: |
|
| 查看次数: |
1418 次 |
| 最近记录: |