Clipboard an image in Flutter

Viewed 2152

how can I copy (clipboard) an image in Flutter? With texts I can but with image I only found these doubts in the Github of Flutter but without solution.

In Text i using with Clipboard.setData(new ClipboardData(text: widget.content)); and working.

But how copy an image?

3 Answers

Image paste is not supported by flutter clipboard. You can access clipboard on the web like this.

  addPasteListener(ClipboardCallback callback) {
    document.removeEventListener('paste', pasteAuto, false);
    _singleton._callback = callback;
    document.addEventListener('paste', pasteAuto, false);
  }

  pasteAuto(Event ee) async {
    ClipboardEvent e = ee;
    if (e.clipboardData != null) {
      var items = e.clipboardData.items;
      if (items == null) return;

      //access data directly
      var blob;
      for (var i = 0; i < items.length; i++) {
        if (items[i].type.indexOf("image") != -1) {
          blob = items[i].getAsFile();
          break;
        }
      }
      if (blob != null) {
        _singleton._callback(blob);
        e.preventDefault();
      }
    }
  }

As @ariefbayu commented, copying files to clipboard is not widely supported, however, as a general standard, some applications follow the rule of copying the path of the file to the clipboard in order to access it.

To do so, our code could look like this:


Future<String> get _localPath async {
  final directory = await getApplicationDocumentsDirectory();
  return directory.path;
}

Future<void> _copyFile() async {
   final path = await _localPath;
   Clipboard.setData(new ClipboardData(text: "content://${_localPath}/image.png"));
   return;
}

I found a solution for web. I did not test it on android, but maybe it works too?

document.onPaste.listen((ClipboardEvent e) {
  File? blob = e.clipboardData?.items?[0].getAsFile();
});

The blob is your image file.

Related