如何在Flutter中获取资产的文件路径? [英] How do I get the Asset's file path in flutter?
问题描述
这是我的pubspec.yaml:
Here is my pubspec.yaml:
assets:
- assets/mySecertImage.png
这是我读回资产的方式:
Here is how I read back the assets:
var data = await PlatformAssetBundle().load('assets/mySecertImage.png');
我可以直接获取文件路径吗?如果无法这样做,是否可以将 data
更改为 File
对象?谢谢。
Instead of reading it directly, can I get the file path instead? If it is not possible to do so, it is possible to change the data
to become a File
object? Thanks.
推荐答案
您找到解决方案了吗? (我也在寻找相同的东西。)
Have you found a solution ? (I am looking for the same as well).
这里是我追求的一种解决方法(由于缺乏更好的主意)...:
Here is a workaround that I pursue (out of lack of a better idea)... :
我这样做:
- 为文档目录$ b $创建新的文件路径b(在下面的代码示例中命名为app.txt)
- 将资产文件夹中的文件复制到此
文档目录位置 - 从现在开始使用复制的文件(如果需要,您现在可以使用文件路径,甚至还有字节内容)
这是Dart代码:
import 'package:path/path.dart';
Directory directory = await getApplicationDocumentsDirectory();
var dbPath = join(directory.path, "app.txt");
ByteData data = await rootBundle.load("assets/demo.txt");
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await File(dbPath).writeAsBytes(bytes);
某些人还使用 getDatabasesPath()
,而不是 getApplicationDocumentsDirectory()
。但是我发现在iOS模拟器上,这最终是完全相同的位置。 (未在Android上验证)...因此,它会说:
Some people also work with the getDatabasesPath()
instead of getApplicationDocumentsDirectory()
. But I figured that on an iOS-Simulator this ends up being the exact same location. (not verified on Android)... So, it would say:
var dbDir = await getDatabasesPath();
var dbPath = join(dbDir, "app.txt");
ByteData data = await rootBundle.load("assets/demo.txt");
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await File(dbPath).writeAsBytes(bytes);
对于iOS模拟器:在上述两个示例中,您都可以在以下文件夹中找到复制的文件:
For an iOS-Simulator: In both above examples, you can find your copied file under the folder:
/ Users / username / Library / Developer / CoreSimulator / Devices / AE5C3275-CD65-3537-9B32-53533B97477C / data / Containers / Data / Application / 7BE2B2EE-4E45-3783-B4BD-341DA83C43BD / Documents / app.txt
(当然,您的UUID有所不同...)
(of course, the UUID's being different in your case...)
如果只想复制不存在的文件,则可以这样写:
And if you want to copy the file only if it does not exist already, you could write:
Directory directory = await getApplicationDocumentsDirectory();
var dbPath = join(directory.path, "app.txt");
if (FileSystemEntity.typeSync(dbPath) == FileSystemEntityType.notFound) {
ByteData data = await rootBundle.load("assets/demo.txt");
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await File(dbPath).writeAsBytes(bytes);
}
这篇关于如何在Flutter中获取资产的文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!