From 38879daef73feaca5d3c14ab4389bd79d3173781 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 29 Jan 2024 11:14:02 -0700 Subject: [PATCH] Implementing `switch` expressions in `foundation/` and `material/` (#142279) This PR is the fourth step in the journey to solve issue #136139 and make the entire Flutter repo more readable. (previous pull requests: #139048, #139882, #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`. --- .../flutter/lib/src/foundation/binding.dart | 13 ++--- .../lib/src/foundation/diagnostics.dart | 45 ++++++--------- packages/flutter/lib/src/material/about.dart | 13 ++--- .../adaptive_text_selection_toolbar.dart | 34 ++++-------- packages/flutter/lib/src/material/arc.dart | 12 ++-- .../src/material/bottom_navigation_bar.dart | 55 +++++++------------ .../flutter/lib/src/material/button_bar.dart | 11 ++-- .../lib/src/material/button_theme.dart | 35 ++++-------- .../flutter/lib/src/material/checkbox.dart | 11 ++-- packages/flutter/lib/src/material/chip.dart | 40 +++++--------- .../lib/src/material/circle_avatar.dart | 20 +++---- .../lib/src/material/color_scheme.dart | 22 +++----- 12 files changed, 115 insertions(+), 196 deletions(-) diff --git a/packages/flutter/lib/src/foundation/binding.dart b/packages/flutter/lib/src/foundation/binding.dart index a663cf9716..424c545c62 100644 --- a/packages/flutter/lib/src/foundation/binding.dart +++ b/packages/flutter/lib/src/foundation/binding.dart @@ -585,14 +585,11 @@ abstract class BindingBase { name: FoundationServiceExtensions.brightnessOverride.name, callback: (Map 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(), diff --git a/packages/flutter/lib/src/foundation/diagnostics.dart b/packages/flutter/lib/src/foundation/diagnostics.dart index a23a9bee34..d56ba92592 100644 --- a/packages/flutter/lib/src/foundation/diagnostics.dart +++ b/packages/flutter/lib/src/foundation/diagnostics.dart @@ -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. diff --git a/packages/flutter/lib/src/material/about.dart b/packages/flutter/lib/src/material/about.dart index 76462c8c60..84c3028d53 100644 --- a/packages/flutter/lib/src/material/about.dart +++ b/packages/flutter/lib/src/material/about.dart @@ -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 >[masterPageRoute]; - case _Focus.detail: - return >[ - masterPageRoute, - _detailPageRoute(_cachedDetailArguments), - ]; - } + return switch (focus) { + _Focus.master => >[masterPageRoute], + _Focus.detail => >[masterPageRoute, _detailPageRoute(_cachedDetailArguments)], + }; }, onGenerateRoute: (RouteSettings settings) { switch (settings.name) { diff --git a/packages/flutter/lib/src/material/adaptive_text_selection_toolbar.dart b/packages/flutter/lib/src/material/adaptive_text_selection_toolbar.dart index c4fb54c631..6c08ac58ef 100644 --- a/packages/flutter/lib/src/material/adaptive_text_selection_toolbar.dart +++ b/packages/flutter/lib/src/material/adaptive_text_selection_toolbar.dart @@ -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 => '', + }; } } diff --git a/packages/flutter/lib/src/material/arc.dart b/packages/flutter/lib/src/material/arc.dart index d194d08c15..cb873a4c36 100644 --- a/packages/flutter/lib/src/material/arc.dart +++ b/packages/flutter/lib/src/material/arc.dart @@ -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 diff --git a/packages/flutter/lib/src/material/bottom_navigation_bar.dart b/packages/flutter/lib/src/material/bottom_navigation_bar.dart index ee92130fd6..6e981ec86b 100644 --- a/packages/flutter/lib/src/material/bottom_navigation_bar.dart +++ b/packages/flutter/lib/src/material/bottom_navigation_bar.dart @@ -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, @@ -858,12 +856,10 @@ class _BottomNavigationBarState extends State 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 @@ -969,13 +965,10 @@ class _BottomNavigationBarState extends State 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( @@ -1138,13 +1131,10 @@ class _BottomNavigationBarState extends State 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, @@ -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; } @@ -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 radiusTween = Tween( begin: 0.0, diff --git a/packages/flutter/lib/src/material/button_bar.dart b/packages/flutter/lib/src/material/button_bar.dart index e3e36ec80f..46b646652c 100644 --- a/packages/flutter/lib/src/material/button_bar.dart +++ b/packages/flutter/lib/src/material/button_bar.dart @@ -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; diff --git a/packages/flutter/lib/src/material/button_theme.dart b/packages/flutter/lib/src/material/button_theme.dart index e41ea025e5..4a27a398a5 100644 --- a/packages/flutter/lib/src/material/button_theme.dart +++ b/packages/flutter/lib/src/material/button_theme.dart @@ -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; @@ -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; diff --git a/packages/flutter/lib/src/material/checkbox.dart b/packages/flutter/lib/src/material/checkbox.dart index 25c5ad532b..b898e2cf06 100644 --- a/packages/flutter/lib/src/material/checkbox.dart +++ b/packages/flutter/lib/src/material/checkbox.dart @@ -508,13 +508,10 @@ class _CheckboxState extends State 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 effectiveMouseCursor = MaterialStateProperty.resolveWith((Set states) { diff --git a/packages/flutter/lib/src/material/chip.dart b/packages/flutter/lib/src/material/chip.dart index db91a12477..7d5d7e84b8 100644 --- a/packages/flutter/lib/src/material/chip.dart +++ b/packages/flutter/lib/src/material/chip.dart @@ -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 @@ -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); @@ -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 diff --git a/packages/flutter/lib/src/material/circle_avatar.dart b/packages/flutter/lib/src/material/circle_avatar.dart index 3f7c9584ff..aecfa93112 100644 --- a/packages/flutter/lib/src/material/circle_avatar.dart +++ b/packages/flutter/lib/src/material/circle_avatar.dart @@ -204,19 +204,15 @@ class CircleAvatar extends StatelessWidget { Color? effectiveBackgroundColor = backgroundColor ?? (theme.useMaterial3 ? theme.colorScheme.primaryContainer : null); if (effectiveBackgroundColor == null) { - switch (ThemeData.estimateBrightnessForColor(textStyle.color!)) { - case Brightness.dark: - effectiveBackgroundColor = theme.primaryColorLight; - case Brightness.light: - effectiveBackgroundColor = theme.primaryColorDark; - } + effectiveBackgroundColor = switch (ThemeData.estimateBrightnessForColor(textStyle.color!)) { + Brightness.dark => theme.primaryColorLight, + Brightness.light => theme.primaryColorDark, + }; } else if (effectiveForegroundColor == null) { - switch (ThemeData.estimateBrightnessForColor(backgroundColor!)) { - case Brightness.dark: - textStyle = textStyle.copyWith(color: theme.primaryColorLight); - case Brightness.light: - textStyle = textStyle.copyWith(color: theme.primaryColorDark); - } + textStyle = switch (ThemeData.estimateBrightnessForColor(backgroundColor!)) { + Brightness.dark => textStyle.copyWith(color: theme.primaryColorLight), + Brightness.light => textStyle.copyWith(color: theme.primaryColorDark), + }; } final double minDiameter = _minDiameter; final double maxDiameter = _maxDiameter; diff --git a/packages/flutter/lib/src/material/color_scheme.dart b/packages/flutter/lib/src/material/color_scheme.dart index 2ee1d0c083..a0d92122fd 100644 --- a/packages/flutter/lib/src/material/color_scheme.dart +++ b/packages/flutter/lib/src/material/color_scheme.dart @@ -193,13 +193,10 @@ class ColorScheme with Diagnosticable { Color? scrim, Color? surfaceTint, }) { - final Scheme scheme; - switch (brightness) { - case Brightness.light: - scheme = Scheme.light(seedColor.value); - case Brightness.dark: - scheme = Scheme.dark(seedColor.value); - } + final Scheme scheme = switch (brightness) { + Brightness.light => Scheme.light(seedColor.value), + Brightness.dark => Scheme.dark(seedColor.value), + }; return ColorScheme( primary: primary ?? Color(scheme.primary), onPrimary: onPrimary ?? Color(scheme.onPrimary), @@ -1073,13 +1070,10 @@ class ColorScheme with Diagnosticable { final List scoredResults = Score.score(colorToCount, desired: 1); final ui.Color baseColor = Color(scoredResults.first); - final Scheme scheme; - switch (brightness) { - case Brightness.light: - scheme = Scheme.light(baseColor.value); - case Brightness.dark: - scheme = Scheme.dark(baseColor.value); - } + final Scheme scheme = switch (brightness) { + Brightness.light => Scheme.light(baseColor.value), + Brightness.dark => Scheme.dark(baseColor.value), + }; return ColorScheme(primary: primary ?? Color(scheme.primary), onPrimary: onPrimary ?? Color(scheme.onPrimary),