How to call javascript object methods from Dart/Flutter using package:js?

968 Views Asked by At

I'm using Flutter web. I have a javascript class with methods. I can call the constructor from Dart with package:js, and I can access members with getters, but when I try to call a class method I get a NoSuchMethodError. How do I make the class methods available to Dart?

In my index.html I have this in a script block:

class TestClass {
  constructor(val) {
    this.foo = val;
    console.log("TestClass constructed with foo="+this.foo);
  }

  someGenericFunction() {
      console.log("generic");
  }

  getSomeValue(foo, bar) {
    return this.foo+" "+foo+" "+bar;
  }
}

This is my Dart interop code:

@JS()
library testclass.js;

import 'package:js/js.dart';
   
@anonymous
@JS()
abstract class TestClass {
  external factory TestClass({String foo});
  external String get foo;
  external void someGenericFunction();
  external String getSomeValue(String foo, String bar);

}

Here's my Dart code:

TestClass ts = TestClass(foo: "dart"); //Works!
String foo = ts.foo;  //Works!

//The below methods error with:
//JSNoSuchMethodError (NoSuchMethodError: tried to call a non-function...)
ts.someGenericFunction();
ts.someGenericFunction.call();    
String testClassString = ts.getSomeValue("one", "two");

The constructor works and the getter works. How do I correctly expose the TestClass methods?

0

There are 0 best solutions below