I have recently migrated my app to Flutter 2 with null safety and I encountered weird error. I have following function which I use to convert CameraImage (YUV) into RGB image, which worked flawlessly before going from Flutter 1.26 to 2.3 and migrating. Afterwards, it started to complain about RangeError (index): Index out of range, which I do not understand and error description is not helpful.
static imageLib.Image convertYUV420ToImage(CameraImage cameraImage) {
final int width = cameraImage.width;
final int height = cameraImage.height;
final int uvRowStride = cameraImage.planes[1].bytesPerRow;
final int? uvPixelStride = cameraImage.planes[1].bytesPerPixel;
final image = imageLib.Image(width, height);
for (int w = 0; w < width; w++) {
for (int h = 0; h < height; h++) {
final int uvIndex =
uvPixelStride! * (w / 2).floor() + uvRowStride * (h / 2).floor();
final int index = h * width + w;
print("index $index and $uvIndex");
final y = cameraImage.planes[0].bytes[index];
final u = cameraImage.planes[1].bytes[uvIndex];
final v = cameraImage.planes[2].bytes[uvIndex];
image.data[index] = ImageUtils.yuv2rgb(y, u, v);
}
}
return image;
}
Output is
...
I/flutter (19516): index 344169 and 172088
I/flutter (19516): index 344889 and 172088
I/flutter (19516): index 10 and 10
E/flutter (19516): [ERROR:flutter/runtime/dart_isolate.cc(1138)] Unhandled exception:
E/flutter (19516): RangeError (index): Index out of range: index should be less than 345600: 10
E/flutter (19516): #0 _Uint8ArrayView.[] (dart:typed_data-patch/typed_data_patch.dart:4070:7)
E/flutter (19516): #1 ImageUtils.convertYUV420ToImage (package:anh_flutter/recognition/ImageUtils.dart:42:46)
E/flutter (19516): #2 ImageUtils.convertCameraImage (package:anh_flutter/recognition/ImageUtils.dart:13:14)
E/flutter (19516): #3 IsolateUtils.entryPoint (package:anh_flutter/recognition/IsolateUtils.dart:47:30)
Which hardly makes any sense as 10 is less than 345600. I also checked that cameraImage.planes[0].bytes.length is indeed 345600 as expected.
Pls could anyone help me understanding what might be wrong here?