Programming Flutter: Image.toByteData() does not exist (page40)

your book suggests to use Image.toByteData() to convert image to bytes, however I get the following error: "the getter ‘toByteData’ isn’t defined for the type ‘Image’. "

I tried importing the dart:typed_data package, but seems that this method does not exist. Can you please explain how to access it? It would be very useful for my app.

i think I answered my own question by importing dart:ui library, but I am not able to get it to work with the Image widget. Hope you can clarify the proper usage of Image.toByteData() when used with Image widget.

Below is the code that is throwing an exception “Unhandled Exception: type ‘Image’ is not a subtype of type ‘Image’ in type cast where
E/flutter (10879): Image is from package:flutter/src/widgets/image.dart
E/flutter (10879): Image is from dart:ui”

import ‘dart:io’ as io;
import ‘dart:ui’ as ui;
import ‘package:flutter/widgets.dart’ as widgets;
import ‘package:get/get.dart’;
import ‘package:image_picker/image_picker.dart’;

class ImageController extends GetxController {
var image = io.File(’’).obs;
final picker = ImagePicker();
var pickedFile;
var imageBytes;

void getImage(imageSource) async {
pickedFile = await picker.getImage(source: imageSource);
if (pickedFile != null) {
image.value = io.File(pickedFile.path);
} else {
print(‘No image selected.’);
}
}

void convertImageToBytes() async {
if (image.value != null) {
ui.Image _image = widgets.Image.file(image.value) as ui.Image;
imageBytes.value = await _image.toByteData();
}
}
}

I’m terribly sorry for being so late to answer, but I wasn’t 100% aware of how DevTalk worked and I wasn’t getting notified of new posts, but now it should never happen again.

Anyway, you’re confusing the dart:ui’s Image class with the Image widget, on page 253 there is a little section about using ui.Image with a link to the page of the official reference about it, which tells you how to get an ui.Image object, in that code you’re just getting an Image widget and trying to cast it to an ui.Image object, when instead you should follow the instructions in the book (and in the official reference).

What you’re actually trying to do seems to me to have nothing to do with the Image object, as you can get the bytes for the image by running readAsBytes on the io.File directly.

Hope this answers your question, feel free to reply back and, again, I’m really sorry for being very late.

1 Like