1

いくつかのスプライト画像をロードするための基本的なコードがいくつかあります。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でこれを行う良い方法はありますか?

4

1 に答える 1

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");
});
于 2014-08-14T04:27:24.067 に答える