DEV Community

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

Posted on

4 2

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay