Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dart: Generic which has .fromJson constructor

In Swift I'm used to setting up a protocol JSONInitializable which defines an init?(json: JSON) meaning that all classes and structs that conform to the protocol are initializable with a JSON object.

Is it true that this isn't possible in Dart (with an abstract class) because static methods and factory initializers are not inherited from an abstract class?

The reason I'm asking is because I'm writing a lot of similar methods for API GET requests, which could easily be merged into one, e.g.:

static Future<T> get<T extends JSONInitializable>(int id) async {
  final resourceName = T; // TODO: transform to snake case
  final uri = Uri.parse("$kApiHostname/api/$resourceName/$id");

  final response = await _secureGet(uri);
  if (response == null) {
    return null;
  }

  final responseJson = json.decode(response.body);
  final model = T.fromJson(responseJson);

  return model;
}

But for that to work I'd need to constrain T to a protocol/interface that defines the .fromJson() initializer.

like image 642
Rutger Bresjer Avatar asked Dec 10 '18 16:12

Rutger Bresjer


1 Answers

The feature you want is not available (or planned) in Dart, but there have been discussions on it.

Give this issue a thumbs up: https://github.com/dart-lang/language/issues/356

like image 162
Kevin Moore Avatar answered Oct 20 '22 18:10

Kevin Moore