2

I'm post a question here before( How to load an image in Dart ) and get answer, but same time get more questions. Why I'm can draw image only this way:

image.on.load.add((e) {
    context.drawImage(image, 0, 0);
});

but if I'm write something like:

ImageElement image = new ImageElement();
image.src = 'myImage.png';
context.drawImage(image, 0, 0);

^^^ this don't work and don't draw image. Why?

bool loaded = false;
ImageElement image = new ImageElement();
image.src = 'myImage.png';
image.on.load.add((e) {
    loaded = true;
});
print(loaded); // on console get - false

^^^ why I'm get false? I'm created if image loaded variable loaded become true, but loaded don't become true.

Sorry for my bad English language. Thanks!

Community
  • 1
  • 1
narahd
  • 103
  • 2
  • 4

2 Answers2

6

As for your first question, if you leave out

image.onLoad.listen((e) {
    context.drawImage(image, 0, 0);
});

then no code will be executed when the image is loaded.

The on.load.add(...) construction basically assigns a function (often referred to as a handler) that will be executed when the browser loads the image. If no such function is assigned then nothing happens when the image is loaded and consequently context.drawImage(image, 0, 0) will not work.

Your second questions is related to this function. Loading an image is an asynchronous process, meaning your on load handler (on.load.add(...)) is first fired when the client has successfully loaded the image. This means that after assininging your on load handler execution continues to your next call: print(loaded) which will be false as the image is not loaded yet.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Lars Tackmann
  • 20,275
  • 13
  • 66
  • 83
5

Newer image onload syntax:

readFile() {
  ImageElement image = new ImageElement(src: "plant.png");
  document.body.nodes.add(image);
  image.onLoad.listen(
      onData, 
      onError: onError, 
      onDone: onDone, 
      cancelOnError: true
   );
}

onData(Event e) {
  print("success");
}

onError(Event e) {
  print("error: $e");
}

onDone() {
  print("done");
}
Tom Auger
  • 19,421
  • 22
  • 81
  • 104
Brandon
  • 2,034
  • 20
  • 25