寻找 Flutter 的 .toImage() 方法的同步替代方法

Looking for a synchronous alternative to Flutter's .toImage() method

目前我正在试验 Flutter 和 Flame 游戏引擎。 为此,我扩展了 Flame 的 BaseGame class 并在其构造函数中进行了一些繁重的处理。 繁重的处理包括将其他图像组合成一个图像,并最终将其绘制到一个临时 Canvas 上,并将结果存储在一个 Picture 对象中。

ui.PictureRecorder rec = new ui.PictureRecorder();
Canvas tempCanvas = new Canvas(rec, bgRect);
// left out picture operations
ui.Picture pic = rec.endRecording();

为了最终获得一个 Image 对象,我需要调用异步 .toData() 方法,其中 returns 一个 Future。 我将调用包装在异步方法 getImage()

getImage(ui.Picture pic, Rect bgRect) async {
    background = await pic.toImage(bgRect.width.toInt(), bgRect.height.toInt());
    done = true;
}

(background 是 Image 类型的 class 变量,在 BaseGame class 的 render() 方法中使用 class)

问题是,因为它是异步的,所以我在游戏构造函数中的其余语句得到执行,并且在它完成后,render() 方法会触发,但 background 可能不可用然而。 为了解决这个问题,我添加了一个布尔类型的 class 变量 done,它在 getImage() 方法中被设置为 true。 现在我修改了 render() 以等待 done 为真。

void render(Canvas canvas) {
    if (done) {
        canvas.drawImage(background, new Offset(0.0, 0.0), new Paint());
    }
}

当然这并不优雅。 有没有办法在扩展的 BaseGame class 的构造函数中等待 .toImage() 方法完成? 我尝试使构造函数异步,如:

class TheGame extends BaseGame {
    Image background;
    bool done = false;

    TheGame(DeviceOrientation orientation) async {  
    }
}

但这给了我错误:

The modifier 'async' can't be applied to the body of a constructor

我还能做些什么 'synchronous'?

如果你真的需要第一帧渲染之前的图像,你可以只创建一个静态方法来负责创建TheGame

class TheGame extends BaseGame {
    final Image background;

    TheGame._(DeviceOrientation orientation, this.background);

    static Future<TheGame> create(DeviceOrientation orientation) async {
      return TheGame._(orientation, await generateImage());
    }
}

但我认为如果您在没有背景图像的情况下渲染几帧并没有什么坏处,那么我建议您只需检查 background != null 而不是 done 属性 ,感觉有点多余。