DEV Community

Jhin Lee
Jhin Lee

Posted on

How to screenshot a widget in the flutter

Define a global key

GlobalKey previewContainer = GlobalKey();
Enter fullscreen mode Exit fullscreen mode

Wrap the screenshot area with RepaintBoundary

FittedBox(
    fit: BoxFit.contain,
    child: RepaintBoundary(
        key: previewContainer,
        child: Container( // The widget to capture
            width: 500,
            height: 500,
            color: Colors.blue,
        ),
    ),
)

Enter fullscreen mode Exit fullscreen mode

Screenshot for the widget

Future<Uint8List> _capture() async {
    RenderRepaintBoundary boundary = previewContainer.currentContext
        ?.findRenderObject() as RenderRepaintBoundary;
    final image = await boundary.toImage(pixelRatio: 2);
    final byteData = await image.toByteData(format: ImageByteFormat.png);
    return byteData!.buffer.asUint8List();
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)