Zheden Zheden - 2 months ago 19
Dart Question

Create javascript object from dart

I have Dart application that reads data and calls method from javascript to draw a tree from that data (in D3)
I want to create js object on Dart side and draw it on javascript side.

But on Dart side I get expected result and cannot convert to js object properly..

javascript:

var treeRoot = [{}]; // <-- I want to fill this object on Dart side

function updateTree() {
var nodes = tree.nodes(treeRoot).reverse(), // <- use this object on js side
links = tree.links(nodes);
// .. code for tree drawing
}


Dart:

Future _showTree() async {
var treeData = getTreeData();

// try to fill js object with my data
js.context['treeRoot'] = new js.JsObject.jsify([treeData]);

// DART PRINT
var treeRoot = await js.context['treeRoot'];
print('dart : treeRoot\n' + treeRoot.toString());

js.context.callMethod('updateTree');

}


As result in DART PRINT I see what I expect:

dart : treeRoot
[name: A 1
child: {
name: B 1
child: {
name: D 1
}
child: {
name: E 1
}
}
child: {
name: C 1
}
]


But when I look at treeRoot from console (to check js object) I get

[DartObject
o: Tree
__proto__: DartObject]


(Tree is type of getTreeData() in Dart)

How can I get object in format that I printed in DART PRINT? I want to use it as simple js object, forget about any dart objects on js side. (when I look on that 'o' objet, I dont see 'child' and 'name' properties, there is a loot of other stuff)

Small note: I know that json can be used for that communication, but I want js object without any json conversions.

Answer

As Gunter suggested, I should use dart-js-interop. So I create js object in dart - JsTree. To fill the data I traverse tree.

Object is declared like this:

@anonymous
@JS()
class Tree {
  external String get name;
  external set name(String value);

  external List<Tree> get children;
  external set children(List<Tree> value);
}

@JS()
external buildTree(Tree tree);

in dart I call:

Tree jsTree = copyDartTree(treeData);
// call js function
buildTree(jsTree);
Comments