Skip to content

Dot syntax for static access #3616

Open
@nate-thegrate

Description

@nate-thegrate

Proposal

If a type T can be inferred, then interpret .foo as T.foo.

This is similar to #357, but with a broader use case: it applies to enums, static members, and also factories & constructors.


Example

// enums
Brightness brightness = .dark;
final brightness = .dark; // error: no inferred type


// static members
bool isArrowKey(LogicalKeyboardKey key) => switch (key) {
   .arrowDown || .arrowLeft || .arrowRight || .arrowUp => true, // fits on a single line!
  _ => false,
};
if (key == .arrowUp) {} // error, since == operator doesn't infer type


// factories & constructors
HSLColor favoriteColor = .fromColor(Color(0xFF00FFFF)); // factory
HSLColor favoriteHue = .fromAHSL(1, 180, 1, 0.5); // named constructor

// you don't write a dot for the unnamed constructor, so it doesn't change
const Duration twoSeconds = Duration(seconds: 2);

Here's everything put together:

@override
Widget build(BuildContext context) {
  return Container(
    width: .infinity,
    margin: .zero,
    padding: .symmetric(vertical: 8.0),
    decoration: BoxDecoration(
      color: .fromARGB(255, 0, 128, 255),
      shape: .circle,
    ),
    child: widget.child,
  );
}

Note

Setting the margin and padding would probably need something like flutter/flutter#157890 in order to work.



Later On

Static Analysis

If/when this is implemented, it should probably come with some additional linter rules:

  • prefer class name for enums, constructors, static members
  • and the reverse: prefer no class name for enums, constructors, static members

from keyword

I really liked the keyword idea from #1955 and would love to see it implemented at some point down the line.

In that issue, from was added after the parameter name. I think that attaching it to the type would be best but would be happy either way.

abstract final class MyColors {
  static const chartreuse = Color(0xFF80FF00);
  static const spring     = Color(0xFF00FF80);
  static const vermilion  = Color(0xFFFF4000);
  static const indigo     = Color(0xFF4000FF);
}

typedef MyColor = Color from MyColors;

class AnimatedIcon extends StatelessWidget {
  const AnimatedIcon({
    required this.icon,
    required this.duration,
    required this.curve,
    required this.color,
  });
  final IconData from Icons icon;
  final Duration from Durations duration;
  final Curve from Curves curve;
  final MyColor color;
  ...
}

final icon = AnimatedIcon(
  icon: .home,
  duration: .medium1,
  curve: .easeOut,
  color: .spring,
);

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureProposed language feature that solves one or more problems

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions