Skip to content

Flutter style guide – "Constructor syntax" #144501

@nate-thegrate

Description

@nate-thegrate

I've noticed that at this point, the Flutter Style Guide doesn't mention factory constructors, and const factory isn't explained anywhere on dart.dev.

This is a proposal to update the "constructor syntax" section of the Flutter Style Guide to something like the following:

Constructor syntax

Avoid using static methods to create class instances.

class Foo {
  // BAD
  static Foo fromJsonString(String source) {
    // ...
  }

  // GOOD
  factory Foo.fromJsonString(String source) {
    // ...
  }
}

Static methods are sometimes necessary, e.g. when there's a nullable return type:

class Color {
  static Color? lerp(Color? a, Color? b, double t) {
    // ...
  }
}

Assign a factory constructor using = if the factory creates a class object with a different constructor, using the same parameters.

It can be declared as a const factory if it redirects to a const constructor.

abstract class Foo {
  // BAD
  factory Foo.withFunction(VoidCallback function) => _FooWithFunction(function);

  // GOOD
  factory Foo.withFunction(VoidCallback function) = _FooWithFunction;
}

class _FooWithFunction extends Foo {
  _FooWithFunction(this.function);

  final VoidCallback function;
}

A colon : can be used after the class parameter list to assign class members, make asserts, and/or redirect non-factory constructors to this or super.

All expressions after the colon should be aligned to match the indentation of the first.

class Foo {
  Foo.manyAsserts({
    required Text label,
    Color? color,
  }) : _text = label.data,
       _style = label.style,
       _textOpacity = label.style.color.opacity,
       _colorOpacity = color.opacity,
       assert(
         _text.length < 20,
         'label text is too long to be displayed correctly.',
       ),
       assert(_text == _text.trim()),
       assert(_colorOpacity > 0.5);
       assert(_textOpacity >= _colorOpacity);

  // no need to write out everything a second time!
  Foo.blank(Color color) : this.manyAsserts(label: Text(''), color: color);

  // ...
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3Issues that are less important to the Flutter projectd: wikiFlutter or engine wikisr: solvedIssue is closed as solvedteam-frameworkOwned by Framework teamtriaged-frameworkTriaged by Framework team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions