getClipboardData static method

Future<Map<String, String>?> getClipboardData()

Retrieves the plain text and HTML text content from the clipboard asynchronously.

Future<Map<String, String>?> clipboardContent = ClipboardWeb.getClipboardData();
clipboardContent.then((content) {
  if (content != null) {
    String plainText = content['plainText'];
    String htmlText = content['htmlText'];
    // Process the clipboard content
  } else {
    // Clipboard is empty or unsupported
  }
});

Returns:

  • a Future that completes with a Map containing the plain text and HTML text content from the clipboard if the read operation was successful,
  • a Future that completes with null if the clipboard is empty or unsupported.

Implementation

static Future<Map<String, String>?> getClipboardData() async {
  final Clipboard clipboard = getClipboard();
  final Iterable<ClipboardItem> content = await clipboard.read();
  if (content.isEmpty) {
    /// Clipboard is empty, return null.
    return null;
  }
  final Map<String, String> result = <String, String>{};
  for (final ClipboardItem item in content) {
    if (item.types.contains('text/plain')) {
      /// Read the plain text.
      final html.Blob? blob = await item.getType('text/plain');
      if (blob == null) {
        /// Failed to read the plain text, continue.
        continue;
      }
      result['plainText'] = (await blob.text()) ?? '';
    }
    if (item.types.contains('text/html')) {
      /// Read the HTML text.
      final html.Blob? blob = await item.getType('text/html');
      if (blob == null) {
        /// Failed to read the HTML text, continue.
        continue;
      }
      result['htmlText'] = (await blob.text()) ?? '';
    }
  }

  /// Return the clipboard content.
  return result;
}