Returning anonymous JS function which returns javascript plain object from Dart


Dart Code

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

void main() {

  var data = new AddLocationData(locationName: "Location1", locationPath: "ThisFolder");
  var func = () => data;

class AddLocationData {
  external String get locationName;
  external String get locationPath;
  external factory AddLocationData({String locationName, String locationPath});

You would assume that func will be a js function but its not. Its type/name is main_closure. See the screenshot


So the first two lines were printed from Dart code then I used Chrome Inspect Element window and right clicked on main_closure' and selected "Store as global variable" which then printedtemp1` and then I used it to display some information about the generated code.

So it is clear Dart returned an object and not a js function and so is the reason of asking this question.

So I want temp1 to be a function instead of$0 so that I can get the data by calling temp1() and not$0().


See js package doc:

Passing functions to JavaScript.

If you are passing a Dart function to a JavaScript API, you must wrap it using allowInterop or allowInteropCaptureThis.

Answered By – Alexandre Ardhuin

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *