DEV Community

Jhin Lee
Jhin Lee

Posted on

2 1

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

Sentry blog image

The countdown to March 31 is on.

Make the switch from app center suck less with Sentry.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs