How to use constructor tear-offs in Dart
Juan Belieni
Posted on January 19, 2022
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"),
);
💖 💪 🙅 🚩
Juan Belieni
Posted on January 19, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
dart Using Dart to create custom directories and files for your new Flutter project.
August 21, 2023