4

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?

Fabio
  • 53
  • 1
  • 6

3 Answers3

3

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();
      }
    }
  }
9Dragons
  • 137
  • 1
  • 4
2

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;
}
Stefano Amorelli
  • 4,553
  • 3
  • 14
  • 30
  • ok, but if I try when I paste the clipboard on Instagram Direct for example it pastes the image path, not the image. Ex: content:///data/user/0/me.fabio.app/cache/file_picker/ab21d5b71ba7b3b74947c3e5656c6aee.jpg – Fabio Dec 24 '20 at 03:02
  • the target app need to also understand your clipboard schema. I don't thing Instagram undestood that. – ariefbayu Dec 24 '20 at 05:39
  • As @ariefbayu said, that’s the expected behavior. If you’d like to use the image on Instagram, would be the sharing feature a viable option? – Stefano Amorelli Dec 24 '20 at 12:20
2

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.

Bobin
  • 278
  • 5
  • 15