Skip to content

Proposal: allow passing constructors as functions #35901

@rhcarvalho

Description

@rhcarvalho

This feature request intends to allow using constructors where functions with the same type/signature are expected.

Example code: https://dartpad.dartlang.org/9745b0f73157959a1c82a66ddf8fdba4


Background

As of Dart 2, Effective Dart suggests not using the new keyword and removing it from existing code.
Doing that makes named constructors and static methods look the same at call sites.

The Language Tour says (emphasis mine):

Constructors

Declare a constructor by creating a function with the same name as its class [...]

Thus suggesting that a constructor is a function. But it turns out it is not really a function, as it cannot be used in all contexts where a function can.

Why it would be useful

Dart built in types, in particular collection types, have several methods that take functions as arguments, for instance .forEach and .map, two concise and expressive ways to perform computations.

In an program I'm working on, I got a bit surprised by not being able to create new instances using Iterable.map + a named constructor. And then I realized that others have arrived at the same conclusion at least 4 years back on StackOverflow, but I could not find a matching issue.

Example Flutter code

What I would like to write:

  return Column(
    // This won't compile:
    children: ['Alice', 'Bob', 'Charlie'].map(Text).toList(),
  );

What I have to write instead with Dart 2.1.0:

  return Column(
    // Need a dummy wrapper around the constructor:
    children: ['Alice', 'Bob', 'Charlie'].map((name) => Text(name)).toList(),
  );

Note that the feature request is not specific to Flutter code, but applies to any Dart code as per the more generic example in https://dartpad.dartlang.org/9745b0f73157959a1c82a66ddf8fdba4.


  • Dart SDK Version (dart --version)
Dart version 2.1.0 (build 2.1.0-dev.9.4 f9ebf21297)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions