Skip to content

New of T #4333

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
loic-sharma opened this issue Apr 22, 2025 · 1 comment
Closed

New of T #4333

loic-sharma opened this issue Apr 22, 2025 · 1 comment
Labels
feature Proposed language feature that solves one or more problems state-duplicate This issue or pull request already exists

Comments

@loic-sharma
Copy link

loic-sharma commented Apr 22, 2025

Introduction

It would be nice if Dart could instantiate a generic type. For example:

T myFactory<T>() {
  return T();
}

This would likely need some sort of generic constraint to ensure T can be instantiated.

Use case

Today, a Flutter StatefulWidget must implement the createState method:

class Foo extends StatefulWidget {
  const Foo();

  @override
  State<Foo> createState() => _FooState();
}

This language feature would be a step towards removing the createState method: StatefulWidget would accept a generic parameter and use that to provide a default createState implementation:

- class Foo extends StatefulWidget {
+ class Foo extends StatefulWidget<_FooState> {
    const Foo();
-
-   @override
-   State<Foo> createState() => _FooState();
  }

Previous discussions

The following issues appear relevant:

  1. could support T : new() like C#? #1787
  2. More capable Type objects #4200

Feel free to close this if there is a better tracking issue already :)

@loic-sharma loic-sharma added the feature Proposed language feature that solves one or more problems label Apr 22, 2025
@lrhn
Copy link
Member

lrhn commented Apr 28, 2025

I think the current place-holder issue for this is #356.

The issue is the same in every case: There needs to be some way to ensure that the type bound to T has an unnamed constructor with that signature. That means some restriction on which types can be passed as arguments, which has to be expressed in some way (what #1787 was one syntax for).
Having specific static members is also a property of a type that cannot be tested at runtime, so there is no way to go from a type parameter <T> to a type argument to <T : new()>. That's what #4200 tries to solve by making the type objects implement interfaces that can be checked at runtime.

Closing this deferring to #356.

@lrhn lrhn closed this as completed Apr 28, 2025
@lrhn lrhn added the state-duplicate This issue or pull request already exists label Apr 28, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature Proposed language feature that solves one or more problems state-duplicate This issue or pull request already exists
Projects
None yet
Development

No branches or pull requests

2 participants