2012-11-28 40 views
4

我正试图学习来自服务器端Java EE世界的客户端Dart,并且我无法将数组从现有JavaScript库转换为Dart列表。从Javascript数组创建飞镖列表

我想通过建立在Javascript互操作示例0123.上学习。在Google的Maps API's documentation中,DirectionsLeg对象的step属性返回。

DirectionsSteps的阵列,每个包含在这条腿

我如何转换这种var的各个步骤到达特列表的信息?我曾尝试以下方法:

final List<maps.DirectionsStep> steps = List.from(directionsLeg.steps); 

但是Dart Editor告诉我cannot resolve method 'from' in class 'List'。我的进口是:

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

我在做什么错?这是甚至可能或者我必须接受使用var

回答

7

js-interop现在没有内置的方法来使用飞镖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 
} 

如果你真的想用一个飞镖List可以的JS Arrayjs.Proxy转换成飞镖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上js google.maps.DirectionsStep(此外它并不真正存在 - 只有一个容器js对象{})。
  • List.from(...):在这里,您尝试调用Dart List对象上名为from的静态方法。那就是为什么你得到你的错误。 List.from实际上是一个工厂named constructor,必须与new关键字(new List.from(otherIterable))一起使用。
+0

感谢您对代码的评论 - 我非常喜欢这门语言,但是与Java的细微差别让我感觉很不舒服,我将静态方法这个命名的构造函数当作一个完美的例子。 – Rich