Search code examples
dartdart-html

dart clipboardData always null


The following

main.html

<!DOCTYPE html>

<html>
  <head>
    <title>test</title>
  </head>
  <body>
    <p id="test" draggable="true">hello world</p> 
    <script type="application/dart" src="main.dart"></script>
    <!-- for this next line to work, your pubspec.yaml file must have a dependency on 'browser' -->
    <script src="packages/browser/dart.js"></script>
  </body>
</html>

and main.dart

import 'dart:html';
void main() {
  var elem = query('#test');
  elem.onDragStart.listen((evt) {
    evt.clipboardData.setData('text/html', elem.innerHtml);
  });
}

are producing the exception

The null object does not have a method 'setData'.

NoSuchMethodError : method not found: 'setData'
Receiver: null
Arguments: ["text/html", "hello world"]

I've searched, but can find no relevant information about what I could possibly be doing wrong, or about clipboardData in dart at all (even the API is silent on the issue, and the source dart:html file just points to "native code"


Solution

  • (From my comment to the original question)

    Use this instead:

    evt.dataTransfer.setData('text/html', elem.innerHtml);
    

    It is an attribute on MouseEvent (api ref) rather than the base Event class, and you can get autocomplete and remove editor warnings by explicitly declaring that evt is of type MouseEvent:

    elem.onDragStart.listen((MouseEvent evt) {
      evt.dataTransfer.setData('text/html', elem.innerHtml);
    });