Skip to content

Instantly share code, notes, and snippets.

@bergwerf
Created April 28, 2017 11:54
Show Gist options
  • Save bergwerf/1b427ad2b1f9770b260dd4dac295b6f0 to your computer and use it in GitHub Desktop.
Save bergwerf/1b427ad2b1f9770b260dd4dac295b6f0 to your computer and use it in GitHub Desktop.
Copy to clipboard for Dart
/// A hack to copy a string to the clipboard.
bool _copyToClipboardHack(String text) {
final textarea = new TextAreaElement();
document.body.append(textarea);
textarea.style.border = '0';
textarea.style.margin = '0';
textarea.style.padding = '0';
textarea.style.opacity = '0';
textarea.style.position = 'absolute';
textarea.readOnly = true;
textarea.value = text;
textarea.select();
final result = document.execCommand('copy');
textarea.remove();
return result;
}
@bergwerf
Copy link
Author

bergwerf commented Dec 6, 2020

How can we do it using the navigator's clipboard feature?

You can directly access the clipboard API in Dart. Note that you can only alter the clipboard in response to user events (this is a safety measure).

<button id="copy">Copy!</button>
import 'dart:html';

void main() {
  document.querySelector('#copy').onClick.listen((_) {
    window.navigator.clipboard.writeText("Hello, World!");
  });
}

@vakenbolt
Copy link

@bergwerf Thanks for posting a clipboard API example in dart. 💯 🙌 🍻

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment