DEV Community

Cover image for How to use constructor tear-offs in Dart
Juan Belieni
Juan Belieni

Posted on

How to use constructor tear-offs in Dart

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) ...
Enter fullscreen mode Exit fullscreen mode

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"
...
Enter fullscreen mode Exit fullscreen mode

Examples with Flutter

1 - Let's think in a simple example:

Column(
  children: ['Apple', 'Orange'].map((word) => Text(word)).toList(),
);
Enter fullscreen mode Exit fullscreen mode

With constructor tear-offs, you can simplify this expression as the following:

Column(
  children: ['Apple', 'Orange'].map(Text.new).toList(),
);
Enter fullscreen mode Exit fullscreen mode

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"),
    );
}
Enter fullscreen mode Exit fullscreen mode

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"),
);
Enter fullscreen mode Exit fullscreen mode

Discussion (0)