Skip to content

Proposal to implement switch expressions throughout the Flutter repo. #136139

@nate-thegrate

Description

@nate-thegrate

switch expressions are designed for specific use cases; several such cases exist in the flutter repo, but right now they're implemented as switch statements.

Example (animation.dart):

String toStringDetails() {
  switch (status) {
    case AnimationStatus.forward:
      return '\u25B6'; // >
    case AnimationStatus.reverse:
      return '\u25C0'; // <
    case AnimationStatus.completed:
      return '\u23ED'; // >>|
    case AnimationStatus.dismissed:
      return '\u23EE'; // |<<
  }
}
String toStringDetails() {
  return switch (status) {
    AnimationStatus.forward   => '\u25B6'; // >
    AnimationStatus.reverse   => '\u25C0'; // <
    AnimationStatus.completed => '\u23ED'; // >>|
    AnimationStatus.dismissed => '\u23EE'; // |<<
  };
}

They both work, but in my opinion the latter is easier to understand and thus more helpful for debugging.


Additionally, there are places where implementing switch expressions can remove the need for a variable, or allow you to make it final or non-nullable when you otherwise wouldn't be able to:

Example 2 (list_tile.dart):

EdgeInsetsGeometry? padding = widget.padding;
if (padding == null) {
  switch (widget._type) {
    case _CupertinoListTileType.base:
      padding = widget.subtitle == null ? _kPadding : _kPaddingWithSubtitle;
    case _CupertinoListTileType.notched:
      padding = widget.leading == null ? _kNotchedPaddingWithoutLeading : _kNotchedPadding;
  }
}
final EdgeInsetsGeometry padding = widget.padding ?? switch (widget._type) {
  _CupertinoListTileType.base   => widget.subtitle == null ? _kPadding : _kPaddingWithSubtitle,
  _CupertinoListTileType.notched => widget.leading == null ? _kNotchedPaddingWithoutLeading : _kNotchedPadding,
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3Issues that are less important to the Flutter projectc: proposalA detailed proposal for a change to Flutterframeworkflutter/packages/flutter repository. See also f: labels.r: fixedIssue is closed as already fixed in a newer versionrefactorImproving readability/efficiency without behavioral changesteam-frameworkOwned by Framework teamtriaged-frameworkTriaged by Framework team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions