Is there a better way to make a method of a Dart c

2019-02-09 15:43发布

问题:

index.html (head)

<script>
  var callDartMethod = function(dartObject) {
    return dartObject.fullName();
  }
</script>

index.dart

import 'package:js/js.dart';

@Js() // about to being changed to @JS
external String callDartMethod(p);

main() {
  final p = Person.create(firstName: 'Günter', lastName: 'Zöchbauer');
  print(callDartMethod(p)); // indirect call from JS
  // print(p.fullName()); // call from Dart directly
}

@Js() // about to being changed to @JS
class Person {
  external String get firstName;
  external set firstName(String firstName);

  external String get lastName;
  external set lastName(String lastName);

  external Function get fullName;
  external set fullName(Function function);

  external factory Person({String firstName, String lastName});

  static Person create({String firstName, String lastName}) =>
      new Person(firstName: firstName, lastName: lastName)
        // works but feels a bit cumbersome
        ..fullName = allowInteropCaptureThis(fullNameImpl);

  static String fullNameImpl(self) => '${self.firstName} ${self.lastName}';
}

回答1:

Short answer: no.

pkg/js is currently focused on letting a Dart app consume JavaScript libraries.

We want to make it easier to export APIs written in Dart to JavaScript consumers, but that will come later.