Flutter: How to copy HTML into the clipboard so mail apps recognize it as HTML?

Viewed 125

Is it possible to copy HTML and paste it into Gmail or Apple Mail?

Sample HTML:

<img src="w3schools.jpg" alt="W3Schools.com"
width="104" height="142">

I've tried a few different approaches, such as using

Clipboard.setData(ClipboardData(text: myHtmlCode));

and

FlutterClipboard.copy(myHtmlCode).then((value) => print('copied'));

The result is always the same, it pastes literal html code into the mail app instead of jpg or styles. Outlook, on the other hand, does work. I've seen several other apps that do this successfully, but I can't seem to figure it out.

Chatting with colleagues, it seems to be related to copy plain/text and copy plain/html, but I'm still not sure.

1 Answers

There's a package called rich_clipboard that allows us to copy HTML text to the clipboard.

Here's how we do it:

final RichClipboardData data = RichClipboardData(
  text: 'plaintext',
  html: '<html><body>HTMLtext</body></html>',
);

await RichClipboard.setData(data);

To access the data:

// Get clipboard data.
final RichClipboardData clipboardData = await RichClipboard.getData();

// Get plaintext data.
final String? textData = clipboardData.text;

// Get HTML data.
final String? htmlData = clipboardData.html;

You may want to check out this article for more details.

Related