Flutter Web - Save Image .png from Custom Paint

Viewed 1214

i'm porting a mobile App to Web, this app use the CustomPaint widget to draw based on user inputs. With RepaintBoundary i take a screenshot of the paint and save it on the device using save_in_gallery.dart package.

On the Web app the drawing part works fine, but i can't get the part of the screenshot or the part of saving the image to work. Here's the code i use to save

    RenderRepaintBoundary boundary =
        globalKey.currentContext.findRenderObject();
    ui.Image image = await boundary.toImage();
    ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
    Uint8List pngBytes = byteData.buffer.asUint8List();
    final res = await _imageSaver.saveImage(
      imageBytes: pngBytes,
      directoryName: "dir_name",
    );
    print(res);
    print(pngBytes);
  } 

From what i understood the dart:ui package doesn't work on Flutter Web, but i did not find any alternative. So my question is: there is a way to take an image of Custom Paint and save it as Png file on Flutter Web?

1 Answers

add the following line to the web/index.html file

<script src="https://cdnjs.cloudflare.com/ajax/libs/amcharts/3.21.15/plugins/export/libs/FileSaver.js/FileSaver.min.js"></script>

then pass your pngBytes to a method like this :

import 'dart:html' as html; //ignore: avoid_web_libraries_in_flutter
import 'dart:js' as js; // ignore: avoid_web_libraries_in_flutter

class FileSaver {
  void saveAs(List<int> bytes, String fileName)
    => js.context.callMethod("saveAs", [html.Blob([bytes]), fileName]);
}
Related