Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write static classes in dart?

Tags:

flutter

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 {}
like image 858
damphat Avatar asked Sep 13 '25 10:09

damphat


1 Answers

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

like image 50
Pieter van Loon Avatar answered Sep 15 '25 23:09

Pieter van Loon