javascript - 从 Javascript 数组创建 Dart 列表

标签 javascript dart

我正在尝试学习来自服务器端 Java EE 世界的客户端 Dart,但我无法将数组从现有 JavaScript 库转换为 Dart 列表。

我正在尝试通过构建 uses Google Maps 的 Javascript Interop 示例来学习.在谷歌的 Maps API's documentationDirectionsLeg 对象的 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关于 js google.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/

相关文章:

flutter - 单击按钮后执行函数 FLUTTER

javascript - 使用 HTML5 本地存储存储下拉列表中的多个选择

javascript - d3v4 "columns"的替代方案(我必须使用 d3v3)

javascript - 将数组放入自定义对象

javascript - 将 leaflet-control-geocoder 与 react-leaflet 一起使用

javascript - 循环遍历对象并查找指定属性

dart - 如何从\n中删除字符以字符串结尾

dart - 在 dart web 项目中,输入和引用警告不应该是错误吗?

android - Flutter:热重载后出现 "Lost connection to device"错误

flutter - 所有卡片的 TextField 值更改