In Dart 2.15, it was announced a new language feature called constructor tear-offs. Now, you can treat constructors as regular functions that returns an instance of a class.
Enabling constructor tear-offs
To use this feature, you just have to have Dart 2.15 (or any higher version) installed in your system:
$ dart --version
# Dart SDK version: 2.15.1 (stable) ...
At your pubspec.yaml
, it is import to update the SDK version to have 2.15 (or any higher version installed in your system) as the minimum version:
...
environment:
sdk: ">=2.15.0 <3.0.0"
...
Examples with Flutter
1 - Let's think in a simple example:
Column(
children: ['Apple', 'Orange'].map((word) => Text(word)).toList(),
);
With constructor tear-offs, you can simplify this expression as the following:
Column(
children: ['Apple', 'Orange'].map(Text.new).toList(),
);
2 - Code abstraction is also made easier with this syntax:
Widget widget;
switch (type) {
case "outlined":
widget = OutlinedButton(
onPressed: () {},
child: const Text("Button"),
);
break;
case "text":
widget = TextButton(
onPressed: () {},
child: const Text("Button"),
);
break;
default:
widget = ElevatedButton(
onPressed: () {},
child: const Text("Button"),
);
}
Abstracting...
Function button;
switch (type) {
case "outlined":
button = OutlinedButton.new;
break;
case "text":
button = TextButton.new;
break;
default:
button = ElevatedButton.new;
}
Widget widget = button(
onPressed: () {},
child: const Text("Button"),
);
Top comments (0)