2012-11-28 41 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