简体   繁体   English

如何等待直到将图像加载到Dart中

[英]How to wait until image(s) loaded in Dart

I have some basic code to load some sprite images, I am using Future.wait to wait until both images are loaded. 我有一些基本的代码可以加载一些精灵图像,我正在使用Future.wait等到两个图像都加载完毕。 However this still does not what I exactly want to do, Because I want to assign image width and height to members before It exits. 但是,这仍然不是我真正想做的,因为我想在退出之前为成员分配图像的宽度和高度。

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");

The output: 输出:

Returning
Ship Constructor exited
Images loaded. 40 75

I want a way to wait until everything image loading done before exiting the constructor.Is there a good way to do this in Dart? 我想要一种方法,直到所有图像加载完成后再退出构造函数。在Dart中是否有一个很好的方法可以做到这一点?

I just added some comments why it doesn't work 我刚刚添加了一些评论,为什么它不起作用

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");

This way it should work (not tested) 这样就可以正常工作(未经测试)

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");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM