0

Is there a reason why using json_serializable I should use a factory constructor instead of a static method?

I would need to use a static method, but I'm wondering about the downsides

imtoori
  • 570
  • 6
  • 13
  • I read somewhere (can't find the source now) that a factory constructor is essentially a static method that returns a new instance of the class. – Tom Jan 27 '20 at 16:45

1 Answers1

0

Using factory has a purpose here:

it forces you to define

factory counts as a constructor, so if you define at least one then there's no implicit constructor:

class Foo {
  factory Foo.fromJson() {
    return Foo(); // Doesn't compile
  }
}

Which is opposed to:

class Foo {
  static Foo.fromJson() {
    return Foo(); // compiles
  }
}
Rémi Rousselet
  • 256,336
  • 79
  • 519
  • 432