【发布时间】:2020-11-18 02:39:33
【问题描述】:
我有一个想要保存到 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 = byteData.buffer.asUint8List();
// SHARING IMAGE TO SOCIAL MEDIA
// CODE
// widget is presented with a dialog so I just pop it
Navigator.of(context).pop();
} catch (_) {
await Future.delayed(const Duration(milliseconds: 5));
return _capturePng();
}
}
@override
void afterFirstLayout(BuildContext context) {
_capturePng();
}
@override
Widget build(BuildContext context) {
return RepaintBoundary(
key: globalKey,
child: SuperFancyWidget(),
);
}
}
afterFirstLayout 来自https://pub.dev/packages/after_layout 包
【问题讨论】: