dartmigrationdart-html

Migrating from dart:html to web — how to listen for events?


I'm currently trying to follow the migration guide at dart.dev to update a package that relies on the now deprecated dart:html library.

Some of the updates are straightforward. For example, something like

import "dart:html" as html;

...

final canvas = html.CanvasElement(width: 100, height: 100);

becomes

import "package:web/web.dart" as web;

...

final canvas = web.HTMLCanvasElement()..width=100..height=100;

but I am struggling to handle listeners.

For example, I have something like this, which works using dart:html:

html.document.onFocus.listen((_) {
  // handle event...
});

I notice that web.document has an onfocus attached, but I can't add a listener to it...

How do we handle events, such as the above? And where can we find detailed documentation for the web package?


Solution

  • You can convert a Dart function into a JSFunction by calling the .toJS (from dart:js_interop) getter on your Function.

    The JSFunction instance can be used to set the callback of your web.document.onfocus.

    So something like:

    import 'package:web/web.dart' as web;
    import 'dart:js_interop';
    
    void main() {
      void printString(web.Event event) {
        print(event.target);
      }
    
      web.document.onfocus = printString.toJS;
    }