Flutter 创建界面组件截图并保存

12 min read
final key = GlobalKey();

...

RepaintBoundary(
  key: key,
  child: Container(
    decoration: BoxDecoration(
      color: Colors.green,
    ),
    height: 200,
    width: 400,
    child: Center(
      child: Text(
        "Hello world!",
        style: TextStyle(
          color: Colors.white,
          fontSize: 24,
        ),
      ),
    ),
  ),
)
  
  
final boundary = key.currentContext?.findRenderObject() as RenderRepaintBoundary?;
final image = await boundary?.toImage();
final byteData = await image?.toByteData(format: ImageByteFormat.png);
final imageBytes = byteData?.buffer.asUint8List();

if (imageBytes != null) {
  final directory = await getApplicationDocumentsDirectory();
  final imagePath = await File('${directory.path}/container_image.png').create();
  await imagePath.writeAsBytes(imageBytes);
}
  • 要把这个小组件转换为图像文件(或捕获/截图),你需要把这个小组件包在一个RepaintBoundary小组件中。

  • 然后你需要创建一个GlobalKey,并将其传递给RepaintBoundary小组件。