flutterdart

How to write static classes in dart?


I am porting JSON5 to dart, and I want to keep the original convention.

The original code has a static class JSON5 which contains 2 static methods. But dart doesn't allow static classes.

My dart code:

/// static class, do not instanciate or inherit this
class JSON5 {
  static String stringify(dynamic obj) { };
  static dynamic parse(String json5String) { };
}

Is it possible to stop users from 2 things?


Solution

  • To disallow instantiation you can add a private constructor: JSON5._();

    And to prevent inheritance the best you can currently do in dart is adding the @sealed annotation from the meta package