我有一个自定义小部件,我想将其保存为 png 图像。我面临的问题是,在当前的实现中,我需要在屏幕上显示小部件。我想要的是将小部件直接保存到图像中而不显示它。
作为解决方法,我会在图像在屏幕上呈现时第一时间保存图像,然后快速将其关闭。
这就是我现在保存小部件的方式:
class SomeWidget extends StatefulWidget {
const SomeWidget({
Key key,
}) : super(key: key);
@override
_ShareCocktailMockState createState() => _ShareCocktailMockState();
}
class _SomeWidgetState extends State<SomeWidget>
with AfterLayoutMixin<SomeWidget> {
GlobalKey globalKey = GlobalKey();
Future<void> _capturePng() async {
RenderRepaintBoundary boundary =
globalKey.currentContext.findRenderObject();
try {
if (boundary.debugNeedsPaint) {
print("Waiting for boundary to be painted.");
await Future.delayed(const Duration(milliseconds: 5));
return _capturePng();
}
} catch (_) {}
try {
ui.Image image = await boundary.toImage();
ByteData byteData =
await image.toByteData(format: ui.ImageByteFormat.png);
Uint8List pngBytes …Run Code Online (Sandbox Code Playgroud)