如何等待Dart中加载的图像

时间:2014-08-13 21:35:19

标签: dart dart-async

我有一些基本代码来加载一些精灵图像,我使用Future.wait等到两个图像都被加载。然而,这仍然不是我想要做的,因为我想在它退出之前为成员分配图像宽度和高度。

SpaceShip(this.x, this.y) {
  rocket = new ImageElement(src: "nofire.png");
  firingRockets = new ImageElement(src: "fire.png");
  var futures = [rocket.onLoad.first, firingRockets.onLoad.first];
  Future.wait(futures).then((_) {
    width = rocket.width;
    height = rocket.height;
    print("Images loaded. $width $height");     
  });
  print("Returning");
}
....
ship = new SpaceShip(400.0, 200.0);
print("Ship Constructor exited");

输出:

Returning
Ship Constructor exited
Images loaded. 40 75

我希望有一种方法可以等到所有图像加载完成后再退出构造函数。在Dart中有一个很好的方法吗?

1 个答案:

答案 0 :(得分:1)

我刚刚添加了一些评论,说明为什么它不起作用

SpaceShip(this.x, this.y) {
  rocket = new ImageElement(src: "nofire.png");
  firingRockets = new ImageElement(src: "fire.png");
  var futures = [rocket.onLoad.first, firingRockets.onLoad.first];
  // this call just gets enqueued in the Dart event queue and then the 
  // execution is continued at the next statement
  // the async code is executed only after this thread of execution 
  // has ended
  Future.wait(futures).then((_) {
    width = rocket.width;
    height = rocket.height;
    print("Images loaded. $width $height");     
  });
  // this code doesn't wait for Future.wait to finish
  print("Returning");
}
....
// this code doesn't wait for Future.wait to finish
ship = new SpaceShip(400.0, 200.0);
print("Ship Constructor exited");

这样它应该可以工作(未经测试)

SpaceShip(this.x, this.y);

// I moved this to a method because the constructor can't return a Future
Future load() {
  rocket = new ImageElement(src: "nofire.png");
  firingRockets = new ImageElement(src: "fire.png");
  var futures = [rocket.onLoad.first, firingRockets.onLoad.first]; 
  return Future.wait(futures).then((_) {  // return a Future
    width = rocket.width;
    height = rocket.height;
    print("Images loaded. $width $height");     
  })
  .then(() {
    print("Returning");
  }});
}
....

var ship = new SpaceShip(400.0, 200.0);
// the returned future allows to wait until the async code has finished (using then)
ship.load().then(() {
    print("Ship Constructor exited");
});