简体   繁体   English

无法在 Flutter 中加载资产

[英]Unable to load asset in Flutter

I'm sharing a picture that I've taken previously with the camera using image_picker .我正在分享我之前使用image_picker用相机拍摄的image_picker It works fine on the emulator but not on my device:它在模拟器上运行良好,但在我的设备上运行不正常:

onPressed: () async {
  ByteData image = await rootBundle.load(team.avatar.path);
  ...
},

This is the error with the path:这是路径的错误:

Unable to load asset: /storage/emulated/0/Android/data/drodriguez.apps.Words/files/Pictures/scaled_2eccad3d-382e-462e-b124-b8fa06a2a32b791445736175256137.jpg无法加载资源:/storage/emulated/0/Android/data/drodriguez.apps.Words/files/Pictures/scaled_2eccad3d-382e-462e-b124-b8fa06a2a32b791445736175256137.jpg

The image is being shown without errors so the path is 100% correct:图像显示没有错误,所以路径是 100% 正确的:

Image.file(
  _orderedTeams[index].avatar,
  fit: BoxFit.cover,
  height: 92.0,
  width: 92.0,
)

Do I need to add something else maybe on the pubspec.yml ?我是否需要在pubspec.yml上添加其他pubspec.yml

You can't use the rootBundle to access files on the phone.您不能使用rootBundle访问手机上的文件。 The rootBundle (as said in its docs ) only works for files packaged with the application when was built (probably saved on assets, declared on pubspec, etc). rootBundle(如其文档中所述)仅适用于构建时与应用程序一起打包的文件(可能保存在资产上,在 pubspec 上声明等)。

If you want to load an image from the phone, this maybe help.如果您想从手机加载图像, 可能会有所帮助。


ANSWER回答

This function can read a filePath and return a Uint8List (a byteArray):这个函数可以读取一个文件路径并返回一个 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;
}

And, to get a ByteData just:而且,要获得ByteData只是:

var path = 'Some path to an image';
var byteArray = _readFileByte(path);
ByteData data = ByteData.view(byteArray.buffer);

(The answer is based on this ) (答案基于

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM