我正在尝试学习来自服务器端 Java EE 世界的客户端 Dart,但我无法将数组从现有 JavaScript 库转换为 Dart 列表。
我正在尝试通过构建 uses Google Maps 的 Javascript Interop 示例来学习.在谷歌的 Maps API's documentation ,DirectionsLeg
对象的 step
属性返回。
array of DirectionsSteps, each of which contains information about the individual steps in this leg
如何将这个 var
转换为 Dart 列表?我尝试了以下方法:
final List<maps.DirectionsStep> steps = List.from(directionsLeg.steps);
但是 Dart 编辑器告诉我无法解析类“List”中的方法“from”
。我的导入是:
import 'dart:html';
import 'dart:core';
import 'package:js/js.dart' as js;
我做错了什么?是否有可能或者我必须接受使用 var
?
最佳答案
js-interop 中没有内置方法现在使用 Dart List
当一个 js Array
被退回。
directionsLeg.steps
返回 js.Proxy
像 js Array
一样处理.您可以像这样对其进行迭代:
final steps = directionsLeg.steps;
for (var i = 0; i < steps.length ; i++) {
final step = steps[i];
// do the job with step
}
如果你真的想使用 Dart List
你可以转换 js.Proxy
js Array
Dart List
像这样:
List<js.Proxy> convertToList(js.Proxy arrayProxy){
final result = new List<js.Proxy>();
for (var i = 0; i < arrayProxy.length ; i++) {
result.add(arrayProxy[i]);
}
return result;
}
关于您的代码:
- 你不能定义
List<maps.DirectionsStep>
:maps.DirectionsStep
不是类型,它是js.Proxy
关于 jsgoogle.maps.DirectionsStep
(此外,它实际上并不存在 - 只有一个容器 js 对象{}
)。 -
List.from(...)
: 在这里,您尝试调用名为from
的静态方法在 Dart 上List
目的。这就是为什么你得到你的错误。List.from
其实是个工厂named constructor并且必须与new
一起使用关键字 (new List.from(otherIterable)
)。
关于javascript - 从 Javascript 数组创建 Dart 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13598965/