Search code examples
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?

  • instanciate the class: var json5 = JSON5()
  • extends or implements the class: class DerivedJSON5 extends JSON5 {}

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