Expose Dart functions to javascript

天涯浪子 提交于 2019-12-17 16:09:42

问题


I'm a bit of a newb to dart, and trying to get my feet wet by writing some library functions in it.

While I've had no problem calling javascript functions from dart, I'd love to be able to call dart functions from javascript, but so far, I'm not having much like.

For example, I'd love to be able to expose some basic functions from dart, for example like so:

main() {
  String foo() {
    return "bar!";
  }

  js.scoped(() {
    js.context.foo = foo;
  });
}

and then be able to call them from javascript, like so:

<script>
  window.onload = function() {
    alert("foo() = " + foo());
  }
</script>

Is something like this even possible?


回答1:


No problem ! see Calling Dart from JavaScript.

In your case :

import 'dart:js' as js;
main() {
  String foo() {
    return "bar!";
  }

  js.context['foo'] = foo;
}



回答2:


In Dart 1.20 I had to add allowInterop()

import 'dart:js' as js;
main() {
  String foo() {
    return "bar!";
  }

  js.context['foo'] = allowInterop(foo);
}



回答3:


In Dart 2.3.0 I had to tweak the solution just a bit for allowInterop to play nice.


    import 'dart:js' as js;
    main() {
      String foo() {
        return "bar!";
      }

      js.context['foo'] = js.allowInterop(foo);
    }



来源:https://stackoverflow.com/questions/15669163/expose-dart-functions-to-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!