Given the following code:
const jsonString = '{"myString":"Hello"}';
final jsonMap = jsonDecode(jsonString);
final myObject = MyClass.fromJson(jsonMap);
How many ways are there to create a new object using this syntax:
MyClass.fromJson(jsonMap)
Recently I've been trying to understand the differences between named constructors, factory constructors and static methods so I'm posting my answer below so that I have something to come back to as a reference in the future.
To create a new instance of an object using the following syntax:
MyClass.fromJson(jsonMap)
For use with the following code:
// import 'dart:convert';
const jsonString = '{"myString":"Hello"}';
final jsonMap = jsonDecode(jsonString);
final myObject = MyClass.fromJson(jsonMap);
There are at least the following ways to do it (with supplemental notes about the characteristics of each):
class MyClass {
MyClass(this.myString);
final String myString;
MyClass.fromJson(Map<String, dynamic> json) : this(json['myString']);
}
There are two kinds of generative constructors: named and unnamed. The MyClass.fromJson()
is a named constructor while MyClass()
is an unnamed constructor. The following principles apply to generative constructors:
final
properties, that is, not in the constructor body.const
, even if they are not redirecting.class MyClass {
MyClass(this.myString);
final String myString;
factory MyClass.fromJson(Map<String, dynamic> json) {
return MyClass(json['myString']);
}
}
const
, but only when redirecting.class MyClass {
MyClass(this.myString);
final String myString;
static MyClass fromJson(Map<String, dynamic> json) {
return MyClass(json['myString']);
}
}