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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more