How to create a type alias in Flutter?
Asked Answered
D

3

5

I have seen some old questions/answers that said it's impossible to create a type alias on Flutter. I just want to make sure whether it's the case, as the language seems to have been updated numerous times since.

My specific question is, how can I make a type alias like this:

typealias Json = Map<String, dynamic>;

?

Or is there any workaround, because I've tried to use empty mixin to do this but it says that there are 18 missing method implementations.

Discriminator answered 19/1, 2021 at 4:17 Comment(0)
R
1

At this point, typedefs are supported only for Function types (https://dart.dev/guides/language/language-tour#typedefs). There is talk of adding more, but not any time soon (https://github.com/dart-lang/language/issues/115).

Rozalie answered 19/1, 2021 at 5:11 Comment(0)
S
7

Small update on Randai Schwartz's comment. The feature seems (as of April 2021) almost ready and will probably be released in the next minor version or the one after it.

When you read this, it is probably worth checking the following issue: https://github.com/dart-lang/language/issues/65

This should allow to do:

typedef NewTypeName = OldTypeName;

Update:

Flutter officially supports now typedefs. :) So you can just use my code example above.

Scapegrace answered 4/4, 2021 at 17:7 Comment(1)
That's great to hear!!Discriminator
R
1

At this point, typedefs are supported only for Function types (https://dart.dev/guides/language/language-tour#typedefs). There is talk of adding more, but not any time soon (https://github.com/dart-lang/language/issues/115).

Rozalie answered 19/1, 2021 at 5:11 Comment(0)
L
0

Flutter 2.2 has been released together with Dart 2.13, now SimonEritsch code should work as you wanted as long as you run flutter upgrade on your terminal or upgrade your dart.

Label answered 22/5, 2021 at 4:17 Comment(2)
Ooh. Interesting. At the moment my current projects kinda stuck with the pre-sound-null-safety version of flutter which also might not have the fix from SimonEritsch, so I might use this for future projects. Thanks!Discriminator
Hi! I know it's been some time. Just wanted to say so it's an option for someone looking. Maybe it's a bit much for some easy features like that, but if you have any features between projects and you can or find a good reason to do that: If you make a package with null safety you could put this typedef there as well and it would show in any projects that you included the package.Label

© 2022 - 2024 — McMap. All rights reserved.