Dart using Json_object to produce strong typing

2019-09-12 12:43发布

问题:

Using the ideas outlined in ding the article Using Dart with JSON Web Services at https://www.dartlang.org/articles/json-web-service/, I have been trying to implement the section on using JsonObject and interfaces to produce a strong typing of JSON data.

The article indicates that one should write something like.

abstract class Language {
  String language;
  List targets;
  Map website;
}

class LanguageImpl extends JsonObject implements Language {
  LanguageImpl(); 

  factory LanguageImpl.fromJsonString(string) {
    return new JsonObject.fromJsonString(string, new LanguageImpl());
  }
}

However the compiler 'fail' at the definition of the class LanguageImpl with the message

Missing inherited members: 'Language.website', 'Language.targets' and 'Language.language'

Even more confusing the code will run without a problem....

回答1:

In Darteditor you get Quick fix support for this. Set the caret at LanguageImpl and press ctrl+1 or use the context menu > Quick fix. You get the missing concrete implementations you inherit from the abstract base class generated automatically.

Dart is a dynamic language and therefor very flexible. The tools support you and try to give meaningful warnings and hints about what could go wrong but don't prevent you running a program even when it is not yet finished.

You can use the @proxy annotation on the class to silent the warnings. This also needs the class to have a noSuchMethod() implementation.



标签: dart