One of the limitations of Flutter is its clipboard support. Currently, Flutter's Clipboard API only supports copying and pasting plaintext. While this gets the job done in common scenarios, it can be limited in its application as well.
The copied data is always exposed to the user and can be pasted anywhere. This behavior is not ideal when we want to use the device clipboard to store and access application-specific data. For example, if we want to store an image's metadata in Clipboard to recreate the image on paste, we do not want to expose the data to the user.
This problem can be solved by using HTML text, as most text fields and editors do not parse HTML. As a result, the copied data is kept hidden.
Now, let's take a look at how to copy HTML text in Flutter.
rich_clipboard is the package that allows us to store and access both plaintext and HTML text from the device clipboard. The best thing about this package is that it supports all six platforms.
First, we create an object, RichClipboardData
, with the data to be copied.
final RichClipboardData data = RichClipboardData(text: 'plaintext',html: '<html><body>HTMLtext</body></html>',);
The good thing is that both plaintext and HTML text are copied at the same time, but we're free to keep either of them null
. In this case, only the provided data is copied. We can also keep both the parameters null
to clear the clipboard.
// Copy only plaintext.final RichClipboardData data = RichClipboardData(text: 'plaintext',);// Copy only HTML text.final RichClipboardData data = RichClipboardData(html: '<html><body>HTMLtext</body></html>',);// Clear clipboard.final RichClipboardData data = RichClipboardData();
We use the setData
method to store the data in the device clipboard:
await RichClipboard.setData(data);
To access the data, we simply use the getData
method:
// 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;
That's it! This is how we can store and access HTML data from the device clipboard in Flutter.