1

I can't understand the real purpose of factory constructors. I have this code that contains a method and a factory constructor:

  User fromJJson(Map<String, dynamic> json) {
    final user = User(
      userName: json['userName'],
      photoUrl: json['photoUrl'],
      lastSeen: json['lastSeen'],
      active: json['active'],
    );
    user._id = json['id'];
    return user;
  }

  factory User.fromJson(Map<String, dynamic> json) {
    final user = User(
      userName: json['userName'],
      photoUrl: json['photoUrl'],
      lastSeen: json['lastSeen'],
      active: json['active'],
    );
    user._id = json['id'];
    return user;
  }

What's the difference between the two above, they serve the exact same purpose, so what do factory constructors really do ?

Mikelenjilo
  • 171
  • 1
  • 12
  • 2
    Your above example does have any named constructor. `fromJJson` is an *instance* method and would need to be invoked on an existing `User` object. Usage of `fromJJson` and `User.fromJson` therefore would be different at call sites. If `fromJJson` were a `static` method, then there would be no substantial difference in this case. See https://stackoverflow.com/a/54997386/ – jamesdlin Apr 15 '23 at 15:48

1 Answers1

0

A factory constructor does not Create instance of the class it just return an existing instance of the class.

Example of a factory constructor

class Animal{
  String name;
  String color;

  factory Animal.fromJson(Map<String, dynamic> json) {
    return Animal(json['name'], json['color']);
  }
}

Example of a named constructor

class Animal{
   String name;
   String color;

  Person(this.name, this.color);

  Person.fromName(String name)
      : this(name, "Black");

  Person.fromColor(int color)
      : this("Unknown", color);

}
Mobin Ansar
  • 631
  • 2
  • 13