flutterimageuint8list

Cannot convert DataBytes to UInt8LIst for img.decodePng() method


This works fine:

var imgBytes = await rootBundle.load('packages/gm_firebase/images/cards/card_template.png');

This gives me the error "type '_UnmodifiableByteDataView' is not a subtype of type 'Uint8List' in type cast"

var imgBytes = await rootBundle.load('packages/gm_firebase/images/cards/card_template.png');
final image1 = img.decodePng(imgBytes as Uint8List);

Is there a better way for me to read the file? I'm also reading an image2 and then merging them both using the image class and writing the result to a file.


Solution

  • An as cast in Dart does not do conversions. as just tells the compiler to treat an object as a different type. It does not create any new objects. If the object is not actually that type, then a typecast will do not work. Since image.decodePng requires a Uint8List and AssetBundle.load returns a Future<ByteData>, you will need to create a Uint8List from a ByteData object.

    It's not that obvious from the Uint8List and ByteData documentation how to convert between them, but both of them refer to a ByteBuffer class, so that can be used to bridge the types:

    var imgBytes = await rootBundle.load('packages/gm_firebase/images/cards/card_template.png');
    final image1 = img.decodePng(imgBytes.buffer.asUint8List());