【问题标题】:Unable to load asset in Flutter无法在 Flutter 中加载资产
【发布时间】:2020-04-26 02:49:16
【问题描述】:

我正在分享一张我之前使用image_picker 使用相机拍摄的照片。它在模拟器上运行良好,但在我的设备上却不行:

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

这是路径错误:

无法加载资产: /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 上添加其他内容?

【问题讨论】:

  • 你的加载方法是否在开头插入/?如果是这样,您的初始路径将是根路径,这很有意义
  • 是的,它显示/storage

标签: flutter flutter-dependencies


【解决方案1】:

您不能使用rootBundle 访问手机上的文件。 rootBundle(如其docs 所述)仅适用于在构建时与应用程序一起打包的文件(可能保存在资产上,在 pubspec 上声明等)。

如果您想从手机加载图片,this 可能会有所帮助。


回答

这个函数可以读取一个filePath并返回一个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);

(答案基于this

【讨论】:

  • 感谢您的澄清。我不想加载图像,那已经可以了。我要分享它
  • 您想要将手机上的图像(比如说,相机拍摄的照片)转换为ByteData
  • 这个答案here(不被接受)就是你想要的。从路径中读取图像并返回一个字节数组。 (之后您可以使用ByteData data = ByteData.view(byteArray.buffer); 将字节数组转换为ByteData
  • 哇,效果很好。随意将其添加到不同的答案中,我会批准它为有效答案。非常感谢!
猜你喜欢
  • 2020-04-28
  • 2021-05-10
  • 2020-04-11
  • 2020-10-12
  • 1970-01-01
  • 1970-01-01
  • 2021-01-17
  • 2021-10-14
  • 2020-12-19
相关资源
最近更新 更多