I am trying to learn client-side Dart, coming from a server-side Java EE world, and I am having trouble converting an array from an existing JavaScript library into a Dart List.
I am trying to learn by building on the Javascript Interop example that uses Google Maps. In Google's Maps API's documentation, the DirectionsLeg
object's step
property returns.
array of DirectionsSteps, each of which contains information about the individual steps in this leg
How can I convert this var
into a Dart List? I have tried the following:
final List<maps.DirectionsStep> steps = List.from(directionsLeg.steps);
But Dart Editor tells me cannot resolve method 'from' in class 'List'
. My imports are:
import 'dart:html';
import 'dart:core';
import 'package:js/js.dart' as js;
What am I doing wrong? Is it even possible or must I just accept using a var
?
There's no built-in way in js-interop for now to use Dart List
when a js Array
is returned.
directionsLeg.steps
returns a js.Proxy
which handles like js Array
. You can iterate on it like this :
final steps = directionsLeg.steps;
for (var i = 0; i < steps.length ; i++) {
final step = steps[i];
// do the job with step
}
If you really want to use a Dart List
you can convert the js.Proxy
of js Array
to a Dart List
with something like :
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;
}
About your code :
List<maps.DirectionsStep>
: maps.DirectionsStep
is not a type, it's a js.Proxy
on js google.maps.DirectionsStep
(moreover it don't really exist - only a container js object {}
).List.from(...)
: here, you try to call a static method named from
on Dart List
object. That why you get your error. List.from
is actually a factory named constructor and has to be used with the new
keyword ( new List.from(otherIterable)
).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With