dart advantage of a factory constructor identifier

前端 未结 3 2159
小蘑菇
小蘑菇 2020-11-29 04:48

I\'ve been investigating JSON parsing for my Flutter app and have a question about factory constructors that I can\'t resolve. I\'m trying to understand the advantage of usi

3条回答
  •  执念已碎
    2020-11-29 04:57

    A factory constructor vs. a normal constructor

    • A factory constructor invokes another constructor.
    • Since a factory constructor does not directly create a new instance, it cannot use a constructor initializer list.
    • A normal constructor always returns a new instance of the class. A factory constructor is permitted to return an existing instance, an instance of a derived class, or null. (However, some people dislike returning null from a factory constructor.)

    A factory constructor vs. a static method

    • A factory constructor can be the unnamed, default constructor of a class.
    • A factory constructor can be used with new. (But using new is now discouraged.)
    • Static methods can be used to create tear-offs (i.e., they can be used as callbacks) but constructors currently can't.
    • Static methods can be async. (A factory constructor must return a type of its class, so it cannot return a Future.)
    • Factory constructors can be declared const.
    • In generated dartdoc documentation, a factory constructor obviously will be listed in the "Constructors" section (which is prominently at the top) whereas a static method will be in the "Static Methods" section (which currently is buried at the bottom).

提交回复
热议问题