captureWidget static method

Future<Uint8List> captureWidget(
  1. GlobalKey<State<StatefulWidget>> key
)

截取小部件的图片

Implementation

static Future<Uint8List> captureWidget(GlobalKey key) async {
  try {
    // 获取 RenderRepaintBoundary 对象
    final boundary =
        key.currentContext?.findRenderObject() as RenderRepaintBoundary;

    // 渲染并转换为 Uint8List 数据
    final image = await boundary.toImage();
    final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    return byteData?.buffer.asUint8List() ?? Uint8List(0);
  } catch (e) {
    // 处理异常情况
    debugPrint('Error capturing widget: $e');
    return Uint8List(0);
  }
}