Creating raw image from Widget or Canvas

There is support for this now. You can either use RenderRepaintBoundry or OffsetLayer or Scene. They all have a toImage. Here is the link to RenderRepaintBoundry.toImage()

class PngHome extends StatefulWidget {
  const PngHome({super.key});

  @override
  PngHomeState createState() => PngHomeState();
}

class PngHomeState extends State<PngHome> {
  GlobalKey globalKey = GlobalKey();

  Future<void> _capturePng() async {
    RenderRepaintBoundary boundary = globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    ui.Image image = await boundary.toImage();
    ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List pngBytes = byteData!.buffer.asUint8List();
    print(pngBytes);
  }

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      key: globalKey,
      child: Center(
        child: TextButton(
          onPressed: _capturePng,
          child: const Text('Take screenshot', textDirection: TextDirection.ltr),
        ),
      ),
    );
  }
}

This is copied from the docs and adapted to latest null safety and dart language features. The values for globalKey.currentContext and byteData can be null, so your production code should ideally check them.


This is not currently possible from Dart code running in a FlutterView today, however we have a bug on file tracking implementing such: https://github.com/flutter/flutter/issues/6774

It is possible to render Flutter widgets as part of a FlutterView and then use Java or Objective-C interfaces onto the FlutterView to capture a picture, such as the standard android.View.getBitmap which FlutterView implements: https://docs.flutter.io/javadoc/io/flutter/view/FlutterView.html#getBitmap--

If this important to your application needs and would like to be able to capture Bitmaps of Widget trees from inside Dart code we'd love to hear about it. Please feel encouraged to provide further context on the above referenced issue!

Tags:

Flutter