作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一些基本代码来加载一些 Sprite 图像,我正在使用 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
最佳答案
我刚刚添加了一些评论为什么它不起作用
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");
});
关于dart - 如何等到图像)在 Dart 中加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25296563/
我是一名优秀的程序员,十分优秀!