Skip to content

Commit

Permalink
Implementing switch expressions in foundation/ and material/ (f…
Browse files Browse the repository at this point in the history
…lutter#142279)

This PR is the fourth step in the journey to solve issue flutter#136139 and make the entire Flutter repo more readable.

(previous pull requests: flutter#139048, flutter#139882, flutter#141591)

This one is covering files in `packages/flutter/lib/src/foundation/` and `packages/flutter/lib/src/material/`.  
The `material/` directory is pretty big though, so for now I just did the files that start with `a`, `b`, and `c`.
  • Loading branch information
nate-thegrate authored Jan 29, 2024
1 parent 5ee1460 commit 38879da
Show file tree
Hide file tree
Showing 12 changed files with 115 additions and 196 deletions.
13 changes: 5 additions & 8 deletions packages/flutter/lib/src/foundation/binding.dart
Original file line number Diff line number Diff line change
Expand Up @@ -585,14 +585,11 @@ abstract class BindingBase {
name: FoundationServiceExtensions.brightnessOverride.name,
callback: (Map<String, String> parameters) async {
if (parameters.containsKey('value')) {
switch (parameters['value']) {
case 'Brightness.light':
debugBrightnessOverride = ui.Brightness.light;
case 'Brightness.dark':
debugBrightnessOverride = ui.Brightness.dark;
default:
debugBrightnessOverride = null;
}
debugBrightnessOverride = switch (parameters['value']) {
'Brightness.light' => ui.Brightness.light,
'Brightness.dark' => ui.Brightness.dark,
_ => null,
};
_postExtensionStateChangedEvent(
FoundationServiceExtensions.brightnessOverride.name,
(debugBrightnessOverride ?? platformDispatcher.platformBrightness).toString(),
Expand Down
45 changes: 17 additions & 28 deletions packages/flutter/lib/src/foundation/diagnostics.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1718,34 +1718,23 @@ abstract class DiagnosticsNode {
@protected
TextTreeConfiguration? get textTreeConfiguration {
assert(style != null);
switch (style!) {
case DiagnosticsTreeStyle.none:
return null;
case DiagnosticsTreeStyle.dense:
return denseTextConfiguration;
case DiagnosticsTreeStyle.sparse:
return sparseTextConfiguration;
case DiagnosticsTreeStyle.offstage:
return dashedTextConfiguration;
case DiagnosticsTreeStyle.whitespace:
return whitespaceTextConfiguration;
case DiagnosticsTreeStyle.transition:
return transitionTextConfiguration;
case DiagnosticsTreeStyle.singleLine:
return singleLineTextConfiguration;
case DiagnosticsTreeStyle.errorProperty:
return errorPropertyTextConfiguration;
case DiagnosticsTreeStyle.shallow:
return shallowTextConfiguration;
case DiagnosticsTreeStyle.error:
return errorTextConfiguration;
case DiagnosticsTreeStyle.truncateChildren:
// Truncate children doesn't really need its own text style as the
// rendering is quite custom.
return whitespaceTextConfiguration;
case DiagnosticsTreeStyle.flat:
return flatTextConfiguration;
}
return switch (style!) {
DiagnosticsTreeStyle.none => null,
DiagnosticsTreeStyle.dense => denseTextConfiguration,
DiagnosticsTreeStyle.sparse => sparseTextConfiguration,
DiagnosticsTreeStyle.offstage => dashedTextConfiguration,
DiagnosticsTreeStyle.whitespace => whitespaceTextConfiguration,
DiagnosticsTreeStyle.transition => transitionTextConfiguration,
DiagnosticsTreeStyle.singleLine => singleLineTextConfiguration,
DiagnosticsTreeStyle.errorProperty => errorPropertyTextConfiguration,
DiagnosticsTreeStyle.shallow => shallowTextConfiguration,
DiagnosticsTreeStyle.error => errorTextConfiguration,
DiagnosticsTreeStyle.flat => flatTextConfiguration,

// Truncate children doesn't really need its own text style as the
// rendering is quite custom.
DiagnosticsTreeStyle.truncateChildren => whitespaceTextConfiguration,
};
}

/// Returns a string representation of this node and its descendants.
Expand Down
13 changes: 4 additions & 9 deletions packages/flutter/lib/src/material/about.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1187,15 +1187,10 @@ class _MasterDetailFlowState extends State<_MasterDetailFlow> implements _PageOp
key: _navigatorKey,
initialRoute: 'initial',
onGenerateInitialRoutes: (NavigatorState navigator, String initialRoute) {
switch (focus) {
case _Focus.master:
return <Route<void>>[masterPageRoute];
case _Focus.detail:
return <Route<void>>[
masterPageRoute,
_detailPageRoute(_cachedDetailArguments),
];
}
return switch (focus) {
_Focus.master => <Route<void>>[masterPageRoute],
_Focus.detail => <Route<void>>[masterPageRoute, _detailPageRoute(_cachedDetailArguments)],
};
},
onGenerateRoute: (RouteSettings settings) {
switch (settings.name) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -212,28 +212,18 @@ class AdaptiveTextSelectionToolbar extends StatelessWidget {
case TargetPlatform.windows:
assert(debugCheckHasMaterialLocalizations(context));
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
switch (buttonItem.type) {
case ContextMenuButtonType.cut:
return localizations.cutButtonLabel;
case ContextMenuButtonType.copy:
return localizations.copyButtonLabel;
case ContextMenuButtonType.paste:
return localizations.pasteButtonLabel;
case ContextMenuButtonType.selectAll:
return localizations.selectAllButtonLabel;
case ContextMenuButtonType.delete:
return localizations.deleteButtonTooltip.toUpperCase();
case ContextMenuButtonType.lookUp:
return localizations.lookUpButtonLabel;
case ContextMenuButtonType.searchWeb:
return localizations.searchWebButtonLabel;
case ContextMenuButtonType.share:
return localizations.shareButtonLabel;
case ContextMenuButtonType.liveTextInput:
return localizations.scanTextButtonLabel;
case ContextMenuButtonType.custom:
return '';
}
return switch (buttonItem.type) {
ContextMenuButtonType.cut => localizations.cutButtonLabel,
ContextMenuButtonType.copy => localizations.copyButtonLabel,
ContextMenuButtonType.paste => localizations.pasteButtonLabel,
ContextMenuButtonType.selectAll => localizations.selectAllButtonLabel,
ContextMenuButtonType.delete => localizations.deleteButtonTooltip.toUpperCase(),
ContextMenuButtonType.lookUp => localizations.lookUpButtonLabel,
ContextMenuButtonType.searchWeb => localizations.searchWebButtonLabel,
ContextMenuButtonType.share => localizations.shareButtonLabel,
ContextMenuButtonType.liveTextInput => localizations.scanTextButtonLabel,
ContextMenuButtonType.custom => '',
};
}
}

Expand Down
12 changes: 6 additions & 6 deletions packages/flutter/lib/src/material/arc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -279,12 +279,12 @@ class MaterialRectArcTween extends RectTween {
}

Offset _cornerFor(Rect rect, _CornerId id) {
switch (id) {
case _CornerId.topLeft: return rect.topLeft;
case _CornerId.topRight: return rect.topRight;
case _CornerId.bottomLeft: return rect.bottomLeft;
case _CornerId.bottomRight: return rect.bottomRight;
}
return switch (id) {
_CornerId.topLeft => rect.topLeft,
_CornerId.topRight => rect.topRight,
_CornerId.bottomLeft => rect.bottomLeft,
_CornerId.bottomRight => rect.bottomRight,
};
}

/// The path of the corresponding [begin], [end] rectangle corners that lead
Expand Down
55 changes: 21 additions & 34 deletions packages/flutter/lib/src/material/bottom_navigation_bar.dart
Original file line number Diff line number Diff line change
Expand Up @@ -558,12 +558,10 @@ class _BottomNavigationTile extends StatelessWidget {
).evaluate(animation);
}

switch (type) {
case BottomNavigationBarType.fixed:
size = 1;
case BottomNavigationBarType.shifting:
size = (flex! * 1000.0).round();
}
size = switch (type) {
BottomNavigationBarType.fixed => 1,
BottomNavigationBarType.shifting => (flex! * 1000.0).round(),
};

Widget result = InkResponse(
onTap: onTap,
Expand Down Expand Up @@ -858,12 +856,10 @@ class _BottomNavigationBarState extends State<BottomNavigationBar> with TickerPr
// Unselected labels are shown by default for [BottomNavigationBarType.fixed],
// and hidden by default for [BottomNavigationBarType.shifting].
bool get _defaultShowUnselected {
switch (_effectiveType) {
case BottomNavigationBarType.shifting:
return false;
case BottomNavigationBarType.fixed:
return true;
}
return switch (_effectiveType) {
BottomNavigationBarType.shifting => false,
BottomNavigationBarType.fixed => true,
};
}

@override
Expand Down Expand Up @@ -969,13 +965,10 @@ class _BottomNavigationBarState extends State<BottomNavigationBar> with TickerPr
final ThemeData themeData = Theme.of(context);
final BottomNavigationBarThemeData bottomTheme = BottomNavigationBarTheme.of(context);

final Color themeColor;
switch (themeData.brightness) {
case Brightness.light:
themeColor = themeData.colorScheme.primary;
case Brightness.dark:
themeColor = themeData.colorScheme.secondary;
}
final Color themeColor = switch (themeData.brightness) {
Brightness.light => themeData.colorScheme.primary,
Brightness.dark => themeData.colorScheme.secondary,
};

final TextStyle effectiveSelectedLabelStyle =
_effectiveTextStyle(
Expand Down Expand Up @@ -1138,13 +1131,10 @@ class _BottomNavigationBarState extends State<BottomNavigationBar> with TickerPr
?? BottomNavigationBarLandscapeLayout.spread;
final double additionalBottomPadding = MediaQuery.viewPaddingOf(context).bottom;

Color? backgroundColor;
switch (_effectiveType) {
case BottomNavigationBarType.fixed:
backgroundColor = widget.backgroundColor ?? bottomTheme.backgroundColor;
case BottomNavigationBarType.shifting:
backgroundColor = _backgroundColor;
}
final Color? backgroundColor = switch (_effectiveType) {
BottomNavigationBarType.fixed => widget.backgroundColor ?? bottomTheme.backgroundColor,
BottomNavigationBarType.shifting => _backgroundColor,
};

return Semantics(
explicitChildNodes: true,
Expand Down Expand Up @@ -1298,8 +1288,8 @@ class _RadialPainter extends CustomPainter {
for (int i = 0; i < circles.length; i += 1) {
if (circles[i] != oldPainter.circles[i]) {
return true;
}
}
}
return false;
}

Expand All @@ -1309,13 +1299,10 @@ class _RadialPainter extends CustomPainter {
final Paint paint = Paint()..color = circle.color;
final Rect rect = Rect.fromLTWH(0.0, 0.0, size.width, size.height);
canvas.clipRect(rect);
final double leftFraction;
switch (textDirection) {
case TextDirection.rtl:
leftFraction = 1.0 - circle.horizontalLeadingOffset;
case TextDirection.ltr:
leftFraction = circle.horizontalLeadingOffset;
}
final double leftFraction = switch (textDirection) {
TextDirection.rtl => 1.0 - circle.horizontalLeadingOffset,
TextDirection.ltr => circle.horizontalLeadingOffset,
};
final Offset center = Offset(leftFraction * size.width, size.height / 2.0);
final Tween<double> radiusTween = Tween<double>(
begin: 0.0,
Expand Down
11 changes: 4 additions & 7 deletions packages/flutter/lib/src/material/button_bar.dart
Original file line number Diff line number Diff line change
Expand Up @@ -383,14 +383,11 @@ class _RenderButtonBarRow extends RenderFlex {
super.performLayout();
} else {
final BoxConstraints childConstraints = constraints.copyWith(minWidth: 0.0);
RenderBox? child;
double currentHeight = 0.0;
switch (verticalDirection) {
case VerticalDirection.down:
child = firstChild;
case VerticalDirection.up:
child = lastChild;
}
RenderBox? child = switch (verticalDirection) {
VerticalDirection.down => firstChild,
VerticalDirection.up => lastChild,
};

while (child != null) {
final FlexParentData childParentData = child.parentData! as FlexParentData;
Expand Down
35 changes: 11 additions & 24 deletions packages/flutter/lib/src/material/button_theme.dart
Original file line number Diff line number Diff line change
Expand Up @@ -241,16 +241,11 @@ class ButtonThemeData with Diagnosticable {
/// * [getPadding], which is used to calculate padding for the [button]'s
/// child (typically the button's label).
EdgeInsetsGeometry get padding {
if (_padding != null) {
return _padding;
}
switch (textTheme) {
case ButtonTextTheme.normal:
case ButtonTextTheme.accent:
return const EdgeInsets.symmetric(horizontal: 16.0);
case ButtonTextTheme.primary:
return const EdgeInsets.symmetric(horizontal: 24.0);
}
return _padding ?? switch (textTheme) {
ButtonTextTheme.normal => const EdgeInsets.symmetric(horizontal: 16.0),
ButtonTextTheme.accent => const EdgeInsets.symmetric(horizontal: 16.0),
ButtonTextTheme.primary => const EdgeInsets.symmetric(horizontal: 24.0),
};
}
final EdgeInsetsGeometry? _padding;

Expand All @@ -269,20 +264,12 @@ class ButtonThemeData with Diagnosticable {
/// * [getShape], which is used to calculate the shape of the [button]'s
/// [Material].
ShapeBorder get shape {
if (_shape != null) {
return _shape;
}
switch (textTheme) {
case ButtonTextTheme.normal:
case ButtonTextTheme.accent:
return const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(2.0)),
);
case ButtonTextTheme.primary:
return const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(4.0)),
);
}
return _shape ?? switch (textTheme) {
ButtonTextTheme.normal || ButtonTextTheme.accent =>
const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2.0))),
ButtonTextTheme.primary =>
const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))),
};
}
final ShapeBorder? _shape;

Expand Down
11 changes: 4 additions & 7 deletions packages/flutter/lib/src/material/checkbox.dart
Original file line number Diff line number Diff line change
Expand Up @@ -508,13 +508,10 @@ class _CheckboxState extends State<Checkbox> with TickerProviderStateMixin, Togg
final VisualDensity effectiveVisualDensity = widget.visualDensity
?? checkboxTheme.visualDensity
?? defaults.visualDensity!;
Size size;
switch (effectiveMaterialTapTargetSize) {
case MaterialTapTargetSize.padded:
size = const Size(kMinInteractiveDimension, kMinInteractiveDimension);
case MaterialTapTargetSize.shrinkWrap:
size = const Size(kMinInteractiveDimension - 8.0, kMinInteractiveDimension - 8.0);
}
Size size = switch (effectiveMaterialTapTargetSize) {
MaterialTapTargetSize.padded => const Size(kMinInteractiveDimension, kMinInteractiveDimension),
MaterialTapTargetSize.shrinkWrap => const Size(kMinInteractiveDimension - 8.0, kMinInteractiveDimension - 8.0),
};
size += effectiveVisualDensity.baseSizeAdjustment;

final MaterialStateProperty<MouseCursor> effectiveMouseCursor = MaterialStateProperty.resolveWith<MouseCursor>((Set<MaterialState> states) {
Expand Down
40 changes: 15 additions & 25 deletions packages/flutter/lib/src/material/chip.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1439,14 +1439,11 @@ class _ChipRenderWidget extends SlottedMultiChildRenderObjectWidget<_ChipSlot, R

@override
Widget? childForSlot(_ChipSlot slot) {
switch (slot) {
case _ChipSlot.label:
return theme.label;
case _ChipSlot.avatar:
return theme.avatar;
case _ChipSlot.deleteIcon:
return theme.deleteIcon;
}
return switch (slot) {
_ChipSlot.label => theme.label,
_ChipSlot.avatar => theme.avatar,
_ChipSlot.deleteIcon => theme.deleteIcon,
};
}

@override
Expand Down Expand Up @@ -1971,17 +1968,12 @@ class _RenderChip extends RenderBox with SlottedContainerRenderObjectMixin<_Chip
}

void _paintCheck(Canvas canvas, Offset origin, double size) {
Color? paintColor;
if (theme.checkmarkColor != null) {
paintColor = theme.checkmarkColor;
} else {
switch (theme.brightness) {
case Brightness.light:
paintColor = theme.showAvatar ? Colors.white : Colors.black.withAlpha(_kCheckmarkAlpha);
case Brightness.dark:
paintColor = theme.showAvatar ? Colors.black : Colors.white.withAlpha(_kCheckmarkAlpha);
}
}
Color? paintColor = theme.checkmarkColor ?? switch ((theme.brightness, theme.showAvatar)) {
(Brightness.light, true ) => Colors.white,
(Brightness.light, false) => Colors.black.withAlpha(_kCheckmarkAlpha),
(Brightness.dark, true ) => Colors.black,
(Brightness.dark, false) => Colors.white.withAlpha(_kCheckmarkAlpha),
};

final ColorTween fadeTween = ColorTween(begin: Colors.transparent, end: paintColor);

Expand Down Expand Up @@ -2260,12 +2252,10 @@ bool _hitIsOnDeleteIcon({
deflatedSize.width * 0.499,
math.min(labelPadding.resolve(textDirection).right + deleteButtonSize.width, 24.0 + deleteButtonSize.width / 2.0),
);
switch (textDirection) {
case TextDirection.ltr:
return adjustedPosition.dx >= deflatedSize.width - accessibleDeleteButtonWidth;
case TextDirection.rtl:
return adjustedPosition.dx <= accessibleDeleteButtonWidth;
}
return switch (textDirection) {
TextDirection.ltr => adjustedPosition.dx >= deflatedSize.width - accessibleDeleteButtonWidth,
TextDirection.rtl => adjustedPosition.dx <= accessibleDeleteButtonWidth,
};
}

// BEGIN GENERATED TOKEN PROPERTIES - Chip
Expand Down
Loading

0 comments on commit 38879da

Please sign in to comment.