Flutter : How to save widget to png with transparent background?

Viewed 1157

There is the way to save the widget into transparent png and save it into gallery? Thanks in advance.

1 Answers

Flutter draws every single pixel, so you can easily convert your widget to an image.

You need to follow these steps:

Edit -- first import path_provider link to pupspec.yaml and then follow this steps

  1. Create a GlobalKey

    final _globalKey = GlobalKey();
    
  2. Create Uint8List

    Uint8List pngBytes;
    
  3. Wrap your widget with RepaintBoundary widget & pass in the key

    RepaintBoundary(
      key: _globalKey,
      child: YourWidget(),
    ),
    
  4. Create a method to convert your widget to image:

    Future<void> _capturePng() async {
      try {
        final RenderRepaintBoundary boundary =
            _globalKey.currentContext.findRenderObject();
        final image = await boundary.toImage(pixelRatio: 2.0); // image quality
        final byteData = await image.toByteData(format: ui.ImageByteFormat.png);
        pngBytes = byteData.buffer.asUint8List();
      } catch (e) {
        print(e);
      }
    }
    
  5. Convert your image to a file so that you can save it in your app

    Future<File> convertImageToFile(Uint8List image) async {
      final file = File(
          '${(await 
         getTemporaryDirectory()).path}/${DateTime.now().millisecondsSinceEpoch}.png');
      await file.writeAsBytes(image);
    
      return file;
    }
    
Related