简体   繁体   中英

Unable to load asset in Flutter

I'm sharing a picture that I've taken previously with the camera using 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

The image is being shown without errors so the path is 100% correct:

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 ?

You can't use the rootBundle to access files on the phone. 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).

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):

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:

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

(The answer is based on this )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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