-
Notifications
You must be signed in to change notification settings - Fork 29.7k
Description
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);
// ...
}