widget2image static method

Future<ByteData?> widget2image(
  1. GlobalKey<State<StatefulWidget>> key, {
  2. ImageByteFormat format = ImageByteFormat.png,
})

key所在节点必须是RepaintBoundary节点,否则会报错,截取 RenderRepaintBoundary 的内容

Implementation

static Future<ByteData?> widget2image(GlobalKey key, {ImageByteFormat format = ImageByteFormat.png}) async {
  if(key.currentContext==null) return null;
  double dpr = View.of(key.currentContext!).devicePixelRatio; // 获取当前设备的像素比
  RenderRepaintBoundary boundary = (key).currentContext!.findRenderObject() as RenderRepaintBoundary;
  var image = await boundary.toImage(pixelRatio: dpr);
  return await (image.toByteData(format: format));
}