1

I'm trying to read an image in flutter into a Uint8List but it keeps returning file not found even after ive added the asset path in pubspec file

Future<Uint8List> pick_default_image() async {
  Uint8List img = (await rootBundle.load('assets/logo_oinkgram.png')).buffer.asUint8List();
  return img;
}

pickImage(ImageSource source) async {
  final ImagePicker _imagePicker = ImagePicker();
  XFile? _file = await _imagePicker.pickImage(source: source);

  if (_file != Null) {
    return await _file!.readAsBytes();
  }
}





//The variable
  Future<Uint8List>  _image = pick_default_image();

Here's the code and error i'm getting: Code and error\

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PathNotFoundException: Cannot open file, path = 'assets/logo_oinkgram.png' (OS Error: No such file or directory, errno = 2)

any suggestions on what do I do?

edit:

I've updated the functions but the functions applied on the variable are now of different types Future and Uint8List

1 Answers1

1

You can't directly access asset files using the dart:io library, because assets are bundled with the application and are not part of the device's file system. You should use the rootBundle from package:flutter/services.dart instead to read the asset data.

Modifing your pick_default_image() function like this should work:

Future<Uint8List> pick_default_image() async {
  Uint8List img = (await rootBundle.load('assets/logo_oinkgram.png')).buffer.asUint8List();
  return img;
}

And don't forget to import package:flutter/services.dart.

nibbo
  • 149
  • 1
  • 9
  • This code works but i'm prompted with the error can't assign Future to Uint8List type and i'm using another function which updates the same variable which has a Uint8List return type – WinterSolstice Mar 23 '23 at 08:38
  • Is the other function marked as `async` and are you awaiting the `Future` `pick_default_image()` returns? – nibbo Mar 23 '23 at 08:41
  • yes, i've updated both the functions in the post – WinterSolstice Mar 23 '23 at 08:41