无法在 Flutter 中加载资产
Unable to load asset in Flutter
我正在分享一张我之前用 image_picker
相机拍摄的照片。它在模拟器上运行良好,但在我的设备上运行不正常:
onPressed: () async {
ByteData image = await rootBundle.load(team.avatar.path);
...
},
这是路径错误:
Unable to load asset:
/storage/emulated/0/Android/data/drodriguez.apps.Words/files/Pictures/scaled_2eccad3d-382e-462e-b124-b8fa06a2a32b791445736175256137.jpg
显示的图像没有错误,因此路径 100% 正确:
Image.file(
_orderedTeams[index].avatar,
fit: BoxFit.cover,
height: 92.0,
width: 92.0,
)
我是否需要在 pubspec.yml
上添加其他内容?
您不能使用 rootBundle
访问 phone 上的文件。 rootBundle(如其 docs 中所述)仅适用于构建时随应用程序打包的文件(可能保存在资产上,在 pubspec 上声明等)。
如果您想从 phone 加载图像,this 可能会有所帮助。
回答
这个函数可以读取一个filePath和return一个Uint8List(一个byteArray):
Future<Uint8List> _readFileByte(String filePath) async {
Uri myUri = Uri.parse(filePath);
File audioFile = new File.fromUri(myUri);
Uint8List bytes;
await audioFile.readAsBytes().then((value) {
bytes = Uint8List.fromList(value);
print('reading of bytes is completed');
}).catchError((onError) {
print('Exception Error while reading audio from path:' +
onError.toString());
});
return bytes;
}
并且,要获得 ByteData
只需:
var path = 'Some path to an image';
var byteArray = _readFileByte(path);
ByteData data = ByteData.view(byteArray.buffer);
(答案基于)
我正在分享一张我之前用 image_picker
相机拍摄的照片。它在模拟器上运行良好,但在我的设备上运行不正常:
onPressed: () async {
ByteData image = await rootBundle.load(team.avatar.path);
...
},
这是路径错误:
Unable to load asset: /storage/emulated/0/Android/data/drodriguez.apps.Words/files/Pictures/scaled_2eccad3d-382e-462e-b124-b8fa06a2a32b791445736175256137.jpg
显示的图像没有错误,因此路径 100% 正确:
Image.file(
_orderedTeams[index].avatar,
fit: BoxFit.cover,
height: 92.0,
width: 92.0,
)
我是否需要在 pubspec.yml
上添加其他内容?
您不能使用 rootBundle
访问 phone 上的文件。 rootBundle(如其 docs 中所述)仅适用于构建时随应用程序打包的文件(可能保存在资产上,在 pubspec 上声明等)。
如果您想从 phone 加载图像,this 可能会有所帮助。
回答
这个函数可以读取一个filePath和return一个Uint8List(一个byteArray):
Future<Uint8List> _readFileByte(String filePath) async {
Uri myUri = Uri.parse(filePath);
File audioFile = new File.fromUri(myUri);
Uint8List bytes;
await audioFile.readAsBytes().then((value) {
bytes = Uint8List.fromList(value);
print('reading of bytes is completed');
}).catchError((onError) {
print('Exception Error while reading audio from path:' +
onError.toString());
});
return bytes;
}
并且,要获得 ByteData
只需:
var path = 'Some path to an image';
var byteArray = _readFileByte(path);
ByteData data = ByteData.view(byteArray.buffer);
(答案基于