Skip to content
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

Allow for shorter dot syntax to access enum values #357

Open
rami-a opened this issue May 16, 2019 · 168 comments
Open

Allow for shorter dot syntax to access enum values #357

rami-a opened this issue May 16, 2019 · 168 comments
Labels
enums feature Proposed language feature that solves one or more problems

Comments

@rami-a
Copy link

rami-a commented May 16, 2019

When using enums in Dart, it can become tedious to have to specify the full enum name every time. Since Dart has the ability to infer the type, it would be nice to allow the use of shorter dot syntax in a similar manner to Swift

The current way to use enums:

enum CompassPoint {
  north,
  south,
  east,
  west,
}

if (myValue == CompassPoint.north) {
  // do something
}

The proposed alternative:

enum CompassPoint {
  north,
  south,
  east,
  west,
}

if (myValue == .north) {
  // do something
}
@johnsonmh
Copy link

This would be especially nice in collections:

const supportedDirections = <CompassPoint>{.north, .east, .west};
bool isSupported = supportedDirections.containsAll({.north, .east});

It's worth noting too that we would only allow it in places where we can infer the enum type.

So

final north = .north; // Invalid.
final CompassPoint north = .north; // Valid.
final north = CompassPoint.north; // Valid.

@kasperpeulen
Copy link

kasperpeulen commented May 18, 2019

In Swift this feature works not only for enums but also for static properties of classes. See also:

munificent/ui-as-code#7

class Fruit {
    static var apple = Fruit(name: "apple");
    static var banana = Fruit(name: "banana");
    
    var name: String;
    
    init(name: String) {
        self.name = name;
    }
}

func printFruit(fruit: Fruit) {
    print(fruit.name);
}

// .banana is here inferred as Fruit.banana
printFruit(fruit: .banana);

@lrhn
Copy link
Member

lrhn commented May 20, 2019

How would the resolution work?

If I write .north, then the compiler has to look for all enums that are available (say, any where the name of the enum resolves to the enum class), and if it finds exactly one such which has a north element, use that.
If there is more than one enum class in scope with a north element, it's a compile-time error. If there is zero, it is a compile-time error.

If we have a context type, we can use that as a conflict resolution: <CompassPoint>[.north, .south] would prefer CompassPoint.north, CompassPoint,south over any other enum with a north or south element.
We won't always have a context type, the example if (myValue == .north) { does not.

Alternatively, we could only allow the short syntax when there is a useful context type.
For the equality, you will have to write CompassPoint.north (unless we introduce something like "context type hints" because we know that if one operand of an == operator is a CompassPoint enum type, and enums don't override Object.==, then the other is probably also a CompassPoint, but that's a different can of worms).
Then we could extend the behavior to any static constant value of the type it's embedded in.
That is, if you have Foo x = .bar; then we check whether Foo has a static constant variable named bar of type Foo, and if so, we use it. That way, a user-written enum class gets the same affordances as a language enum.

I guess we can do that for the non-context type version too, effectively treating any self-typed static constant variable as a potential target for .id.

(Even more alternatively, we can omit the . and just write north. If that name is not in scope, and it's not defined on the interface of this. then we do "magical constant lookup" for enum or enum-like constant declarations in scope.
That's a little more dangerous because it might happen by accident.

@eernstg
Copy link
Member

eernstg commented May 20, 2019

One approach that could be used to avoid writing CompassPoint several times is a local import (#267).

@kasperpeulen
Copy link

How would the resolution work?

@lrhn You may want to study how it works in Swift. I think their implementation is fine.

@johnsonmh
Copy link

@lrhn

Alternatively, we could only allow the short syntax when there is a useful context type.

If we're taking votes, I vote this ☝️

Regarding the case with if (myValue == .north) {, if myValue is dynamic, then I agree, this should not compile. However; myValue would often already be typed, if it is typed, it should work fine. For example:

void _handleCompassPoint(CompassPoint myValue) {
  if (myValue == .north) {
    // do something
  }   
}

For the equality, you will have to write CompassPoint.north

I don't know enough about this, but I don't see why this would need to be the case if we're going with the "useful context type" only route?

Right now we can do:

final direction = CompassPoint.north;
print(direction == CompassPoint.south); // False.
print(direction == CompassPoint.north); // True.
print("foo" == CompassPoint.north); // False.

If we know that direction is CompassPoint, can we not translate direction == .south to direction == CompassPoint.south? Or is that not how this works?

Even more alternatively, we can omit the . and just write north

I don't personally prefer this approach because we risk collisions with existing in scope variable names. If someone has var foo = 5; and enum Bar { foo, }, and they already have a line foo == 5, we won't know if they mean Bar.foo == 5 or 5 == 5.

@lrhn
Copy link
Member

lrhn commented May 22, 2019

The problem with context types is that operator== has an argument type of Object. That gives no useful context type.

We'd have to special case equality with an enum type, so if one operand has an enum type and the other is a shorthand, the shorthand is for an enum value of the other operand's type. That's quite possible, it just doesn't follow from using context types. We have to do something extra for that.

@lrhn
Copy link
Member

lrhn commented Jun 24, 2019

We can generalize the concept of "enum value" to any value or factory.

If you use .foo with a context type of T, then check whether the class/mixin declaration of T declares a static foo getter with a type that is a subtype of T. If so, use that as the value.
If you do an invocation on .foo, that is .foo<...>(...), then check if the declaration of T declares a constructor or static function with a return type which is a subtype of T. If so, invoke that. For constructors, the context type may even apply type arguments.

It still only works when there is a context type. Otherwise, you have to write the name to give context.

@ReinBentdal
Copy link

ReinBentdal commented Jun 24, 2019

To omit the . would make sense for widgets with constructors.

From

Text(
  'some text',
  style: FontStyle(
    fontWeight: FontWeight.bold
  ),
),

To

Text(
  'some text',
  style: ( // [FontStyle] omitted
    fontWeight: .bold // [FontWeight] omitted
  ),
),

For enums and widgets without a constructor the . makes sense to keep, but for widgets where the . never existed, it makes sense to not add it.

FontWeight.bold -> .bold // class without a constructor
Overflow.visible -> .visible // enum
color: Color(0xFF000000) -> color: (0xFF000000) // class with constructor

From issue #417

_Some pints may have been presented already

Not include subclasses of type

Invalid
padding: .all(10)

This wont work because the type EdgeInsetsGeometry is expected, but the type EdgeInsets which is a subclass is given.

Valid
textAlign: .cener

This will work because TextAlign is expected and TextAlign is given.
The solution for the invalid version would be for flutter to adapt to this constraint.

The ?. issue

Alot of people have pointed out this issue on reddit. The problem is as follows:

bool boldText = true;

textAlign = boldText ? .bold : .normal;

The compiler could interpret this as boldText?.bold.
But as mentioned on reddit: https://www.reddit.com/r/FlutterDev/comments/c3prpu/an_option_to_not_write_expected_code_fontweight/ert1nj1?utm_source=share&utm_medium=web2x
This will probably not be a problem because the compiler cares about spaces.

Other usecases

void weight(FontWeight fontWeight) {
  // do something
}
weight(.bold);

@andrewackerman
Copy link

@ReinBentdal

Omitting the period for constructors would lead to a whole slew of ambiguous situations simply because parentheses by themselves are meant to signify a grouping of expressions. Ignoring that, though, I think removing the period will make the intent of the code far less clear. (I'm not even sure I'd agree that this concise syntax should be available for default constructors, only for named constructors and factories.)

And about the ?. issue, like I said in both the reddit post and issue #417, the larger issue is not whether the compiler can use whitespace to tell the difference between ?. and ? .. It's what the compiler should do when there isn't any whitespace at all between the two symbols. Take this for example:

int value = isTrue?1:2;

Notice how there is no space between the ? and the 1. It's ugly, but it's valid Dart code. That means the following also needs to be valid code under the new feature:

textAlign = useBold?.bold:.normal;

And now that there's no space between the ? and the ., how should the compiler interpret the ?.? Is it a null-aware accessor? Is it part of the ternary followed by a type-implicit static accessor? This is an ambiguous situation, so a clear behavior needs to be established.

@ReinBentdal
Copy link

A solution could be to introduce a identifyer.

*.bold // example symbol

But then again, that might just bloat the code/ language.

@lukepighetti
Copy link

lukepighetti commented Feb 27, 2020

I'd like to see something along these lines

final example = MyButton("Press Me!", onTap: () => print("foo"));

final example2 = MyButton("Press Me!",
    size: .small, theme: .subtle(), onTap: () => print("foo"));

class MyButton {
  MyButton(
    this.text, {
    @required this.onTap,
    this.icon,
    this.size = .medium,
    this.theme = .standard(),
  });

  final VoidCallback onTap;
  final String text;
  final MyButtonSize size;
  final MyButtonTheme theme;
  final IconData icon;
}

enum MyButtonSize { small, medium, large }

class MyButtonTheme {
  MyButtonTheme.primary()
      : borderColor = Colors.transparent,
        fillColor = Colors.purple,
        textColor = Colors.white,
        iconColor = Colors.white;

  MyButtonTheme.standard()
      : borderColor = Colors.transparent,
        fillColor = Colors.grey,
        textColor = Colors.white,
        iconColor = Colors.white;

  MyButtonTheme.subtle()
      : borderColor = Colors.purple,
        fillColor = Colors.transparent,
        textColor = Colors.purple,
        iconColor = Colors.purple;

  final Color borderColor;
  final Color fillColor;
  final Color textColor;
  final Color iconColor;
}

@MarcelGarus
Copy link
Contributor

MarcelGarus commented Jul 3, 2020

Exhaustive variants and default values are both concepts applicable in a lot of scenarios, and this feature would help in all of them to make the code more readable. I'd love to be able to use this in Flutter!

return Column(
  mainAxisSize: .max,
  mainAxisAlignment: .end,
  crossAxisAlignment: .start,
  children: <Widget>[
    Text('Hello', textAlign: .justify),
    Row(
      crossAxisAlignment: .baseline,
      textBaseline: .alphabetic,
      children: <Widget>[
        Container(color: Colors.red),
        Align(
          alignment: .bottomCenter,
          child: Container(color: Colors.green),
        ),
      ],
    ),
  ],
);

@lrhn lrhn added the small-feature A small feature which is relatively cheap to implement. label Jul 8, 2020
@lrhn lrhn removed the small-feature A small feature which is relatively cheap to implement. label Sep 8, 2020
@munificent
Copy link
Member

munificent commented Sep 10, 2020

Replying to @mraleph's comment #1077 (comment) on this issue since this is the canonical one for enum shorthands:

I think this is extremely simple feature to implement - yet it has a very delightful effect, code becomes less repetetive and easier to read (in certain cases).

I agree that it's delightful when it works. Unfortunately, I don't think it's entirely simple to implement. At least two challenges are I know are:

How does it interact with generics and type inference?

You need a top-down inference context to know what .foo means, but we often use bottom-up inference based on argument types. So in something like:

f<T>(T t) {}

f(.foo)

We don't know what .foo means. This probably tractable by saying, "Sure, if there's no concrete inference context type, you can't use the shorthand", but I worry there are other complications related to this that we haven't realized yet. My experience is that basically anything touching name resolution gets complex.

What does it mean for enum-like classes?

In large part because enums are underpowered in Dart, it's pretty common to turn an enum into an enum-like class so that you can add other members. If this shorthand only works with actual enums, that breaks any existing code that was using the shorthand syntax to access an enum member. I think that would be really painful.

We could try to extend the shorthand to work with enum-like members, but that could get weird. Do we allow it at access any static member defined on the context type? Only static getters whose return type is the surrounding class's type? What if the return type is a subtype?

Or we could make enum types more full-featured so that this transformation isn't needed as often. That's great, but it means the shorthand is tied to a larger feature.

How does it interact with subtyping?

If we extend the shorthand to work with enum-like classes, or make enums more powerful, there's a very good chance you'll have enum or enum-like types that have interesting super- and subtypes. How does the shorthand play with those?

Currently, if I have a function:

foo(int n) {}

I can change the parameter type to accept a wider type:

foo(num n) {}

That's usually not a breaking change, and is a pretty minor, safe thing to do. But if that original parameter was an enum type and people were calling foo with the shorthand syntax, then widening the parameter type might break the context needed to resolve those shorthands. Ouch.

All of this does not mean that I think a shorthand is intractable or a bad idea. Just that it's more complex than it seems and we'll have to put some real thought into doing it right.

@Abion47
Copy link

Abion47 commented Sep 10, 2020

@munificent

If changing the interface breaks the context to the point that name inference breaks, then that is probably a good thing in the same way that making a breaking change in a package should be statically caught by the compiler. It means that the developer needs to update their code to address the breaking change.

To your last example in particular

foo(int n) {}
// to
foo(num n) {}

if that original parameter was an enum type

Enums don't have a superclass type, so I don't really see how an inheritance issue could arise when dealing with enums. With enum-like classes, maybe, but if you have a function that takes an enum-like value of a specific type, changing the type to a wider superclass type seems like it would be an anti-pattern anyway, and regardless would also fall into what I said earlier about implementing breaking changes resulting in errors in the static analysis of your code being a good thing.

@mraleph
Copy link
Member

mraleph commented Sep 10, 2020

Unfortunately, I don't think it's entirely simple to implement. At least two challenges are I know are:

FWIW you list design challenges, not implementation challenges. The feature as I have described it (treat .m as E.m if .m occurs in place where E is statically expected) is in fact extremely simple to implement. You just treat all occurrences of .m as a dynamic, run the whole inference and then at the very end return to .m shorthands - for each of those look at the context type E and check if E.m is assignable to E (this condition might be tightened to require E.m to be specifically static final|const E m). If it is - great, if it is not issue an error. Done. As described it's a feature on the level of complexity of double literals change that we did few years back (double x = 1 is equivalent to double x = 1.0).

I concede that there might be some design challenges here, but I don't think resolving them should be a blocker for releasing "MVP" version of this feature.

Obviously things like grammar ambiguities would need to be ironed out first: but I am not very ambitions here either, I would be totally fine shipping something that only works in parameter positions, lists and on the right hand side of comparisons - which just side steps known ambiguities.

Just that it's more complex than it seems and we'll have to put some real thought into doing it right.

Sometimes putting too much thought into things does not pay off because you are entering the area of diminishing returns (e.g. your design challenges are the great example of things which I think is not worth even thinking about in the context of this language feature) or worse you are entering analysis paralysis which prevents you from moving ahead and actually making the language more delightful to use with simple changes to it.

That's usually not a breaking change, and is a pretty minor, safe thing to do.

You break anybody doing this:

var x = foo;
x = (int n) { /* ... */ }

Does it mean we should maybe unship static tear-offs? Probably not. Same applies to the shorthand syntax being discussed here.

@lukepighetti
Copy link

lukepighetti commented Sep 10, 2020

I'm not a computer scientist but aren't the majority of these issues solved by making it only work with constructors / static fields that share return a type that matches the host class & enum values? That's my only expectation for it anyway, and none of those come through generic types to begin with. If the type is explicit, it seems like the dart tooling would be able to to know what type you're referring to.

I don't think the value of this sugar can be understated. In the context of Flutter it would offer a ton of positive developer experience.

enum FooEnum {
  foo,
  bar,
  baz
}

f(FooEnum t) {}

f(.foo) // tooling sees f(FooEnum .foo)
f(.bar) // tooling sees f(FooEnum .bar)
f(.baz) // tooling sees f(FooEnum .baz)

In the context of Flutter the missing piece that I find first is how to handle foo(Color c) and trying to do foo(.red) for Colors.red. That seems like it would be a nice feature but I'm not sure how you'd handle that quickly and cleanly. I don't think it's necessary to be honest, though.

@munificent
Copy link
Member

munificent commented Sep 10, 2020

FWIW you list design challenges, not implementation challenges.

Yes, good point. I mispoke there. :)

As described it's a feature on the level of complexity of double literals change that we did few years back

That feature has caused some problems around inference, too, though, for many of the same reasons. Any time you use the surrounding context to know what an expression means while also using the expression to infer the surrounding context, you risk circularity and ambiguity problems. If we ever try to add overloading, this will be painful.

I concede that there might be some design challenges here, but I don't think resolving them should be a blocker for releasing "MVP" version of this feature.

We have been intensely burned on Dart repeatedly by shipping minimum viable features:

  • The cascade syntax is a readability nightmare when used in nested contexts. The language team at the time dismissed this as, "Well, users shouldn't nest it." But they do, all the time, and the code is hard to read because of it. No one correctly understands the precedence and god help you if you try to combine it with a conditional operator.

  • We shipped minimal null-aware operators that were described as a "slam dunk" because of how simple and easy it was. If I recall right, the initial release completely forgot to specify what short-circuiting ??= does. The ?. specified no short-circuiting at all which made it painful and confusing to use in method chains. We are laboriously fixing that now with NNBD and we had to bundle that change into NNBD because it's breaking and needs an explicit migration.

  • The generalized tear-off syntax was basically dead-on-arrival and ended up getting removed.

  • Likewise, the "minimal" type promotion rules initially added to the language didn't cover many common patterns and we are again fixing that with NNBD (even though most of it is not actually related to NNBD) because doing otherwise is a breaking change.

  • The crude syntax-driven exhaustiveness checking for switch statements was maybe sufficient when we were happy with any function possibly silently returning null if it ran past the end without a user realizing but had to be fixed for NNBD.

  • The somewhat-arbitrary set of expressions that are allowed in const is a constant friction point and every couple of releases we end up adding a few more cherry-picked operations to be used there because there is no coherent principle controlling what is and is not allowed in a const expression.

  • The completely arbitrary restriction preventing a method from having both optional positional and optional named parameters causes real pain to users trying to evolve APIs in non-breaking ways.

  • The deliberate simplifications to the original optional type system—mainly covariant everything, no generic methods, and implicit downcasts—were the wrong choice (though made for arguably good reasons at the time) and had to be fixed with an agonizing migration in Dart 2.

I get what you're saying. I'm not arguing that the language team needs to go meditate on a mountain for ten years before we add a single production to the grammar. But I'm pretty certain we have historically been calibrated to underthink language designs to our detriment.

I'm not proposing that we ship a complex feature, I'm suggesting that we think deeply so that we can ship a good simple feature. There are good complex features (null safety) and bad simple ones (non-shorting ?.). Thinking less may by necessity give you a simple feature, but there's no guarantee it will give you a good one.

It's entirely OK if we think through something and decide "We're OK with the feature simply not supporting this case." That's fine. What I want to avoid is shipping it and then realizing "Oh shit, we didn't think about that interaction at all." which has historically happened more than I would like.

You break anybody doing this:

var x = foo;
x = (int n) { /* ... */ }

Does it mean we should maybe unship static tear-offs?

That's why I said "usually". :) I don't think we should unship that, no. But it does factor into the trade-offs of static tear-offs and it is something API maintainers have to think about. The only reason we have been able to change the signature of constructors in the core libraries, which we have done, is because constructors currently can't be torn off.

@jacob314
Copy link
Member

As discussed multiple times, the feature isn't inherently about writability. It's also a readability issue, by removing redundancy. Autocompletion does nothing toward that.
I agree there is an element of readability in this feature. All things being equal I find terse syntax more readable. However, I find cases where syntax is made more terse in ways that leave me guessing at what the code is actually doing slower to understand.

But which unsupported Flutter case are you talking about exactly?

For example, consider the following Flutter code:

Container(
  constraints: BoxConstraints.expand(
    height: Theme.of(context).textTheme.headlineMedium!.fontSize! * 1.1 + 200.0,
  ),
  padding: const EdgeInsets.all(8.0),
  color: Colors.blue[600],
  alignment: Alignment.center,
  transform: Matrix4.rotationZ(0.1),
  child: Text('Hello World',
    style: Theme.of(context)
        .textTheme
        .headlineMedium!
        .copyWith(color: Colors.white)),
)

Here it would seem like the shorter dot syntax should apply to at least the alignment parameter but even with #723 (which I think is great) that is not feasible because Alignment.center and DirectionalAlignment.center would be equally important to include as static extension on AlignmentGeometry. Even if you could, it would be harmful for readability to hide from readers whether Alignment or DirectionalAlignment was used.

@rrousselGit
Copy link

I am sure the framework could adapt to the new feature on those specific cases.

For example, one of the many alternatives is to offer:

alignment: .center,
// vs
alignment: .directionalCenter,

I'm sure an api could be found which would match the requirements people have

And the beauty of static extensions is that if folks are unsatisfied with the current one or none is provided, they can make their own.

@erf
Copy link

erf commented Jul 18, 2023

It's perhaps silly, but i enjoy my code being aesthetically pleasing and sometimes e.g. when using this new switch expression with an Enum the line is too long and must be broken, but only on one line that is, not the others, symmetry is broken, and i can't use block body on the new switch expressions to fit them all in the same way, as i do with some functions, so i try to shorten variables names, but they won't fit still .. so please allow for shorter dot syntax, so my lines are not broken 🙏🥹

@bernaferrari
Copy link

I am 100% pro this change (my second-third favorite feature after Unions and Data Class). This is a small shortcoming, but it is fine: https://twitter.com/i/web/status/1686456074034143232

Apple changed Swift's .foregroundColor(.primary) (Color.primary) to .foregroundStyle(), but .primary is style.primary, not color.primary.

@lutes1
Copy link

lutes1 commented Aug 7, 2023

dart feels like a century old language to a Swift developer precisely because it lacks this feature, please make it happen

@mym0404
Copy link

mym0404 commented Oct 8, 2023

Yeah, we would make Flutter beginner happy if docs shows like that for their first Widget example.

Column(
  crossAxisAlignment: .stretch,
  children: ...,
)

@HaloWang
Copy link

HaloWang commented Oct 12, 2023

I believe this issue is somewhat off-topic. We should avoid discussing code style, but I hope that the Dart language could provide developers with more options.

If we only focus on the enum keyword, it might be easier to implement. We can use analysis_options.yaml to lint the code, or the Dart VS Code extension can offer suggestions when we type a period . while passing parameters to a function.

@zhxst
Copy link

zhxst commented Nov 1, 2023

This proposal is a useful addition to the Type Inference.
As we all use something like final number = 10 or final total = someList.length.
They improve the life of programmers.
And things like Color color = .red and employee.class = .newbie will also improve the life.
I know we maybe greedy and lazy, but that makes us programmers.😂
So please consider this quality of life feature. Thank you🙏

@mit-mit
Copy link
Member

mit-mit commented Dec 15, 2023

I've been looking around at some Flutter code, and from that I think there are three kinds of Dart code that this would be useful for: Enums, named constructors and static members.

I'm curious to hear if others find these useful? And are there more cases to consider?

Enums

Example 1: BoxFit

Use current:

Image(
  image: collectible.icon,
  fit: BoxFit.contain,
)

Use desired:

Image(
  image: collectible.icon,
  fit: .contain,
)

Definitions:

class Image extends StatefulWidget {
  final BoxFit? fit;

  const Image({
    super.key,
    required this.image,
    ...
    this.fit,
  });
}

enum BoxFit {
  fill,
  contain,
  ...
}

Example:
Image(fit: BoxFit.contain)

Example 2: Alignment

Use current:

Row(
  mainAxisAlignment: MainAxisAlignment.center,
  mainAxisSize: MainAxisSize.min,
  children: [ ... ],
)

Use desired:

Row(
  mainAxisAlignment: .center,
  mainAxisSize: .min,
  children: [ ... ],
)

Definitions:

class Row extends Flex {
  const Row({
    ...
    super.mainAxisAlignment,
    ...
  }) : super(
    ...
  );
}

class Flex extends MultiChildRenderObjectWidget {
  final MainAxisAlignment mainAxisAlignment;

  const Flex({
    ...
    this.mainAxisAlignment = MainAxisAlignment.start,
    ...
  }) : ...
}

enum MainAxisAlignment {
  start,
  end,
  center,
  ...
}

Example:
mainAxisAlignment: MainAxisAlignment.center

Named constructors

Example 1: BackdropFilter

Use current:

BackdropFilter(
  filter: ImageFilter.blur(sigmaX: x, sigmaY: y),
  child: myWidget,
)

Use desired:

BackdropFilter(
  filter: .blur(sigmaX: x, sigmaY: y),
  child: myWidget,
)

Definitions:

class BackdropFilter extends SingleChildRenderObjectWidget {
  final ui.ImageFilter filter;

  const BackdropFilter({
    required this.filter,
    ...
  });
}

abstract class ImageFilter {
  ImageFilter._(); // ignore: unused_element
  factory ImageFilter.blur({ double sigmaX = 0.0, double sigmaY = 0.0, TileMode tileMode = TileMode.clamp }) { ... }
}

Example:
filter: ImageFilter.blur

Example 2: Padding

Use current:

Padding(
  padding: EdgeInsets.all(32.0),
  child: myWidget,
),

Use desired:

Padding(
  padding: .all(32.0),
  child: myWidget,
),

Definitions:

class Padding extends SingleChildRenderObjectWidget {
  final EdgeInsetsGeometry padding;

  const Padding({
    super.key,
    required this.padding,
    super.child,
  });
}

class EdgeInsets extends EdgeInsetsGeometry {
  ...
  const EdgeInsets.all(double value)
   : left = value,
      top = value,
      right = value,
      bottom = value;
}

Example: padding: EdgeInsets.all(32.0)

Static members

Use current:

Icon(
  Icons.audiotrack,
  color: Colors.green,
  size: 30.0,
),

Use desired:

Icon(
  .audiotrack,
  color: Colors.green,
  size: 30.0,
),

Definitions:

class Icon extends StatelessWidget {
  /// Creates an icon.
  const Icon(
    this.icon, {
    ...
   }) : ... ;

  final IconData? icon;
}

abstract final class Icons {
  ...
  static const IconData audiotrack = IconData(0xe0b6, fontFamily: 'MaterialIcons');
  ...
}

Example:
Icon(...)

@bernaferrari
Copy link

Super useful, because there is no cognitive load to remember anything. You just press dot and wait for autocomplete to tell the options. Right now is too hard.

@FMorschel
Copy link

Just something that came to me while reading Mit's comment is: what about when for example someone has extended EdgeInsets and has used one of its constructors' name?

For example:

class EdgeInsets2 extends EdgeInsets {
  const EdgeInsets2.all(super.value) : super.all();
}

What would happen when we called .all(8) there (sorry if this has already been discussed. I could not find this above)?

@rrousselGit
Copy link

rrousselGit commented Dec 15, 2023

@mit-mit Color is a big one too, and it's neither an enum nor static members nor named constructors.
For that, I think the most logical is relying on the "static extension" feature

It's about supporting values defined outside of the original class/enum, and support third-party values, such as custom colors/icons.

Use current:

ColoredBox(
  color: Colors.red,
)

Use desired:

ColoredBox(
  color: .red,
)

Definitions:

class ColoredBox extends StatefulWidget {
  final Color fit;

  const ColoredBox({
    super.key,
    required this.color,
  });
}

class Color {}

// Current definition
abstract class Colors { 
  static final red = Color(...);
}

// After using static extensions
static extension Colors on Color {
  static final red = Color(...);
}

Where Colors could become a "static extension" once they land

@bernaferrari
Copy link

Icon would be useful, but then, how do you differentiate Material icon from something else? You can't.

My fear with color is that there is no way to catch the presence of Colors

@rrousselGit
Copy link

rrousselGit commented Dec 15, 2023

My fear with color is that there is no way to catch the presence of Colors

It'd be relying on a separate highly upvoted feature: #723

Cases such as "Icon" vs "MaterialIcon" could use the same logic too.

@FMorschel
Copy link

Icon would be useful [...] there is no way to catch the presence of [...]

The same would be applied to Icons since flutter/flutter#104987 is still open.

@bernaferrari
Copy link

Yes, but it would accept IconData, not Icon, which allows Phosphor/Awesome/Other custom icons to be there. Even if material icon were an enum, it wouldn't be auto suggested because the field doesn't expect a material icon, it expects any icon.

@rrousselGit
Copy link

rrousselGit commented Dec 15, 2023

Static extensions can once again be used:

class IconData {}

static extension Icons on Icon {
  static final abc = IconData(...);
}

void main() {
  Icons.abc; // valid;
  IconData.abc; // also valid
  
  // And with enum shorthands:
  IconData icon = .abc; // valid too. Unwraps to `IconData.abc`
}

It's the same as with Colors in the end

And the key part is that it enables folks to define their own icons/colors if they wish to.

For example one could use FontAwesome and define:

static extension FontAwesomeIcons on IconData {
  static final faMicroship = IconData(0xf2db, fontFamily: 'font-awesome');
}

...
Icon(.faMicroship);

@bernaferrari
Copy link

bernaferrari commented Dec 15, 2023

How would it know which one to import when the names collide?

@rrousselGit
Copy link

That's probably better discussed in #723.
But TL;DR like normal extensions. In case of conflict, have a compilation error when using the .name syntax, and use MyExtension.name or rely on import ... show/hide to resolve the conflict

@bernaferrari
Copy link

bernaferrari commented Dec 15, 2023

This one I don't like, because there is no way to not have the native things (Icon, Color, etc), so you would always have a conflict when using something else. You would end being even more forced to use the native Icons than right now. Would be useful if MaterialIcon(.favorite), but then kind of kills the simplification of Icon(Icons.favorite).

But with everything else I fully agree.

@FMorschel
Copy link

I believe it would be better to have the analyzer do it's job and tell you that you have conflicting options. So you would need to solve that prior to building (of course that could be also a building error).

This way it could show what conflicting options there were, just like when you have two classes with the same name from different sources and it shows us what is conflicting.

@eernstg
Copy link
Member

eernstg commented Dec 18, 2023

@mit-mit, those use cases are very useful!

Just one little thing: It looks like the 'Static Members' example is a copy of the first example, and there's nothing in this example that involves static members (other than the fact that every enum value is compiled into a static const variable). Was there a different example that got lost during editing?

@mit-mit
Copy link
Member

mit-mit commented Dec 19, 2023

It looks like the 'Static Members' example is a copy of the first example

Sorry about that, fixed!

@nidegen
Copy link

nidegen commented Dec 31, 2023

Let's get this merged already!;)

@matt-ragonese
Copy link

An additional use case that should be taken into account when considering this Dart language improvement is the usage of code-generated protobuf enums in Dart (CC @jacob314).

These generated enum types can become very long in Dart, especially when you’re working with protobuf enums that have definitions that are nested within a message type. Borrowing the following protocol buffer enum example from the Dart protobuf documentation:

message Bar {
  enum Color {
    COLOR_UNSPECIFIED = 0;
    COLOR_RED = 1;
    COLOR_GREEN = 2;
    COLOR_BLUE = 3;
  }
}

Usage of the first enum field in Dart post-codegen currently looks like Bar_Color.COLOR_UNSPECIFIED. However, when substituting Bar and Color with longer type names, usage of protobuf enums in Dart without shortened dot syntax can become unwieldy (e.g. SomethingClassType_SomethingEnumType.SOMETHING_UNSPECIFIED).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enums feature Proposed language feature that solves one or more problems
Projects
None yet
Development

No branches or pull requests