简体   繁体   English

从 Dart 调用 javascript

[英]calling javascript from Dart

i was able to fire off an alert message from dart, but couldn't figure out how to call a function I wrote in another js file from dart.我能够从 dart 发出警报消息,但无法弄清楚如何从 dart 调用我在另一个 js 文件中编写的函数。 This would have been a great selling point if it was straight forward.如果直截了当,这将是一个很好的卖点。 I did see this post , which got me started, but i feel there must be a way, so please share the love if you figured it out.我确实看到了这篇文章,它让我开始了,但我觉得一定有办法,所以如果你想通了,请分享爱。

Here's what I've done:这是我所做的:

  1. Add this to yaml file:将此添加到 yaml 文件:

    dependencies: js: hosted: js依赖项:js:托管:js

  2. Add import statement to top of dart file: import 'package:js/js.dart' as js;在 dart 文件顶部添加 import 语句: import 'package:js/js.dart' as js;

  3. Add this bit of code to show alert message添加这段代码以显示警报消息

    js.scoped(() { js.context.alert("jump for joy;"); }); js.scoped(() { js.context.alert("欢呼雀跃;"); });

  4. Here's the part which I think should work but doesn't: given that I have a javascript function doSomething(), I should be able to call这是我认为应该起作用但不起作用的部分:鉴于我有一个 javascript 函数 doSomething(),我应该能够调用

    js.context.doSomething(); js.context.doSomething();

First add the js package as dependency in your pubspec.yaml :首先将js 包添加为pubspec.yaml中的依赖项:

dependencies:
  js: any

Then you can use your own js function myFunc() like that:然后你可以像这样使用你自己的 js 函数myFunc()

import 'package:js/js.dart' as js;

main() {
  js.context.myFunc();
}

js.context is an alias to javascript window . js.context是 javascript window的别名。

See Using JavaScript from Dart: The js Library for more details.有关更多详细信息,请参阅从 Dart 使用 JavaScript:js 库

Maybe my answer will be worth it for somebody, so that's why I'm posting a simple JS function call from Dart.也许我的回答对某些人来说是值得的,所以这就是为什么我要发布一个来自 Dart 的简单 JS 函数调用。

  1. Add the js package dependency:添加js包依赖:
     dependencies: js: any
  2. Create a JS file, let's say example.js :创建一个 JS 文件,比方说example.js
     function test() { return 12+20; }
  3. Add the example.js above inside index.html with the <script src="..."> tag.使用<script src="...">标签将上面的example.js添加到index.html中。
  4. Interop the function above from JS to Dart:从 JS 到 Dart 互操作上面的函数:
     @JS() library t; import 'package:js/js.dart'; @JS() external int Test(); class MyOwn { int get value => Test(); }
  5. And, in AngularDart's TODOLIST — which is default component available —:并且,在 AngularDart 的 TODOLIST——这是可用的默认组件——:
     @override Future<Null> ngOnInit() async => print(MyOwn().value);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM