diff --git a/packages/flutter/lib/src/animation/animation_controller.dart b/packages/flutter/lib/src/animation/animation_controller.dart index 27919f2c1bb..a0ec2c8e756 100644 --- a/packages/flutter/lib/src/animation/animation_controller.dart +++ b/packages/flutter/lib/src/animation/animation_controller.dart @@ -598,20 +598,15 @@ class AnimationController extends Animation } TickerFuture _animateToInternal(double target, { Duration? duration, Curve curve = Curves.linear }) { - double scale = 1.0; - if (SemanticsBinding.instance.disableAnimations) { - switch (animationBehavior) { - case AnimationBehavior.normal: - // Since the framework cannot handle zero duration animations, we run it at 5% of the normal - // duration to limit most animations to a single frame. - // Ideally, the framework would be able to handle zero duration animations, however, the common - // pattern of an eternally repeating animation might cause an endless loop if it weren't delayed - // for at least one frame. - scale = 0.05; - case AnimationBehavior.preserve: - break; - } - } + final double scale = switch (animationBehavior) { + // Since the framework cannot handle zero duration animations, we run it at 5% of the normal + // duration to limit most animations to a single frame. + // Ideally, the framework would be able to handle zero duration animations, however, the common + // pattern of an eternally repeating animation might cause an endless loop if it weren't delayed + // for at least one frame. + AnimationBehavior.normal when SemanticsBinding.instance.disableAnimations => 0.05, + AnimationBehavior.normal || AnimationBehavior.preserve => 1.0, + }; Duration? simulationDuration = duration; if (simulationDuration == null) { assert(!(this.duration == null && _direction == _AnimationDirection.forward)); @@ -721,16 +716,12 @@ class AnimationController extends Animation _direction = velocity < 0.0 ? _AnimationDirection.reverse : _AnimationDirection.forward; final double target = velocity < 0.0 ? lowerBound - _kFlingTolerance.distance : upperBound + _kFlingTolerance.distance; - double scale = 1.0; final AnimationBehavior behavior = animationBehavior ?? this.animationBehavior; - if (SemanticsBinding.instance.disableAnimations) { - switch (behavior) { - case AnimationBehavior.normal: - scale = 200.0; // This is arbitrary (it was chosen because it worked for the drawer widget). - case AnimationBehavior.preserve: - break; - } - } + final double scale = switch (behavior) { + // This is arbitrary (it was chosen because it worked for the drawer widget). + AnimationBehavior.normal when SemanticsBinding.instance.disableAnimations => 200.0, + AnimationBehavior.normal || AnimationBehavior.preserve => 1.0, + }; final SpringSimulation simulation = SpringSimulation(springDescription, value, target, velocity * scale) ..tolerance = _kFlingTolerance; assert( diff --git a/packages/flutter/lib/src/animation/animations.dart b/packages/flutter/lib/src/animation/animations.dart index 93e01248744..6aa6c72684e 100644 --- a/packages/flutter/lib/src/animation/animations.dart +++ b/packages/flutter/lib/src/animation/animations.dart @@ -425,15 +425,10 @@ class CurvedAnimation extends Animation with AnimationWithParentMixin null, + AnimationStatus.forward || AnimationStatus.reverse => _curveDirection ?? status, + }; } bool get _useForwardCurve { @@ -584,12 +579,10 @@ class TrainHoppingAnimation extends Animation bool hop = false; if (_nextTrain != null) { assert(_mode != null); - switch (_mode!) { - case _TrainHoppingMode.minimize: - hop = _nextTrain!.value <= _currentTrain!.value; - case _TrainHoppingMode.maximize: - hop = _nextTrain!.value >= _currentTrain!.value; - } + hop = switch (_mode!) { + _TrainHoppingMode.minimize => _nextTrain!.value <= _currentTrain!.value, + _TrainHoppingMode.maximize => _nextTrain!.value >= _currentTrain!.value, + }; if (hop) { _currentTrain! ..removeStatusListener(_statusChangeHandler) diff --git a/packages/flutter/lib/src/cupertino/date_picker.dart b/packages/flutter/lib/src/cupertino/date_picker.dart index b4d4b83ae82..8d22bd17a01 100644 --- a/packages/flutter/lib/src/cupertino/date_picker.dart +++ b/packages/flutter/lib/src/cupertino/date_picker.dart @@ -414,20 +414,18 @@ class CupertinoDatePicker extends StatefulWidget { final double itemExtent; @override - State createState() { // ignore: no_logic_in_create_state, https://github.com/flutter/flutter/issues/70499 - // The `time` mode and `dateAndTime` mode of the picker share the time - // columns, so they are placed together to one state. - // The `date` mode has different children and is implemented in a different - // state. - switch (mode) { - case CupertinoDatePickerMode.time: - case CupertinoDatePickerMode.dateAndTime: - return _CupertinoDatePickerDateTimeState(); - case CupertinoDatePickerMode.date: - return _CupertinoDatePickerDateState(dateOrder: dateOrder); - case CupertinoDatePickerMode.monthYear: - return _CupertinoDatePickerMonthYearState(dateOrder: dateOrder); - } + State createState() { + // ignore: no_logic_in_create_state, https://github.com/flutter/flutter/issues/70499 + return switch (mode) { + // The `time` mode and `dateAndTime` mode of the picker share the time + // columns, so they are placed together to one state. + // The `date` mode has different children and is implemented in a different + // state. + CupertinoDatePickerMode.time => _CupertinoDatePickerDateTimeState(), + CupertinoDatePickerMode.dateAndTime => _CupertinoDatePickerDateTimeState(), + CupertinoDatePickerMode.date => _CupertinoDatePickerDateState(dateOrder: dateOrder), + CupertinoDatePickerMode.monthYear => _CupertinoDatePickerMonthYearState(dateOrder: dateOrder), + }; } // Estimate the minimum width that each column needs to layout its content. diff --git a/packages/flutter/lib/src/cupertino/list_tile.dart b/packages/flutter/lib/src/cupertino/list_tile.dart index 83c542f3ba2..31f8bd77a0c 100644 --- a/packages/flutter/lib/src/cupertino/list_tile.dart +++ b/packages/flutter/lib/src/cupertino/list_tile.dart @@ -287,15 +287,12 @@ class _CupertinoListTileState extends State { child: widget.title, ); - 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 when widget.subtitle != null => _kPaddingWithSubtitle, + _CupertinoListTileType.notched when widget.leading != null => _kNotchedPadding, + _CupertinoListTileType.base => _kPadding, + _CupertinoListTileType.notched => _kNotchedPaddingWithoutLeading, + }; Widget? subtitle; if (widget.subtitle != null) { @@ -325,13 +322,12 @@ class _CupertinoListTileState extends State { backgroundColor = widget.backgroundColorActivated ?? CupertinoColors.systemGrey4.resolveFrom(context); } - double minHeight; - switch (widget._type) { - case _CupertinoListTileType.base: - minHeight = subtitle == null ? _kMinHeight : _kMinHeightWithSubtitle; - case _CupertinoListTileType.notched: - minHeight = widget.leading == null ? _kNotchedMinHeightWithoutLeading : _kNotchedMinHeight; - } + final double minHeight = switch (widget._type) { + _CupertinoListTileType.base when subtitle != null => _kMinHeightWithSubtitle, + _CupertinoListTileType.notched when widget.leading != null => _kNotchedMinHeight, + _CupertinoListTileType.base => _kMinHeight, + _CupertinoListTileType.notched => _kNotchedMinHeightWithoutLeading, + }; final Widget child = Container( constraints: BoxConstraints(minWidth: double.infinity, minHeight: minHeight), diff --git a/packages/flutter/lib/src/cupertino/route.dart b/packages/flutter/lib/src/cupertino/route.dart index 188ac7b8635..1a3d8fb5226 100644 --- a/packages/flutter/lib/src/cupertino/route.dart +++ b/packages/flutter/lib/src/cupertino/route.dart @@ -975,16 +975,10 @@ class _CupertinoEdgeShadowPainter extends BoxPainter { final TextDirection? textDirection = configuration.textDirection; assert(textDirection != null); - final double start; - final double shadowDirection; // -1 for ltr, 1 for rtl. - switch (textDirection!) { - case TextDirection.rtl: - start = offset.dx + configuration.size!.width; - shadowDirection = 1; - case TextDirection.ltr: - start = offset.dx; - shadowDirection = -1; - } + final (double shadowDirection, double start) = switch (textDirection!) { + TextDirection.rtl => (1, offset.dx + configuration.size!.width), + TextDirection.ltr => (-1, offset.dx), + }; int bandColorIndex = 0; for (int dx = 0; dx < shadowWidth; dx += 1) { diff --git a/packages/flutter/lib/src/cupertino/scrollbar.dart b/packages/flutter/lib/src/cupertino/scrollbar.dart index b3423554319..764c76689cb 100644 --- a/packages/flutter/lib/src/cupertino/scrollbar.dart +++ b/packages/flutter/lib/src/cupertino/scrollbar.dart @@ -174,12 +174,10 @@ class _CupertinoScrollbarState extends RawScrollbarState { if (direction == null) { return; } - switch (direction) { - case Axis.vertical: - _pressStartAxisPosition = localPosition.dy; - case Axis.horizontal: - _pressStartAxisPosition = localPosition.dx; - } + _pressStartAxisPosition = switch (direction) { + Axis.vertical => localPosition.dy, + Axis.horizontal => localPosition.dx, + }; } @override diff --git a/packages/flutter/lib/src/cupertino/slider.dart b/packages/flutter/lib/src/cupertino/slider.dart index 12d35940ae2..94c967173cb 100644 --- a/packages/flutter/lib/src/cupertino/slider.dart +++ b/packages/flutter/lib/src/cupertino/slider.dart @@ -503,19 +503,10 @@ class _RenderCupertinoSlider extends RenderConstrainedBox implements MouseTracke @override void paint(PaintingContext context, Offset offset) { - final double visualPosition; - final Color leftColor; - final Color rightColor; - switch (textDirection) { - case TextDirection.rtl: - visualPosition = 1.0 - _position.value; - leftColor = _activeColor; - rightColor = trackColor; - case TextDirection.ltr: - visualPosition = _position.value; - leftColor = trackColor; - rightColor = _activeColor; - } + final (double visualPosition, Color leftColor, Color rightColor) = switch (textDirection) { + TextDirection.rtl => (1.0 - _position.value, _activeColor, trackColor), + TextDirection.ltr => (_position.value, trackColor, _activeColor), + }; final double trackCenter = offset.dy + size.height / 2.0; final double trackLeft = offset.dx + _trackLeft; diff --git a/packages/flutter/lib/src/material/button_bar.dart b/packages/flutter/lib/src/material/button_bar.dart index 46b646652ce..10c7b0a8b5f 100644 --- a/packages/flutter/lib/src/material/button_bar.dart +++ b/packages/flutter/lib/src/material/button_bar.dart @@ -429,12 +429,10 @@ class _RenderButtonBarRow extends RenderFlex { } } currentHeight += child.size.height; - switch (verticalDirection) { - case VerticalDirection.down: - child = childParentData.nextSibling; - case VerticalDirection.up: - child = childParentData.previousSibling; - } + child = switch (verticalDirection) { + VerticalDirection.down => childParentData.nextSibling, + VerticalDirection.up => childParentData.previousSibling, + }; if (overflowButtonSpacing != null && child != null) { currentHeight += overflowButtonSpacing!; diff --git a/packages/flutter/lib/src/material/button_theme.dart b/packages/flutter/lib/src/material/button_theme.dart index 4a27a398a54..8840820d941 100644 --- a/packages/flutter/lib/src/material/button_theme.dart +++ b/packages/flutter/lib/src/material/button_theme.dart @@ -617,21 +617,11 @@ class ButtonThemeData with Diagnosticable { /// [getTextTheme] is [ButtonTextTheme.primary], 16.0 on the left and right /// otherwise. EdgeInsetsGeometry getPadding(MaterialButton button) { - if (button.padding != null) { - return button.padding!; - } - - if (_padding != null) { - return _padding; - } - - switch (getTextTheme(button)) { - case ButtonTextTheme.normal: - case ButtonTextTheme.accent: - return const EdgeInsets.symmetric(horizontal: 16.0); - case ButtonTextTheme.primary: - return const EdgeInsets.symmetric(horizontal: 24.0); - } + return button.padding ?? _padding ?? switch (getTextTheme(button)) { + ButtonTextTheme.normal => const EdgeInsets.symmetric(horizontal: 16.0), + ButtonTextTheme.accent => const EdgeInsets.symmetric(horizontal: 16.0), + ButtonTextTheme.primary => const EdgeInsets.symmetric(horizontal: 24.0), + }; } /// The shape of the [button]'s [Material]. diff --git a/packages/flutter/lib/src/material/card.dart b/packages/flutter/lib/src/material/card.dart index 07581daacf5..36a01d0c34f 100644 --- a/packages/flutter/lib/src/material/card.dart +++ b/packages/flutter/lib/src/material/card.dart @@ -213,14 +213,11 @@ class Card extends StatelessWidget { final CardTheme cardTheme = CardTheme.of(context); final CardTheme defaults; if (Theme.of(context).useMaterial3) { - switch (_variant) { - case _CardVariant.elevated: - defaults = _CardDefaultsM3(context); - case _CardVariant.filled: - defaults = _FilledCardDefaultsM3(context); - case _CardVariant.outlined: - defaults = _OutlinedCardDefaultsM3(context); - } + defaults = switch (_variant) { + _CardVariant.elevated => _CardDefaultsM3(context), + _CardVariant.filled => _FilledCardDefaultsM3(context), + _CardVariant.outlined => _OutlinedCardDefaultsM3(context), + }; } else { defaults = _CardDefaultsM2(context); } diff --git a/packages/flutter/lib/src/material/checkbox_list_tile.dart b/packages/flutter/lib/src/material/checkbox_list_tile.dart index 8d8648d40b0..0c87dda8194 100644 --- a/packages/flutter/lib/src/material/checkbox_list_tile.dart +++ b/packages/flutter/lib/src/material/checkbox_list_tile.dart @@ -518,16 +518,10 @@ class CheckboxListTile extends StatelessWidget { ); } - Widget? leading, trailing; - switch (controlAffinity) { - case ListTileControlAffinity.leading: - leading = control; - trailing = secondary; - case ListTileControlAffinity.trailing: - case ListTileControlAffinity.platform: - leading = secondary; - trailing = control; - } + final (Widget? leading, Widget? trailing) = switch (controlAffinity) { + ListTileControlAffinity.leading => (control, secondary), + ListTileControlAffinity.trailing || ListTileControlAffinity.platform => (secondary, control), + }; final ThemeData theme = Theme.of(context); final CheckboxThemeData checkboxTheme = CheckboxTheme.of(context); final Set states = { diff --git a/packages/flutter/lib/src/material/drawer.dart b/packages/flutter/lib/src/material/drawer.dart index 9ad5d5ddcbd..84dcc77d342 100644 --- a/packages/flutter/lib/src/material/drawer.dart +++ b/packages/flutter/lib/src/material/drawer.dart @@ -646,35 +646,24 @@ class DrawerControllerState extends State with SingleTickerPro } AlignmentDirectional get _drawerOuterAlignment { - switch (widget.alignment) { - case DrawerAlignment.start: - return AlignmentDirectional.centerStart; - case DrawerAlignment.end: - return AlignmentDirectional.centerEnd; - } + return switch (widget.alignment) { + DrawerAlignment.start => AlignmentDirectional.centerStart, + DrawerAlignment.end => AlignmentDirectional.centerEnd, + }; } AlignmentDirectional get _drawerInnerAlignment { - switch (widget.alignment) { - case DrawerAlignment.start: - return AlignmentDirectional.centerEnd; - case DrawerAlignment.end: - return AlignmentDirectional.centerStart; - } + return switch (widget.alignment) { + DrawerAlignment.start => AlignmentDirectional.centerEnd, + DrawerAlignment.end => AlignmentDirectional.centerStart, + }; } Widget _buildDrawer(BuildContext context) { - final bool isDesktop; - switch (Theme.of(context).platform) { - case TargetPlatform.android: - case TargetPlatform.iOS: - case TargetPlatform.fuchsia: - isDesktop = false; - case TargetPlatform.macOS: - case TargetPlatform.linux: - case TargetPlatform.windows: - isDesktop = true; - } + final bool isDesktop = switch (Theme.of(context).platform) { + TargetPlatform.android || TargetPlatform.iOS || TargetPlatform.fuchsia => false, + TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => true, + }; final double dragAreaWidth = widget.edgeDragWidth ?? _kEdgeDragWidth + switch ((widget.alignment, Directionality.of(context))) { diff --git a/packages/flutter/lib/src/material/dropdown_menu.dart b/packages/flutter/lib/src/material/dropdown_menu.dart index 88b291970f5..0ec91f143ab 100644 --- a/packages/flutter/lib/src/material/dropdown_menu.dart +++ b/packages/flutter/lib/src/material/dropdown_menu.dart @@ -484,22 +484,11 @@ class _DropdownMenuState extends State> { } bool canRequestFocus() { - if (widget.focusNode != null) { - return widget.focusNode!.canRequestFocus; - } - if (widget.requestFocusOnTap != null) { - return widget.requestFocusOnTap!; - } - switch (Theme.of(context).platform) { - case TargetPlatform.iOS: - case TargetPlatform.android: - case TargetPlatform.fuchsia: - return false; - case TargetPlatform.macOS: - case TargetPlatform.linux: - case TargetPlatform.windows: - return true; - } + return widget.focusNode?.canRequestFocus ?? widget.requestFocusOnTap + ?? switch (Theme.of(context).platform) { + TargetPlatform.iOS || TargetPlatform.android || TargetPlatform.fuchsia => false, + TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => true, + }; } void refreshLeadingPadding() { diff --git a/packages/flutter/lib/src/material/ink_well.dart b/packages/flutter/lib/src/material/ink_well.dart index 8b92f28a9d9..97962aa6934 100644 --- a/packages/flutter/lib/src/material/ink_well.dart +++ b/packages/flutter/lib/src/material/ink_well.dart @@ -982,19 +982,13 @@ class _InkResponseState extends State<_InkResponseStateWidget> if (value) { if (highlight == null) { - Color? resolvedOverlayColor = widget.overlayColor?.resolve(statesController.value); - if (resolvedOverlayColor == null) { - // Use the backwards compatible defaults - final ThemeData theme = Theme.of(context); - switch (type) { - case _HighlightType.pressed: - resolvedOverlayColor = widget.highlightColor ?? theme.highlightColor; - case _HighlightType.focus: - resolvedOverlayColor = widget.focusColor ?? theme.focusColor; - case _HighlightType.hover: - resolvedOverlayColor = widget.hoverColor ?? theme.hoverColor; - } - } + final Color resolvedOverlayColor = widget.overlayColor?.resolve(statesController.value) + ?? switch (type) { + // Use the backwards compatible defaults + _HighlightType.pressed => widget.highlightColor ?? Theme.of(context).highlightColor, + _HighlightType.focus => widget.focusColor ?? Theme.of(context).focusColor, + _HighlightType.hover => widget.hoverColor ?? Theme.of(context).hoverColor, + }; final RenderBox referenceBox = context.findRenderObject()! as RenderBox; _highlights[type] = InkHighlight( controller: Material.of(context), @@ -1094,23 +1088,17 @@ class _InkResponseState extends State<_InkResponseStateWidget> } bool get _shouldShowFocus { - final NavigationMode mode = MediaQuery.maybeNavigationModeOf(context) ?? NavigationMode.traditional; - switch (mode) { - case NavigationMode.traditional: - return enabled && _hasFocus; - case NavigationMode.directional: - return _hasFocus; - } + return switch (MediaQuery.maybeNavigationModeOf(context)) { + NavigationMode.traditional || null => enabled && _hasFocus, + NavigationMode.directional => _hasFocus, + }; } void updateFocusHighlights() { - final bool showFocus; - switch (FocusManager.instance.highlightMode) { - case FocusHighlightMode.touch: - showFocus = false; - case FocusHighlightMode.traditional: - showFocus = _shouldShowFocus; - } + final bool showFocus = switch (FocusManager.instance.highlightMode) { + FocusHighlightMode.touch => false, + FocusHighlightMode.traditional => _shouldShowFocus, + }; updateHighlight(_HighlightType.focus, value: showFocus); } @@ -1283,13 +1271,10 @@ class _InkResponseState extends State<_InkResponseStateWidget> } bool get _canRequestFocus { - final NavigationMode mode = MediaQuery.maybeNavigationModeOf(context) ?? NavigationMode.traditional; - switch (mode) { - case NavigationMode.traditional: - return enabled && widget.canRequestFocus; - case NavigationMode.directional: - return true; - } + return switch (MediaQuery.maybeNavigationModeOf(context)) { + NavigationMode.traditional || null => enabled && widget.canRequestFocus, + NavigationMode.directional => true, + }; } @override @@ -1303,17 +1288,14 @@ class _InkResponseState extends State<_InkResponseStateWidget> const Set hovered = {MaterialState.hovered}; final ThemeData theme = Theme.of(context); - switch (type) { + return switch (type) { // The pressed state triggers a ripple (ink splash), per the current // Material Design spec. A separate highlight is no longer used. // See https://material.io/design/interaction/states.html#pressed - case _HighlightType.pressed: - return widget.overlayColor?.resolve(pressed) ?? widget.highlightColor ?? theme.highlightColor; - case _HighlightType.focus: - return widget.overlayColor?.resolve(focused) ?? widget.focusColor ?? theme.focusColor; - case _HighlightType.hover: - return widget.overlayColor?.resolve(hovered) ?? widget.hoverColor ?? theme.hoverColor; - } + _HighlightType.pressed => widget.overlayColor?.resolve(pressed) ?? widget.highlightColor ?? theme.highlightColor, + _HighlightType.focus => widget.overlayColor?.resolve(focused) ?? widget.focusColor ?? theme.focusColor, + _HighlightType.hover => widget.overlayColor?.resolve(hovered) ?? widget.hoverColor ?? theme.hoverColor, + }; } for (final _HighlightType type in _highlights.keys) { _highlights[type]?.color = getHighlightColorForType(type); diff --git a/packages/flutter/lib/src/material/list_tile.dart b/packages/flutter/lib/src/material/list_tile.dart index dc3cb8bbefe..64d9f66e2cd 100644 --- a/packages/flutter/lib/src/material/list_tile.dart +++ b/packages/flutter/lib/src/material/list_tile.dart @@ -1507,14 +1507,13 @@ class _LisTileDefaultsM2 extends ListTileThemeData { @override Color? get iconColor { - switch (_theme.brightness) { - case Brightness.light: - // For the sake of backwards compatibility, the default for unselected - // tiles is Colors.black45 rather than colorScheme.onSurface.withAlpha(0x73). - return Colors.black45; - case Brightness.dark: - return null; // null, Use current icon theme color - } + return switch (_theme.brightness) { + // For the sake of backwards compatibility, the default for unselected + // tiles is Colors.black45 rather than colorScheme.onSurface.withAlpha(0x73). + Brightness.light => Colors.black45, + // null -> use current icon theme color + Brightness.dark => null, + }; } } diff --git a/packages/flutter/lib/src/material/menu_anchor.dart b/packages/flutter/lib/src/material/menu_anchor.dart index ff0c95d3a78..ab05d34e717 100644 --- a/packages/flutter/lib/src/material/menu_anchor.dart +++ b/packages/flutter/lib/src/material/menu_anchor.dart @@ -3360,16 +3360,10 @@ class _MenuPanelState extends State<_MenuPanel> { @override Widget build(BuildContext context) { - final MenuStyle? themeStyle; - final MenuStyle defaultStyle; - switch (widget.orientation) { - case Axis.horizontal: - themeStyle = MenuBarTheme.of(context).style; - defaultStyle = _MenuBarDefaultsM3(context); - case Axis.vertical: - themeStyle = MenuTheme.of(context).style; - defaultStyle = _MenuDefaultsM3(context); - } + final (MenuStyle? themeStyle, MenuStyle defaultStyle) = switch (widget.orientation) { + Axis.horizontal => (MenuBarTheme.of(context).style, _MenuBarDefaultsM3(context)), + Axis.vertical => (MenuTheme.of(context).style, _MenuDefaultsM3(context)), + }; final MenuStyle? widgetStyle = widget.menuStyle; T? effectiveValue(T? Function(MenuStyle? style) getProperty) { @@ -3518,16 +3512,10 @@ class _Submenu extends StatelessWidget { Widget build(BuildContext context) { // Use the text direction of the context where the button is. final TextDirection textDirection = Directionality.of(context); - final MenuStyle? themeStyle; - final MenuStyle defaultStyle; - switch (anchor._parent?._orientation ?? Axis.horizontal) { - case Axis.horizontal: - themeStyle = MenuBarTheme.of(context).style; - defaultStyle = _MenuBarDefaultsM3(context); - case Axis.vertical: - themeStyle = MenuTheme.of(context).style; - defaultStyle = _MenuDefaultsM3(context); - } + final (MenuStyle? themeStyle, MenuStyle defaultStyle) = switch (anchor._parent?._orientation) { + Axis.horizontal || null => (MenuBarTheme.of(context).style, _MenuBarDefaultsM3(context)), + Axis.vertical => (MenuTheme.of(context).style, _MenuDefaultsM3(context)), + }; T? effectiveValue(T? Function(MenuStyle? style) getProperty) { return getProperty(menuStyle) ?? getProperty(themeStyle) ?? getProperty(defaultStyle); } diff --git a/packages/flutter/lib/src/material/search_anchor.dart b/packages/flutter/lib/src/material/search_anchor.dart index 089f18aec0c..70184692b95 100644 --- a/packages/flutter/lib/src/material/search_anchor.dart +++ b/packages/flutter/lib/src/material/search_anchor.dart @@ -442,20 +442,10 @@ class _SearchAnchorState extends State { } bool getShowFullScreenView() { - if (widget.isFullScreen != null) { - return widget.isFullScreen!; - } - - switch (Theme.of(context).platform) { - case TargetPlatform.iOS: - case TargetPlatform.android: - case TargetPlatform.fuchsia: - return true; - case TargetPlatform.macOS: - case TargetPlatform.linux: - case TargetPlatform.windows: - return false; - } + return widget.isFullScreen ?? switch (Theme.of(context).platform) { + TargetPlatform.iOS || TargetPlatform.android || TargetPlatform.fuchsia => true, + TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => false, + }; } @override diff --git a/packages/flutter/lib/src/material/slider.dart b/packages/flutter/lib/src/material/slider.dart index 93998d7f808..0719926cf6f 100644 --- a/packages/flutter/lib/src/material/slider.dart +++ b/packages/flutter/lib/src/material/slider.dart @@ -1629,22 +1629,16 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { @override void paint(PaintingContext context, Offset offset) { - final double value = _state.positionController.value; - final double? secondaryValue = _secondaryTrackValue; + final double controllerValue = _state.positionController.value; // The visual position is the position of the thumb from 0 to 1 from left // to right. In left to right, this is the same as the value, but it is // reversed for right to left text. - final double visualPosition; - final double? secondaryVisualPosition; - switch (textDirection) { - case TextDirection.rtl: - visualPosition = 1.0 - value; - secondaryVisualPosition = (secondaryValue != null) ? (1.0 - secondaryValue) : null; - case TextDirection.ltr: - visualPosition = value; - secondaryVisualPosition = (secondaryValue != null) ? secondaryValue : null; - } + final (double visualPosition, double? secondaryVisualPosition) = switch (textDirection) { + TextDirection.rtl when _secondaryTrackValue == null => (1.0 - controllerValue, null), + TextDirection.rtl => (1.0 - controllerValue, 1.0 - _secondaryTrackValue!), + TextDirection.ltr => (controllerValue, _secondaryTrackValue), + }; final Rect trackRect = _sliderTheme.trackShape!.getPreferredRect( parentBox: this, diff --git a/packages/flutter/lib/src/material/slider_theme.dart b/packages/flutter/lib/src/material/slider_theme.dart index 2172baedc10..f22c33d9b1a 100644 --- a/packages/flutter/lib/src/material/slider_theme.dart +++ b/packages/flutter/lib/src/material/slider_theme.dart @@ -2096,18 +2096,12 @@ class RoundSliderTickMarkShape extends SliderTickMarkShape { assert(sliderTheme.inactiveTickMarkColor != null); // The paint color of the tick mark depends on its position relative // to the thumb and the text direction. - Color? begin; - Color? end; - switch (textDirection) { - case TextDirection.ltr: - final bool isTickMarkRightOfThumb = center.dx > thumbCenter.dx; - begin = isTickMarkRightOfThumb ? sliderTheme.disabledInactiveTickMarkColor : sliderTheme.disabledActiveTickMarkColor; - end = isTickMarkRightOfThumb ? sliderTheme.inactiveTickMarkColor : sliderTheme.activeTickMarkColor; - case TextDirection.rtl: - final bool isTickMarkLeftOfThumb = center.dx < thumbCenter.dx; - begin = isTickMarkLeftOfThumb ? sliderTheme.disabledInactiveTickMarkColor : sliderTheme.disabledActiveTickMarkColor; - end = isTickMarkLeftOfThumb ? sliderTheme.inactiveTickMarkColor : sliderTheme.activeTickMarkColor; - } + final double xOffset = center.dx - thumbCenter.dx; + final (Color? begin, Color? end) = switch (textDirection) { + TextDirection.ltr when xOffset > 0 => (sliderTheme.disabledInactiveTickMarkColor, sliderTheme.inactiveTickMarkColor), + TextDirection.rtl when xOffset < 0 => (sliderTheme.disabledInactiveTickMarkColor, sliderTheme.inactiveTickMarkColor), + TextDirection.ltr || TextDirection.rtl => (sliderTheme.disabledActiveTickMarkColor, sliderTheme.activeTickMarkColor), + }; final Paint paint = Paint()..color = ColorTween(begin: begin, end: end).evaluate(enableAnimation)!; // The tick marks are tiny circles that are the same height as the track. diff --git a/packages/flutter/lib/src/material/stepper.dart b/packages/flutter/lib/src/material/stepper.dart index 2e6a5659511..23a59c1e72d 100644 --- a/packages/flutter/lib/src/material/stepper.dart +++ b/packages/flutter/lib/src/material/stepper.dart @@ -588,13 +588,10 @@ class _StepperState extends State with TickerProviderStateMixin { ); } - final Color cancelColor; - switch (Theme.of(context).brightness) { - case Brightness.light: - cancelColor = Colors.black54; - case Brightness.dark: - cancelColor = Colors.white70; - } + final Color cancelColor = switch (Theme.of(context).brightness) { + Brightness.light => Colors.black54, + Brightness.dark => Colors.white70, + }; final ThemeData themeData = Theme.of(context); final ColorScheme colorScheme = themeData.colorScheme; @@ -960,12 +957,10 @@ class _StepperState extends State with TickerProviderStateMixin { } return true; }()); - switch (widget.type) { - case StepperType.vertical: - return _buildVertical(); - case StepperType.horizontal: - return _buildHorizontal(); - } + return switch (widget.type) { + StepperType.vertical => _buildVertical(), + StepperType.horizontal => _buildHorizontal(), + }; } } diff --git a/packages/flutter/lib/src/material/text_selection.dart b/packages/flutter/lib/src/material/text_selection.dart index 8bc6a22d3a3..a38ea8af27a 100644 --- a/packages/flutter/lib/src/material/text_selection.dart +++ b/packages/flutter/lib/src/material/text_selection.dart @@ -92,20 +92,11 @@ class MaterialTextSelectionControls extends TextSelectionControls { // [handle] is a circle, with a rectangle in the top left quadrant of that // circle (an onion pointing to 10:30). We rotate [handle] to point // straight up or up-right depending on the handle type. - switch (type) { - case TextSelectionHandleType.left: // points up-right - return Transform.rotate( - angle: math.pi / 2.0, - child: handle, - ); - case TextSelectionHandleType.right: // points up-left - return handle; - case TextSelectionHandleType.collapsed: // points up - return Transform.rotate( - angle: math.pi / 4.0, - child: handle, - ); - } + return switch (type) { + TextSelectionHandleType.left => Transform.rotate(angle: math.pi / 2.0, child: handle), // points up-right + TextSelectionHandleType.right => handle, // points up-left + TextSelectionHandleType.collapsed => Transform.rotate(angle: math.pi / 4.0, child: handle), // points up + }; } /// Gets anchor for material-style text selection handles. diff --git a/packages/flutter/lib/src/material/theme_data.dart b/packages/flutter/lib/src/material/theme_data.dart index f861d535b7f..73b0c2e0810 100644 --- a/packages/flutter/lib/src/material/theme_data.dart +++ b/packages/flutter/lib/src/material/theme_data.dart @@ -2525,17 +2525,10 @@ class VisualDensity with Diagnosticable { /// * [adaptivePlatformDensity] which returns a [VisualDensity] that is /// adaptive based on [defaultTargetPlatform]. static VisualDensity defaultDensityForPlatform(TargetPlatform platform) { - switch (platform) { - case TargetPlatform.android: - case TargetPlatform.iOS: - case TargetPlatform.fuchsia: - break; - case TargetPlatform.linux: - case TargetPlatform.macOS: - case TargetPlatform.windows: - return compact; - } - return VisualDensity.standard; + return switch (platform) { + TargetPlatform.android || TargetPlatform.iOS || TargetPlatform.fuchsia => standard, + TargetPlatform.linux || TargetPlatform.macOS || TargetPlatform.windows => compact, + }; } /// Copy the current [VisualDensity] with the given values replacing the diff --git a/packages/flutter/lib/src/material/time_picker.dart b/packages/flutter/lib/src/material/time_picker.dart index 16a42d2a0ce..283726d5aa3 100644 --- a/packages/flutter/lib/src/material/time_picker.dart +++ b/packages/flutter/lib/src/material/time_picker.dart @@ -1136,13 +1136,10 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { double _getRadiusForTime(TimeOfDay time) { switch (widget.hourMinuteMode) { case _HourMinuteMode.hour: - switch (widget.hourDialType) { - case _HourDialType.twentyFourHourDoubleRing: - return time.hour >= 12 ? 0 : 1; - case _HourDialType.twentyFourHour: - case _HourDialType.twelveHour: - return 1; - } + return switch (widget.hourDialType) { + _HourDialType.twentyFourHourDoubleRing => time.hour >= 12 ? 0 : 1, + _HourDialType.twentyFourHour || _HourDialType.twelveHour => 1, + }; case _HourMinuteMode.minute: return 1; } @@ -2752,14 +2749,11 @@ class _TimePickerState extends State<_TimePicker> with RestorationMixin { final _TimePickerDefaults defaultTheme = theme.useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); final Orientation orientation = _orientation.value ?? MediaQuery.orientationOf(context); final HourFormat timeOfDayHour = hourFormat(of: timeOfDayFormat); - final _HourDialType hourMode; - switch (timeOfDayHour) { - case HourFormat.HH: - case HourFormat.H: - hourMode = theme.useMaterial3 ? _HourDialType.twentyFourHourDoubleRing : _HourDialType.twentyFourHour; - case HourFormat.h: - hourMode = _HourDialType.twelveHour; - } + final _HourDialType hourMode = switch (timeOfDayHour) { + HourFormat.HH || HourFormat.H when theme.useMaterial3 => _HourDialType.twentyFourHourDoubleRing, + HourFormat.HH || HourFormat.H => _HourDialType.twentyFourHour, + HourFormat.h => _HourDialType.twelveHour, + }; final String helpText; final Widget picker; diff --git a/packages/flutter/lib/src/painting/alignment.dart b/packages/flutter/lib/src/painting/alignment.dart index 7509321d75b..e54272945a0 100644 --- a/packages/flutter/lib/src/painting/alignment.dart +++ b/packages/flutter/lib/src/painting/alignment.dart @@ -539,12 +539,10 @@ class AlignmentDirectional extends AlignmentGeometry { @override Alignment resolve(TextDirection? direction) { assert(direction != null, 'Cannot resolve $runtimeType without a TextDirection.'); - switch (direction!) { - case TextDirection.rtl: - return Alignment(-start, y); - case TextDirection.ltr: - return Alignment(start, y); - } + return switch (direction!) { + TextDirection.rtl => Alignment(-start, y), + TextDirection.ltr => Alignment(start, y), + }; } static String _stringify(double start, double y) { @@ -643,12 +641,10 @@ class _MixedAlignment extends AlignmentGeometry { @override Alignment resolve(TextDirection? direction) { assert(direction != null, 'Cannot resolve $runtimeType without a TextDirection.'); - switch (direction!) { - case TextDirection.rtl: - return Alignment(_x - _start, _y); - case TextDirection.ltr: - return Alignment(_x + _start, _y); - } + return switch (direction!) { + TextDirection.rtl => Alignment(_x - _start, _y), + TextDirection.ltr => Alignment(_x + _start, _y), + }; } } diff --git a/packages/flutter/lib/src/painting/basic_types.dart b/packages/flutter/lib/src/painting/basic_types.dart index e8ab537d5f1..a89a8ca3cf1 100644 --- a/packages/flutter/lib/src/painting/basic_types.dart +++ b/packages/flutter/lib/src/painting/basic_types.dart @@ -140,12 +140,10 @@ enum Axis { /// /// * [flipAxisDirection], which does the same thing for [AxisDirection] values. Axis flipAxis(Axis direction) { - switch (direction) { - case Axis.horizontal: - return Axis.vertical; - case Axis.vertical: - return Axis.horizontal; - } + return switch (direction) { + Axis.horizontal => Axis.vertical, + Axis.vertical => Axis.horizontal, + }; } /// A direction in which boxes flow vertically. @@ -276,14 +274,10 @@ enum AxisDirection { /// [AxisDirection.down] and returns [Axis.horizontal] for [AxisDirection.left] /// and [AxisDirection.right]. Axis axisDirectionToAxis(AxisDirection axisDirection) { - switch (axisDirection) { - case AxisDirection.up: - case AxisDirection.down: - return Axis.vertical; - case AxisDirection.left: - case AxisDirection.right: - return Axis.horizontal; - } + return switch (axisDirection) { + AxisDirection.up || AxisDirection.down => Axis.vertical, + AxisDirection.left || AxisDirection.right => Axis.horizontal, + }; } /// Returns the [AxisDirection] in which reading occurs in the given [TextDirection]. @@ -291,12 +285,10 @@ Axis axisDirectionToAxis(AxisDirection axisDirection) { /// Specifically, returns [AxisDirection.left] for [TextDirection.rtl] and /// [AxisDirection.right] for [TextDirection.ltr]. AxisDirection textDirectionToAxisDirection(TextDirection textDirection) { - switch (textDirection) { - case TextDirection.rtl: - return AxisDirection.left; - case TextDirection.ltr: - return AxisDirection.right; - } + return switch (textDirection) { + TextDirection.rtl => AxisDirection.left, + TextDirection.ltr => AxisDirection.right, + }; } /// Returns the opposite of the given [AxisDirection]. @@ -309,16 +301,12 @@ AxisDirection textDirectionToAxisDirection(TextDirection textDirection) { /// /// * [flipAxis], which does the same thing for [Axis] values. AxisDirection flipAxisDirection(AxisDirection axisDirection) { - switch (axisDirection) { - case AxisDirection.up: - return AxisDirection.down; - case AxisDirection.right: - return AxisDirection.left; - case AxisDirection.down: - return AxisDirection.up; - case AxisDirection.left: - return AxisDirection.right; - } + return switch (axisDirection) { + AxisDirection.up => AxisDirection.down, + AxisDirection.right => AxisDirection.left, + AxisDirection.down => AxisDirection.up, + AxisDirection.left => AxisDirection.right, + }; } /// Returns whether traveling along the given axis direction visits coordinates @@ -327,12 +315,8 @@ AxisDirection flipAxisDirection(AxisDirection axisDirection) { /// Specifically, returns true for [AxisDirection.up] and [AxisDirection.left] /// and false for [AxisDirection.down] and [AxisDirection.right]. bool axisDirectionIsReversed(AxisDirection axisDirection) { - switch (axisDirection) { - case AxisDirection.up: - case AxisDirection.left: - return true; - case AxisDirection.down: - case AxisDirection.right: - return false; - } + return switch (axisDirection) { + AxisDirection.up || AxisDirection.left => true, + AxisDirection.down || AxisDirection.right => false, + }; } diff --git a/packages/flutter/lib/src/painting/borders.dart b/packages/flutter/lib/src/painting/borders.dart index 63e7f3bf837..dc67e200129 100644 --- a/packages/flutter/lib/src/painting/borders.dart +++ b/packages/flutter/lib/src/painting/borders.dart @@ -275,19 +275,14 @@ class BorderSide with Diagnosticable { strokeAlign: a.strokeAlign, // == b.strokeAlign ); } - final Color colorA, colorB; - switch (a.style) { - case BorderStyle.solid: - colorA = a.color; - case BorderStyle.none: - colorA = a.color.withAlpha(0x00); - } - switch (b.style) { - case BorderStyle.solid: - colorB = b.color; - case BorderStyle.none: - colorB = b.color.withAlpha(0x00); - } + final Color colorA = switch (a.style) { + BorderStyle.solid => a.color, + BorderStyle.none => a.color.withAlpha(0x00), + }; + final Color colorB = switch (b.style) { + BorderStyle.solid => b.color, + BorderStyle.none => b.color.withAlpha(0x00), + }; if (a.strokeAlign != b.strokeAlign) { return BorderSide( color: Color.lerp(colorA, colorB, t)!, diff --git a/packages/flutter/lib/src/painting/box_border.dart b/packages/flutter/lib/src/painting/box_border.dart index c19441abb60..0155ac9deaa 100644 --- a/packages/flutter/lib/src/painting/box_border.dart +++ b/packages/flutter/lib/src/painting/box_border.dart @@ -1013,16 +1013,11 @@ class BorderDirectional extends BoxBorder { return; } - final BorderSide left, right; assert(textDirection != null, 'Non-uniform BorderDirectional objects require a TextDirection when painting.'); - switch (textDirection!) { - case TextDirection.rtl: - left = end; - right = start; - case TextDirection.ltr: - left = start; - right = end; - } + final (BorderSide left, BorderSide right) = switch (textDirection!) { + TextDirection.rtl => (end, start), + TextDirection.ltr => (start, end), + }; // Allow painting non-uniform borders if the visible colors are uniform. final Set visibleColors = _distinctVisibleColors(); diff --git a/packages/flutter/lib/src/painting/edge_insets.dart b/packages/flutter/lib/src/painting/edge_insets.dart index 5334913e965..9fc54ea26ee 100644 --- a/packages/flutter/lib/src/painting/edge_insets.dart +++ b/packages/flutter/lib/src/painting/edge_insets.dart @@ -64,12 +64,10 @@ abstract class EdgeInsetsGeometry { /// The total offset in the given direction. double along(Axis axis) { - switch (axis) { - case Axis.horizontal: - return horizontal; - case Axis.vertical: - return vertical; - } + return switch (axis) { + Axis.horizontal => horizontal, + Axis.vertical => vertical, + }; } /// The size that this [EdgeInsets] would occupy with an empty interior. @@ -897,12 +895,10 @@ class EdgeInsetsDirectional extends EdgeInsetsGeometry { @override EdgeInsets resolve(TextDirection? direction) { assert(direction != null); - switch (direction!) { - case TextDirection.rtl: - return EdgeInsets.fromLTRB(end, top, start, bottom); - case TextDirection.ltr: - return EdgeInsets.fromLTRB(start, top, end, bottom); - } + return switch (direction!) { + TextDirection.rtl => EdgeInsets.fromLTRB(end, top, start, bottom), + TextDirection.ltr => EdgeInsets.fromLTRB(start, top, end, bottom), + }; } /// Creates a copy of this EdgeInsetsDirectional but with the given @@ -1016,11 +1012,9 @@ class _MixedEdgeInsets extends EdgeInsetsGeometry { @override EdgeInsets resolve(TextDirection? direction) { assert(direction != null); - switch (direction!) { - case TextDirection.rtl: - return EdgeInsets.fromLTRB(_end + _left, _top, _start + _right, _bottom); - case TextDirection.ltr: - return EdgeInsets.fromLTRB(_start + _left, _top, _end + _right, _bottom); - } + return switch (direction!) { + TextDirection.rtl => EdgeInsets.fromLTRB(_end + _left, _top, _start + _right, _bottom), + TextDirection.ltr => EdgeInsets.fromLTRB(_start + _left, _top, _end + _right, _bottom), + }; } } diff --git a/packages/flutter/lib/src/semantics/semantics.dart b/packages/flutter/lib/src/semantics/semantics.dart index 98f55fe0d06..db8b7f6297b 100644 --- a/packages/flutter/lib/src/semantics/semantics.dart +++ b/packages/flutter/lib/src/semantics/semantics.dart @@ -3005,12 +3005,10 @@ class SemanticsNode with DiagnosticableTreeMixin { return const []; } - switch (childOrder) { - case DebugSemanticsDumpOrder.inverseHitTest: - return _children!; - case DebugSemanticsDumpOrder.traversalOrder: - return _childrenInTraversalOrder(); - } + return switch (childOrder) { + DebugSemanticsDumpOrder.inverseHitTest => _children!, + DebugSemanticsDumpOrder.traversalOrder => _childrenInTraversalOrder(), + }; } } @@ -5042,12 +5040,11 @@ AttributedString _concatAttributedString({ return thisAttributedString; } if (thisTextDirection != otherTextDirection && otherTextDirection != null) { - switch (otherTextDirection) { - case TextDirection.rtl: - otherAttributedString = AttributedString(Unicode.RLE) + otherAttributedString + AttributedString(Unicode.PDF); - case TextDirection.ltr: - otherAttributedString = AttributedString(Unicode.LRE) + otherAttributedString + AttributedString(Unicode.PDF); - } + final AttributedString directionEmbedding = switch (otherTextDirection) { + TextDirection.rtl => AttributedString(Unicode.RLE), + TextDirection.ltr => AttributedString(Unicode.LRE), + }; + otherAttributedString = directionEmbedding + otherAttributedString + AttributedString(Unicode.PDF); } if (thisAttributedString.string.isEmpty) { return otherAttributedString; diff --git a/packages/flutter/lib/src/services/binding.dart b/packages/flutter/lib/src/services/binding.dart index 2659e43e167..e6105ed6537 100644 --- a/packages/flutter/lib/src/services/binding.dart +++ b/packages/flutter/lib/src/services/binding.dart @@ -335,30 +335,14 @@ mixin ServicesBinding on BindingBase, SchedulerBinding { // Any transition to itself shouldn't happen. return false; } - switch (starting) { - case AppLifecycleState.detached: - if (ending == AppLifecycleState.resumed || ending == AppLifecycleState.paused) { - return true; - } - case AppLifecycleState.resumed: - // Can't go from resumed to detached directly (must go through paused). - if (ending == AppLifecycleState.inactive) { - return true; - } - case AppLifecycleState.inactive: - if (ending == AppLifecycleState.resumed || ending == AppLifecycleState.hidden) { - return true; - } - case AppLifecycleState.hidden: - if (ending == AppLifecycleState.inactive || ending == AppLifecycleState.paused) { - return true; - } - case AppLifecycleState.paused: - if (ending == AppLifecycleState.hidden || ending == AppLifecycleState.detached) { - return true; - } - } - return false; + return switch (starting) { + // Can't go from resumed to detached directly (must go through paused). + AppLifecycleState.resumed => ending == AppLifecycleState.inactive, + AppLifecycleState.detached => ending == AppLifecycleState.resumed || ending == AppLifecycleState.paused, + AppLifecycleState.inactive => ending == AppLifecycleState.resumed || ending == AppLifecycleState.hidden, + AppLifecycleState.hidden => ending == AppLifecycleState.paused || ending == AppLifecycleState.inactive, + AppLifecycleState.paused => ending == AppLifecycleState.hidden || ending == AppLifecycleState.detached, + }; } @@ -391,19 +375,14 @@ mixin ServicesBinding on BindingBase, SchedulerBinding { } static AppLifecycleState? _parseAppLifecycleMessage(String message) { - switch (message) { - case 'AppLifecycleState.resumed': - return AppLifecycleState.resumed; - case 'AppLifecycleState.inactive': - return AppLifecycleState.inactive; - case 'AppLifecycleState.hidden': - return AppLifecycleState.hidden; - case 'AppLifecycleState.paused': - return AppLifecycleState.paused; - case 'AppLifecycleState.detached': - return AppLifecycleState.detached; - } - return null; + return switch (message) { + 'AppLifecycleState.resumed' => AppLifecycleState.resumed, + 'AppLifecycleState.inactive' => AppLifecycleState.inactive, + 'AppLifecycleState.hidden' => AppLifecycleState.hidden, + 'AppLifecycleState.paused' => AppLifecycleState.paused, + 'AppLifecycleState.detached' => AppLifecycleState.detached, + _ => null, + }; } /// Handles any requests for application exit that may be received on the diff --git a/packages/flutter/lib/src/services/message_codecs.dart b/packages/flutter/lib/src/services/message_codecs.dart index 2b103d9624c..d16bb0906ee 100644 --- a/packages/flutter/lib/src/services/message_codecs.dart +++ b/packages/flutter/lib/src/services/message_codecs.dart @@ -557,14 +557,11 @@ class StandardMessageCodec implements MessageCodec { /// [readValueOfType]. int readSize(ReadBuffer buffer) { final int value = buffer.getUint8(); - switch (value) { - case 254: - return buffer.getUint16(); - case 255: - return buffer.getUint32(); - default: - return value; - } + return switch (value) { + 254 => buffer.getUint16(), + 255 => buffer.getUint32(), + _ => value, + }; } } diff --git a/packages/flutter/lib/src/services/platform_views.dart b/packages/flutter/lib/src/services/platform_views.dart index 15faa35fa01..5dbc2008f52 100644 --- a/packages/flutter/lib/src/services/platform_views.dart +++ b/packages/flutter/lib/src/services/platform_views.dart @@ -660,40 +660,26 @@ class _AndroidMotionEventConverter { } static int sourceFor(PointerEvent event) { - int source = AndroidViewController.kInputDeviceSourceUnknown; - switch (event.kind) { - case PointerDeviceKind.touch: - source = AndroidViewController.kInputDeviceSourceTouchScreen; - case PointerDeviceKind.trackpad: - source = AndroidViewController.kInputDeviceSourceTouchPad; - case PointerDeviceKind.mouse: - source = AndroidViewController.kInputDeviceSourceMouse; - case PointerDeviceKind.stylus: - case PointerDeviceKind.invertedStylus: - source = AndroidViewController.kInputDeviceSourceStylus; - case PointerDeviceKind.unknown: - source = AndroidViewController.kInputDeviceSourceUnknown; - } - return source; + return switch (event.kind) { + PointerDeviceKind.touch => AndroidViewController.kInputDeviceSourceTouchScreen, + PointerDeviceKind.trackpad => AndroidViewController.kInputDeviceSourceTouchPad, + PointerDeviceKind.mouse => AndroidViewController.kInputDeviceSourceMouse, + PointerDeviceKind.stylus => AndroidViewController.kInputDeviceSourceStylus, + PointerDeviceKind.invertedStylus => AndroidViewController.kInputDeviceSourceStylus, + PointerDeviceKind.unknown => AndroidViewController.kInputDeviceSourceUnknown, + }; } AndroidPointerProperties propertiesFor(PointerEvent event, int pointerId) { - int toolType = AndroidPointerProperties.kToolTypeUnknown; - switch (event.kind) { - case PointerDeviceKind.touch: - case PointerDeviceKind.trackpad: - toolType = AndroidPointerProperties.kToolTypeFinger; - case PointerDeviceKind.mouse: - toolType = AndroidPointerProperties.kToolTypeMouse; - case PointerDeviceKind.stylus: - toolType = AndroidPointerProperties.kToolTypeStylus; - case PointerDeviceKind.invertedStylus: - toolType = AndroidPointerProperties.kToolTypeEraser; - case PointerDeviceKind.unknown: - toolType = AndroidPointerProperties.kToolTypeUnknown; - } - return AndroidPointerProperties(id: pointerId, toolType: toolType); + return AndroidPointerProperties(id: pointerId, toolType: switch (event.kind) { + PointerDeviceKind.touch => AndroidPointerProperties.kToolTypeFinger, + PointerDeviceKind.trackpad => AndroidPointerProperties.kToolTypeFinger, + PointerDeviceKind.mouse => AndroidPointerProperties.kToolTypeMouse, + PointerDeviceKind.stylus => AndroidPointerProperties.kToolTypeStylus, + PointerDeviceKind.invertedStylus => AndroidPointerProperties.kToolTypeEraser, + PointerDeviceKind.unknown => AndroidPointerProperties.kToolTypeUnknown, + }); } bool isSinglePointerAction(PointerEvent event) => @@ -793,12 +779,10 @@ abstract class AndroidViewController extends PlatformViewController { []; static int _getAndroidDirection(TextDirection direction) { - switch (direction) { - case TextDirection.ltr: - return kAndroidLayoutDirectionLtr; - case TextDirection.rtl: - return kAndroidLayoutDirectionRtl; - } + return switch (direction) { + TextDirection.ltr => kAndroidLayoutDirectionLtr, + TextDirection.rtl => kAndroidLayoutDirectionRtl, + }; } /// Creates a masked Android MotionEvent action value for an indexed pointer. diff --git a/packages/flutter/lib/src/services/raw_keyboard.dart b/packages/flutter/lib/src/services/raw_keyboard.dart index a2881c8171e..348fe3df419 100644 --- a/packages/flutter/lib/src/services/raw_keyboard.dart +++ b/packages/flutter/lib/src/services/raw_keyboard.dart @@ -488,14 +488,11 @@ abstract class RawKeyEvent with Diagnosticable { } final bool repeat = RawKeyboard.instance.physicalKeysPressed.contains(data.physicalKey); final String type = message['type']! as String; - switch (type) { - case 'keydown': - return RawKeyDownEvent(data: data, character: character, repeat: repeat); - case 'keyup': - return RawKeyUpEvent(data: data); - default: - throw FlutterError('Unknown key event type: $type'); - } + return switch (type) { + 'keydown' => RawKeyDownEvent(data: data, character: character, repeat: repeat), + 'keyup' => RawKeyUpEvent(data: data), + _ => throw FlutterError('Unknown key event type: $type'), + }; } /// Returns true if the given [LogicalKeyboardKey] is pressed. diff --git a/packages/flutter/lib/src/services/raw_keyboard_android.dart b/packages/flutter/lib/src/services/raw_keyboard_android.dart index 9f7b1bbc859..235f013b9bc 100644 --- a/packages/flutter/lib/src/services/raw_keyboard_android.dart +++ b/packages/flutter/lib/src/services/raw_keyboard_android.dart @@ -216,40 +216,27 @@ class RawKeyEventDataAndroid extends RawKeyEventData { if (metaState & anyMask == 0) { return false; } - switch (side) { - case KeyboardSide.any: - return true; - case KeyboardSide.all: - return metaState & leftMask != 0 && metaState & rightMask != 0; - case KeyboardSide.left: - return metaState & leftMask != 0; - case KeyboardSide.right: - return metaState & rightMask != 0; - } + return switch (side) { + KeyboardSide.any => true, + KeyboardSide.all => (metaState & leftMask != 0) && (metaState & rightMask != 0), + KeyboardSide.left => metaState & leftMask != 0, + KeyboardSide.right => metaState & rightMask != 0, + }; } @override bool isModifierPressed(ModifierKey key, { KeyboardSide side = KeyboardSide.any }) { - switch (key) { - case ModifierKey.controlModifier: - return _isLeftRightModifierPressed(side, modifierControl, modifierLeftControl, modifierRightControl); - case ModifierKey.shiftModifier: - return _isLeftRightModifierPressed(side, modifierShift, modifierLeftShift, modifierRightShift); - case ModifierKey.altModifier: - return _isLeftRightModifierPressed(side, modifierAlt, modifierLeftAlt, modifierRightAlt); - case ModifierKey.metaModifier: - return _isLeftRightModifierPressed(side, modifierMeta, modifierLeftMeta, modifierRightMeta); - case ModifierKey.capsLockModifier: - return metaState & modifierCapsLock != 0; - case ModifierKey.numLockModifier: - return metaState & modifierNumLock != 0; - case ModifierKey.scrollLockModifier: - return metaState & modifierScrollLock != 0; - case ModifierKey.functionModifier: - return metaState & modifierFunction != 0; - case ModifierKey.symbolModifier: - return metaState & modifierSym != 0; - } + return switch (key) { + ModifierKey.controlModifier => _isLeftRightModifierPressed(side, modifierControl, modifierLeftControl, modifierRightControl), + ModifierKey.shiftModifier => _isLeftRightModifierPressed(side, modifierShift, modifierLeftShift, modifierRightShift), + ModifierKey.altModifier => _isLeftRightModifierPressed(side, modifierAlt, modifierLeftAlt, modifierRightAlt), + ModifierKey.metaModifier => _isLeftRightModifierPressed(side, modifierMeta, modifierLeftMeta, modifierRightMeta), + ModifierKey.capsLockModifier => metaState & modifierCapsLock != 0, + ModifierKey.numLockModifier => metaState & modifierNumLock != 0, + ModifierKey.scrollLockModifier => metaState & modifierScrollLock != 0, + ModifierKey.functionModifier => metaState & modifierFunction != 0, + ModifierKey.symbolModifier => metaState & modifierSym != 0, + }; } @override diff --git a/packages/flutter/lib/src/services/raw_keyboard_fuchsia.dart b/packages/flutter/lib/src/services/raw_keyboard_fuchsia.dart index 9a297b91b27..a257d6f8649 100644 --- a/packages/flutter/lib/src/services/raw_keyboard_fuchsia.dart +++ b/packages/flutter/lib/src/services/raw_keyboard_fuchsia.dart @@ -99,16 +99,12 @@ class RawKeyEventDataFuchsia extends RawKeyEventData { if (modifiers & anyMask == 0) { return false; } - switch (side) { - case KeyboardSide.any: - return true; - case KeyboardSide.all: - return modifiers & leftMask != 0 && modifiers & rightMask != 0; - case KeyboardSide.left: - return modifiers & leftMask != 0; - case KeyboardSide.right: - return modifiers & rightMask != 0; - } + return switch (side) { + KeyboardSide.any => true, + KeyboardSide.all => (modifiers & leftMask != 0) && (modifiers & rightMask != 0), + KeyboardSide.left => modifiers & leftMask != 0, + KeyboardSide.right => modifiers & rightMask != 0, + }; } @override diff --git a/packages/flutter/lib/src/services/raw_keyboard_linux.dart b/packages/flutter/lib/src/services/raw_keyboard_linux.dart index 26503a20c59..f9035fb7367 100644 --- a/packages/flutter/lib/src/services/raw_keyboard_linux.dart +++ b/packages/flutter/lib/src/services/raw_keyboard_linux.dart @@ -307,27 +307,15 @@ class GLFWKeyHelper implements KeyHelper { // a key down, then we need to add the correct modifier bits, and if it's a // key up, we need to remove them. - int modifierChange = 0; - switch (keyCode) { - case shiftLeftKeyCode: - case shiftRightKeyCode: - modifierChange = modifierShift; - case controlLeftKeyCode: - case controlRightKeyCode: - modifierChange = modifierControl; - case altLeftKeyCode: - case altRightKeyCode: - modifierChange = modifierAlt; - case metaLeftKeyCode: - case metaRightKeyCode: - modifierChange = modifierMeta; - case capsLockKeyCode: - modifierChange = modifierCapsLock; - case numLockKeyCode: - modifierChange = modifierNumericPad; - default: - break; - } + final int modifierChange = switch (keyCode) { + shiftLeftKeyCode || shiftRightKeyCode => modifierShift, + controlLeftKeyCode || controlRightKeyCode => modifierControl, + altLeftKeyCode || altRightKeyCode => modifierAlt, + metaLeftKeyCode || metaRightKeyCode => modifierMeta, + capsLockKeyCode => modifierCapsLock, + numLockKeyCode => modifierNumericPad, + _ => 0, + }; return isDown ? modifiers | modifierChange : modifiers & ~modifierChange; } @@ -335,25 +323,18 @@ class GLFWKeyHelper implements KeyHelper { @override bool isModifierPressed(ModifierKey key, int modifiers, {KeyboardSide side = KeyboardSide.any, required int keyCode, required bool isDown}) { modifiers = _mergeModifiers(modifiers: modifiers, keyCode: keyCode, isDown: isDown); - switch (key) { - case ModifierKey.controlModifier: - return modifiers & modifierControl != 0; - case ModifierKey.shiftModifier: - return modifiers & modifierShift != 0; - case ModifierKey.altModifier: - return modifiers & modifierAlt != 0; - case ModifierKey.metaModifier: - return modifiers & modifierMeta != 0; - case ModifierKey.capsLockModifier: - return modifiers & modifierCapsLock != 0; - case ModifierKey.numLockModifier: - return modifiers & modifierNumericPad != 0; - case ModifierKey.functionModifier: - case ModifierKey.symbolModifier: - case ModifierKey.scrollLockModifier: - // These are not used in GLFW keyboards. - return false; - } + return switch (key) { + ModifierKey.controlModifier => modifiers & modifierControl != 0, + ModifierKey.shiftModifier => modifiers & modifierShift != 0, + ModifierKey.altModifier => modifiers & modifierAlt != 0, + ModifierKey.metaModifier => modifiers & modifierMeta != 0, + ModifierKey.capsLockModifier => modifiers & modifierCapsLock != 0, + ModifierKey.numLockModifier => modifiers & modifierNumericPad != 0, + // These are not used in GLFW keyboards. + ModifierKey.functionModifier => false, + ModifierKey.symbolModifier => false, + ModifierKey.scrollLockModifier => false, + }; } @override @@ -451,28 +432,15 @@ class GtkKeyHelper implements KeyHelper { // a key down, then we need to add the correct modifier bits, and if it's a // key up, we need to remove them. - int modifierChange = 0; - switch (keyCode) { - case shiftLeftKeyCode: - case shiftRightKeyCode: - modifierChange = modifierShift; - case controlLeftKeyCode: - case controlRightKeyCode: - modifierChange = modifierControl; - case altLeftKeyCode: - case altRightKeyCode: - modifierChange = modifierMod1; - case metaLeftKeyCode: - case metaRightKeyCode: - modifierChange = modifierMeta; - case capsLockKeyCode: - case shiftLockKeyCode: - modifierChange = modifierCapsLock; - case numLockKeyCode: - modifierChange = modifierMod2; - default: - break; - } + final int modifierChange = switch (keyCode) { + shiftLeftKeyCode || shiftRightKeyCode => modifierShift, + controlLeftKeyCode || controlRightKeyCode => modifierControl, + altLeftKeyCode || altRightKeyCode => modifierMod1, + metaLeftKeyCode || metaRightKeyCode => modifierMeta, + capsLockKeyCode || shiftLockKeyCode => modifierCapsLock, + numLockKeyCode => modifierMod2, + _ => 0, + }; return isDown ? modifiers | modifierChange : modifiers & ~modifierChange; } @@ -480,25 +448,18 @@ class GtkKeyHelper implements KeyHelper { @override bool isModifierPressed(ModifierKey key, int modifiers, {KeyboardSide side = KeyboardSide.any, required int keyCode, required bool isDown}) { modifiers = _mergeModifiers(modifiers: modifiers, keyCode: keyCode, isDown: isDown); - switch (key) { - case ModifierKey.controlModifier: - return modifiers & modifierControl != 0; - case ModifierKey.shiftModifier: - return modifiers & modifierShift != 0; - case ModifierKey.altModifier: - return modifiers & modifierMod1 != 0; - case ModifierKey.metaModifier: - return modifiers & modifierMeta != 0; - case ModifierKey.capsLockModifier: - return modifiers & modifierCapsLock != 0; - case ModifierKey.numLockModifier: - return modifiers & modifierMod2 != 0; - case ModifierKey.functionModifier: - case ModifierKey.symbolModifier: - case ModifierKey.scrollLockModifier: - // These are not used in GTK keyboards. - return false; - } + return switch (key) { + ModifierKey.controlModifier => modifiers & modifierControl != 0, + ModifierKey.shiftModifier => modifiers & modifierShift != 0, + ModifierKey.altModifier => modifiers & modifierMod1 != 0, + ModifierKey.metaModifier => modifiers & modifierMeta != 0, + ModifierKey.capsLockModifier => modifiers & modifierCapsLock != 0, + ModifierKey.numLockModifier => modifiers & modifierMod2 != 0, + // These are not used in GTK keyboards. + ModifierKey.functionModifier => false, + ModifierKey.symbolModifier => false, + ModifierKey.scrollLockModifier => false, + }; } @override diff --git a/packages/flutter/lib/src/services/raw_keyboard_web.dart b/packages/flutter/lib/src/services/raw_keyboard_web.dart index e361d9aa4fb..c1f575241d8 100644 --- a/packages/flutter/lib/src/services/raw_keyboard_web.dart +++ b/packages/flutter/lib/src/services/raw_keyboard_web.dart @@ -131,30 +131,18 @@ class RawKeyEventDataWeb extends RawKeyEventData { } @override - bool isModifierPressed( - ModifierKey key, { - KeyboardSide side = KeyboardSide.any, - }) { - switch (key) { - case ModifierKey.controlModifier: - return metaState & modifierControl != 0; - case ModifierKey.shiftModifier: - return metaState & modifierShift != 0; - case ModifierKey.altModifier: - return metaState & modifierAlt != 0; - case ModifierKey.metaModifier: - return metaState & modifierMeta != 0; - case ModifierKey.numLockModifier: - return metaState & modifierNumLock != 0; - case ModifierKey.capsLockModifier: - return metaState & modifierCapsLock != 0; - case ModifierKey.scrollLockModifier: - return metaState & modifierScrollLock != 0; - case ModifierKey.functionModifier: - case ModifierKey.symbolModifier: - // On Web, the browser doesn't report the state of the FN and SYM modifiers. - return false; - } + bool isModifierPressed(ModifierKey key, {KeyboardSide side = KeyboardSide.any}) { + return switch (key) { + ModifierKey.controlModifier => metaState & modifierControl != 0, + ModifierKey.shiftModifier => metaState & modifierShift != 0, + ModifierKey.altModifier => metaState & modifierAlt != 0, + ModifierKey.metaModifier => metaState & modifierMeta != 0, + ModifierKey.numLockModifier => metaState & modifierNumLock != 0, + ModifierKey.capsLockModifier => metaState & modifierCapsLock != 0, + ModifierKey.scrollLockModifier => metaState & modifierScrollLock != 0, + // On Web, the browser doesn't report the state of the FN and SYM modifiers. + ModifierKey.functionModifier || ModifierKey.symbolModifier => false, + }; } @override diff --git a/packages/flutter/lib/src/services/text_editing_delta.dart b/packages/flutter/lib/src/services/text_editing_delta.dart index aff97541467..119fbc9689f 100644 --- a/packages/flutter/lib/src/services/text_editing_delta.dart +++ b/packages/flutter/lib/src/services/text_editing_delta.dart @@ -15,13 +15,11 @@ export 'text_editing.dart' show TextSelection; export 'text_input.dart' show TextEditingValue; TextAffinity? _toTextAffinity(String? affinity) { - switch (affinity) { - case 'TextAffinity.downstream': - return TextAffinity.downstream; - case 'TextAffinity.upstream': - return TextAffinity.upstream; - } - return null; + return switch (affinity) { + 'TextAffinity.downstream' => TextAffinity.downstream, + 'TextAffinity.upstream' => TextAffinity.upstream, + _ => null, + }; } // Replaces a range of text in the original string with the text given in the diff --git a/packages/flutter/lib/src/services/text_input.dart b/packages/flutter/lib/src/services/text_input.dart index 18f93c75bf0..9bc5babad1c 100644 --- a/packages/flutter/lib/src/services/text_input.dart +++ b/packages/flutter/lib/src/services/text_input.dart @@ -712,13 +712,11 @@ class TextInputConfiguration { } TextAffinity? _toTextAffinity(String? affinity) { - switch (affinity) { - case 'TextAffinity.downstream': - return TextAffinity.downstream; - case 'TextAffinity.upstream': - return TextAffinity.upstream; - } - return null; + return switch (affinity) { + 'TextAffinity.downstream' => TextAffinity.downstream, + 'TextAffinity.upstream' => TextAffinity.upstream, + _ => null, + }; } /// The state of a "floating cursor" drag on an iOS soft keyboard. @@ -1515,47 +1513,31 @@ class TextInputConnection { } TextInputAction _toTextInputAction(String action) { - switch (action) { - case 'TextInputAction.none': - return TextInputAction.none; - case 'TextInputAction.unspecified': - return TextInputAction.unspecified; - case 'TextInputAction.go': - return TextInputAction.go; - case 'TextInputAction.search': - return TextInputAction.search; - case 'TextInputAction.send': - return TextInputAction.send; - case 'TextInputAction.next': - return TextInputAction.next; - case 'TextInputAction.previous': - return TextInputAction.previous; - case 'TextInputAction.continueAction': - return TextInputAction.continueAction; - case 'TextInputAction.join': - return TextInputAction.join; - case 'TextInputAction.route': - return TextInputAction.route; - case 'TextInputAction.emergencyCall': - return TextInputAction.emergencyCall; - case 'TextInputAction.done': - return TextInputAction.done; - case 'TextInputAction.newline': - return TextInputAction.newline; - } - throw FlutterError.fromParts([ErrorSummary('Unknown text input action: $action')]); + return switch (action) { + 'TextInputAction.none' => TextInputAction.none, + 'TextInputAction.unspecified' => TextInputAction.unspecified, + 'TextInputAction.go' => TextInputAction.go, + 'TextInputAction.search' => TextInputAction.search, + 'TextInputAction.send' => TextInputAction.send, + 'TextInputAction.next' => TextInputAction.next, + 'TextInputAction.previous' => TextInputAction.previous, + 'TextInputAction.continueAction' => TextInputAction.continueAction, + 'TextInputAction.join' => TextInputAction.join, + 'TextInputAction.route' => TextInputAction.route, + 'TextInputAction.emergencyCall' => TextInputAction.emergencyCall, + 'TextInputAction.done' => TextInputAction.done, + 'TextInputAction.newline' => TextInputAction.newline, + _ => throw FlutterError.fromParts([ErrorSummary('Unknown text input action: $action')]), + }; } FloatingCursorDragState _toTextCursorAction(String state) { - switch (state) { - case 'FloatingCursorDragState.start': - return FloatingCursorDragState.Start; - case 'FloatingCursorDragState.update': - return FloatingCursorDragState.Update; - case 'FloatingCursorDragState.end': - return FloatingCursorDragState.End; - } - throw FlutterError.fromParts([ErrorSummary('Unknown text cursor action: $state')]); + return switch (state) { + 'FloatingCursorDragState.start' => FloatingCursorDragState.Start, + 'FloatingCursorDragState.update' => FloatingCursorDragState.Update, + 'FloatingCursorDragState.end' => FloatingCursorDragState.End, + _ => throw FlutterError.fromParts([ErrorSummary('Unknown text cursor action: $state')]), + }; } RawFloatingCursorPoint _toTextPoint(FloatingCursorDragState state, Map encoded) { diff --git a/packages/flutter/lib/src/services/undo_manager.dart b/packages/flutter/lib/src/services/undo_manager.dart index 71837ad24db..7ba33035406 100644 --- a/packages/flutter/lib/src/services/undo_manager.dart +++ b/packages/flutter/lib/src/services/undo_manager.dart @@ -98,13 +98,11 @@ class UndoManager { } UndoDirection _toUndoDirection(String direction) { - switch (direction) { - case 'undo': - return UndoDirection.undo; - case 'redo': - return UndoDirection.redo; - } - throw FlutterError.fromParts([ErrorSummary('Unknown undo direction: $direction')]); + return switch (direction) { + 'undo' => UndoDirection.undo, + 'redo' => UndoDirection.redo, + _ => throw FlutterError.fromParts([ErrorSummary('Unknown undo direction: $direction')]), + }; } } diff --git a/packages/flutter/lib/src/widgets/focus_traversal.dart b/packages/flutter/lib/src/widgets/focus_traversal.dart index 53455c7397a..45059e53d85 100644 --- a/packages/flutter/lib/src/widgets/focus_traversal.dart +++ b/packages/flutter/lib/src/widgets/focus_traversal.dart @@ -1167,14 +1167,13 @@ class _ReadingOrderSortData with Diagnosticable { } static void sortWithDirectionality(List<_ReadingOrderSortData> list, TextDirection directionality) { - mergeSort<_ReadingOrderSortData>(list, compare: (_ReadingOrderSortData a, _ReadingOrderSortData b) { - switch (directionality) { - case TextDirection.ltr: - return a.rect.left.compareTo(b.rect.left); - case TextDirection.rtl: - return b.rect.right.compareTo(a.rect.right); - } - }); + mergeSort<_ReadingOrderSortData>( + list, + compare: (_ReadingOrderSortData a, _ReadingOrderSortData b) => switch (directionality) { + TextDirection.ltr => a.rect.left.compareTo(b.rect.left), + TextDirection.rtl => b.rect.right.compareTo(a.rect.right), + }, + ); } /// Returns the list of Directionality ancestors, in order from nearest to @@ -1238,14 +1237,13 @@ class _ReadingOrderDirectionalGroupData with Diagnosticable { List? _memberAncestors; static void sortWithDirectionality(List<_ReadingOrderDirectionalGroupData> list, TextDirection directionality) { - mergeSort<_ReadingOrderDirectionalGroupData>(list, compare: (_ReadingOrderDirectionalGroupData a, _ReadingOrderDirectionalGroupData b) { - switch (directionality) { - case TextDirection.ltr: - return a.rect.left.compareTo(b.rect.left); - case TextDirection.rtl: - return b.rect.right.compareTo(a.rect.right); - } - }); + mergeSort<_ReadingOrderDirectionalGroupData>( + list, + compare: (_ReadingOrderDirectionalGroupData a, _ReadingOrderDirectionalGroupData b) => switch (directionality) { + TextDirection.ltr => a.rect.left.compareTo(b.rect.left), + TextDirection.rtl => b.rect.right.compareTo(a.rect.right), + }, + ); } @override diff --git a/packages/flutter/lib/src/widgets/interactive_viewer.dart b/packages/flutter/lib/src/widgets/interactive_viewer.dart index 9ed589af7bb..baa8ec12b0e 100644 --- a/packages/flutter/lib/src/widgets/interactive_viewer.dart +++ b/packages/flutter/lib/src/widgets/interactive_viewer.dart @@ -600,19 +600,15 @@ class _InteractiveViewerState extends State with TickerProvid return matrix.clone(); } - late final Offset alignedTranslation; + final Offset alignedTranslation; if (_currentAxis != null) { - switch (widget.panAxis){ - case PanAxis.horizontal: - alignedTranslation = _alignAxis(translation, Axis.horizontal); - case PanAxis.vertical: - alignedTranslation = _alignAxis(translation, Axis.vertical); - case PanAxis.aligned: - alignedTranslation = _alignAxis(translation, _currentAxis!); - case PanAxis.free: - alignedTranslation = translation; - } + alignedTranslation = switch (widget.panAxis){ + PanAxis.horizontal => _alignAxis(translation, Axis.horizontal), + PanAxis.vertical => _alignAxis(translation, Axis.vertical), + PanAxis.aligned => _alignAxis(translation, _currentAxis!), + PanAxis.free => translation, + }; } else { alignedTranslation = translation; } @@ -739,17 +735,11 @@ class _InteractiveViewerState extends State with TickerProvid // Returns true iff the given _GestureType is enabled. bool _gestureIsSupported(_GestureType? gestureType) { - switch (gestureType) { - case _GestureType.rotate: - return _rotateEnabled; - - case _GestureType.scale: - return widget.scaleEnabled; - - case _GestureType.pan: - case null: - return widget.panEnabled; - } + return switch (gestureType) { + _GestureType.rotate => _rotateEnabled, + _GestureType.scale => widget.scaleEnabled, + _GestureType.pan || null => widget.panEnabled, + }; } // Decide which type of gesture this is by comparing the amount of scale @@ -1448,12 +1438,10 @@ Offset _round(Offset offset) { // Align the given offset to the given axis by allowing movement only in the // axis direction. Offset _alignAxis(Offset offset, Axis axis) { - switch (axis) { - case Axis.horizontal: - return Offset(offset.dx, 0.0); - case Axis.vertical: - return Offset(0.0, offset.dy); - } + return switch (axis) { + Axis.horizontal => Offset(offset.dx, 0.0), + Axis.vertical => Offset(0.0, offset.dy), + }; } // Given two points, return the axis where the distance between the points is diff --git a/packages/flutter/lib/src/widgets/scroll_physics.dart b/packages/flutter/lib/src/widgets/scroll_physics.dart index ef8ca02b0a1..322d4281343 100644 --- a/packages/flutter/lib/src/widgets/scroll_physics.dart +++ b/packages/flutter/lib/src/widgets/scroll_physics.dart @@ -743,13 +743,6 @@ class BouncingScrollPhysics extends ScrollPhysics { Simulation? createBallisticSimulation(ScrollMetrics position, double velocity) { final Tolerance tolerance = toleranceFor(position); if (velocity.abs() >= tolerance.velocity || position.outOfRange) { - double constantDeceleration; - switch (decelerationRate) { - case ScrollDecelerationRate.fast: - constantDeceleration = 1400; - case ScrollDecelerationRate.normal: - constantDeceleration = 0; - } return BouncingScrollSimulation( spring: spring, position: position.pixels, @@ -757,7 +750,10 @@ class BouncingScrollPhysics extends ScrollPhysics { leadingExtent: position.minScrollExtent, trailingExtent: position.maxScrollExtent, tolerance: tolerance, - constantDeceleration: constantDeceleration + constantDeceleration: switch (decelerationRate) { + ScrollDecelerationRate.fast => 1400, + ScrollDecelerationRate.normal => 0, + }, ); } return null; @@ -795,12 +791,10 @@ class BouncingScrollPhysics extends ScrollPhysics { @override double get maxFlingVelocity { - switch (decelerationRate) { - case ScrollDecelerationRate.fast: - return kMaxFlingVelocity * 8.0; - case ScrollDecelerationRate.normal: - return super.maxFlingVelocity; - } + return switch (decelerationRate) { + ScrollDecelerationRate.fast => kMaxFlingVelocity * 8.0, + ScrollDecelerationRate.normal => super.maxFlingVelocity, + }; } @override diff --git a/packages/flutter/lib/src/widgets/scroll_position.dart b/packages/flutter/lib/src/widgets/scroll_position.dart index 2a03d15e0eb..5a995b2feb5 100644 --- a/packages/flutter/lib/src/widgets/scroll_position.dart +++ b/packages/flutter/lib/src/widgets/scroll_position.dart @@ -722,22 +722,12 @@ abstract class ScrollPosition extends ViewportOffset with ScrollMetrics { /// scroll view dimensions both change) and therefore shouldn't do anything /// expensive. void _updateSemanticActions() { - final SemanticsAction forward; - final SemanticsAction backward; - switch (axisDirection) { - case AxisDirection.up: - forward = SemanticsAction.scrollDown; - backward = SemanticsAction.scrollUp; - case AxisDirection.right: - forward = SemanticsAction.scrollLeft; - backward = SemanticsAction.scrollRight; - case AxisDirection.down: - forward = SemanticsAction.scrollUp; - backward = SemanticsAction.scrollDown; - case AxisDirection.left: - forward = SemanticsAction.scrollRight; - backward = SemanticsAction.scrollLeft; - } + final (SemanticsAction forward, SemanticsAction backward) = switch (axisDirection) { + AxisDirection.up => (SemanticsAction.scrollDown, SemanticsAction.scrollUp), + AxisDirection.down => (SemanticsAction.scrollUp, SemanticsAction.scrollDown), + AxisDirection.left => (SemanticsAction.scrollRight, SemanticsAction.scrollLeft), + AxisDirection.right => (SemanticsAction.scrollLeft, SemanticsAction.scrollRight), + }; final Set actions = {}; if (pixels > minScrollExtent) { diff --git a/packages/flutter/lib/src/widgets/scrollable.dart b/packages/flutter/lib/src/widgets/scrollable.dart index 76436807738..f86e24efdff 100644 --- a/packages/flutter/lib/src/widgets/scrollable.dart +++ b/packages/flutter/lib/src/widgets/scrollable.dart @@ -548,16 +548,12 @@ class ScrollableState extends State with TickerProviderStateMixin, R /// Used by [EdgeDraggingAutoScroller] to progress the position forward when a /// drag gesture reaches the edge of the [Viewport]. Offset get deltaToScrollOrigin { - switch (axisDirection) { - case AxisDirection.down: - return Offset(0, position.pixels); - case AxisDirection.up: - return Offset(0, -position.pixels); - case AxisDirection.left: - return Offset(-position.pixels, 0); - case AxisDirection.right: - return Offset(position.pixels, 0); - } + return switch (axisDirection) { + AxisDirection.up => Offset(0, -position.pixels), + AxisDirection.down => Offset(0, position.pixels), + AxisDirection.left => Offset(-position.pixels, 0), + AxisDirection.right => Offset(position.pixels, 0), + }; } ScrollController get _effectiveScrollController => widget.controller ?? _fallbackScrollController!; @@ -1491,16 +1487,12 @@ class _ScrollableSelectionContainerDelegate extends MultiSelectableSelectionCont } Offset _getDeltaToScrollOrigin(ScrollableState scrollableState) { - switch (scrollableState.axisDirection) { - case AxisDirection.down: - return Offset(0, scrollableState.position.pixels); - case AxisDirection.up: - return Offset(0, -scrollableState.position.pixels); - case AxisDirection.left: - return Offset(-scrollableState.position.pixels, 0); - case AxisDirection.right: - return Offset(scrollableState.position.pixels, 0); - } + return switch (scrollableState.axisDirection) { + AxisDirection.up => Offset(0, -scrollableState.position.pixels), + AxisDirection.down => Offset(0, scrollableState.position.pixels), + AxisDirection.left => Offset(-scrollableState.position.pixels, 0), + AxisDirection.right => Offset(scrollableState.position.pixels, 0), + }; } /// With [_ScrollSemantics] certain child [SemanticsNode]s can be diff --git a/packages/flutter/lib/src/widgets/scrollable_helpers.dart b/packages/flutter/lib/src/widgets/scrollable_helpers.dart index e61c015a922..a9f12026e2b 100644 --- a/packages/flutter/lib/src/widgets/scrollable_helpers.dart +++ b/packages/flutter/lib/src/widgets/scrollable_helpers.dart @@ -184,21 +184,17 @@ class EdgeDraggingAutoScroller { bool _scrolling = false; double _offsetExtent(Offset offset, Axis scrollDirection) { - switch (scrollDirection) { - case Axis.horizontal: - return offset.dx; - case Axis.vertical: - return offset.dy; - } + return switch (scrollDirection) { + Axis.horizontal => offset.dx, + Axis.vertical => offset.dy, + }; } double _sizeExtent(Size size, Axis scrollDirection) { - switch (scrollDirection) { - case Axis.horizontal: - return size.width; - case Axis.vertical: - return size.height; - } + return switch (scrollDirection) { + Axis.horizontal => size.width, + Axis.vertical => size.height, + }; } AxisDirection get _axisDirection => scrollable.axisDirection; @@ -415,12 +411,10 @@ class ScrollAction extends ContextAction { ), ); } - switch (type) { - case ScrollIncrementType.line: - return 50.0; - case ScrollIncrementType.page: - return 0.8 * state.position.viewportDimension; - } + return switch (type) { + ScrollIncrementType.line => 50.0, + ScrollIncrementType.page => 0.8 * state.position.viewportDimension, + }; } /// Find out how much of an increment to move by, taking the different diff --git a/packages/flutter/lib/src/widgets/scrollbar.dart b/packages/flutter/lib/src/widgets/scrollbar.dart index f3387d788b9..bb63d5561df 100644 --- a/packages/flutter/lib/src/widgets/scrollbar.dart +++ b/packages/flutter/lib/src/widgets/scrollbar.dart @@ -384,14 +384,10 @@ class ScrollbarPainter extends ChangeNotifier implements CustomPainter { // The track is offset by only padding. double get _totalTrackMainAxisOffsets => _isVertical ? padding.vertical : padding.horizontal; double get _leadingTrackMainAxisOffset { - switch (_resolvedOrientation) { - case ScrollbarOrientation.left: - case ScrollbarOrientation.right: - return padding.top; - case ScrollbarOrientation.top: - case ScrollbarOrientation.bottom: - return padding.left; - } + return switch (_resolvedOrientation) { + ScrollbarOrientation.left || ScrollbarOrientation.right => padding.top, + ScrollbarOrientation.top || ScrollbarOrientation.bottom => padding.left, + }; } Rect? _thumbRect; @@ -401,16 +397,8 @@ class ScrollbarPainter extends ChangeNotifier implements CustomPainter { late double _thumbExtent; // Thumb Offsets // The thumb is offset by padding and margins. - double get _leadingThumbMainAxisOffset { - switch (_resolvedOrientation) { - case ScrollbarOrientation.left: - case ScrollbarOrientation.right: - return padding.top + mainAxisMargin; - case ScrollbarOrientation.top: - case ScrollbarOrientation.bottom: - return padding.left + mainAxisMargin; - } - } + double get _leadingThumbMainAxisOffset => _leadingTrackMainAxisOffset + mainAxisMargin; + void _setThumbExtent() { // Thumb extent reflects fraction of content visible, as long as this // isn't less than the absolute minimum size. diff --git a/packages/flutter/lib/src/widgets/selectable_region.dart b/packages/flutter/lib/src/widgets/selectable_region.dart index 9df96aee545..b69fb49aad0 100644 --- a/packages/flutter/lib/src/widgets/selectable_region.dart +++ b/packages/flutter/lib/src/widgets/selectable_region.dart @@ -2321,14 +2321,10 @@ abstract class MultiSelectableSelectionContainerDelegate extends SelectionContai SelectionResult handleDirectionallyExtendSelection(DirectionallyExtendSelectionEvent event) { assert((currentSelectionStartIndex == -1) == (currentSelectionEndIndex == -1)); if (currentSelectionStartIndex == -1) { - switch (event.direction) { - case SelectionExtendDirection.previousLine: - case SelectionExtendDirection.backward: - currentSelectionStartIndex = currentSelectionEndIndex = selectables.length; - case SelectionExtendDirection.nextLine: - case SelectionExtendDirection.forward: - currentSelectionStartIndex = currentSelectionEndIndex = 0; - } + currentSelectionStartIndex = currentSelectionEndIndex = switch (event.direction) { + SelectionExtendDirection.previousLine || SelectionExtendDirection.backward => selectables.length, + SelectionExtendDirection.nextLine || SelectionExtendDirection.forward => 0, + }; } int targetIndex = event.isEnd ? currentSelectionEndIndex : currentSelectionStartIndex; SelectionResult result = dispatchSelectionEventToChild(selectables[targetIndex], event); diff --git a/packages/flutter/lib/src/widgets/single_child_scroll_view.dart b/packages/flutter/lib/src/widgets/single_child_scroll_view.dart index c7c7a1b87e0..6fec4cb8762 100644 --- a/packages/flutter/lib/src/widgets/single_child_scroll_view.dart +++ b/packages/flutter/lib/src/widgets/single_child_scroll_view.dart @@ -404,12 +404,10 @@ class _RenderSingleChildViewport extends RenderBox with RenderObjectWithChildMix double get _viewportExtent { assert(hasSize); - switch (axis) { - case Axis.horizontal: - return size.width; - case Axis.vertical: - return size.height; - } + return switch (axis) { + Axis.horizontal => size.width, + Axis.vertical => size.height, + }; } double get _minScrollExtent { @@ -422,21 +420,17 @@ class _RenderSingleChildViewport extends RenderBox with RenderObjectWithChildMix if (child == null) { return 0.0; } - switch (axis) { - case Axis.horizontal: - return math.max(0.0, child!.size.width - size.width); - case Axis.vertical: - return math.max(0.0, child!.size.height - size.height); - } + return math.max(0.0, switch (axis) { + Axis.horizontal => child!.size.width - size.width, + Axis.vertical => child!.size.height - size.height, + }); } BoxConstraints _getInnerConstraints(BoxConstraints constraints) { - switch (axis) { - case Axis.horizontal: - return constraints.heightConstraints(); - case Axis.vertical: - return constraints.widthConstraints(); - } + return switch (axis) { + Axis.horizontal => constraints.heightConstraints(), + Axis.vertical => constraints.widthConstraints(), + }; } @override @@ -510,16 +504,12 @@ class _RenderSingleChildViewport extends RenderBox with RenderObjectWithChildMix Offset get _paintOffset => _paintOffsetForPosition(offset.pixels); Offset _paintOffsetForPosition(double position) { - switch (axisDirection) { - case AxisDirection.up: - return Offset(0.0, position - child!.size.height + size.height); - case AxisDirection.down: - return Offset(0.0, -position); - case AxisDirection.left: - return Offset(position - child!.size.width + size.width, 0.0); - case AxisDirection.right: - return Offset(-position, 0.0); - } + return switch (axisDirection) { + AxisDirection.up => Offset(0.0, position - child!.size.height + size.height), + AxisDirection.left => Offset(position - child!.size.width + size.width, 0.0), + AxisDirection.right => Offset(-position, 0.0), + AxisDirection.down => Offset(0.0, -position), + }; } bool _shouldClipAtPaintOffset(Offset paintOffset) { @@ -620,28 +610,12 @@ class _RenderSingleChildViewport extends RenderBox with RenderObjectWithChildMix final Rect bounds = MatrixUtils.transformRect(transform, rect); final Size contentSize = child!.size; - final double leadingScrollOffset; - final double targetMainAxisExtent; - final double mainAxisExtent; - - switch (axisDirection) { - case AxisDirection.up: - mainAxisExtent = size.height; - leadingScrollOffset = contentSize.height - bounds.bottom; - targetMainAxisExtent = bounds.height; - case AxisDirection.right: - mainAxisExtent = size.width; - leadingScrollOffset = bounds.left; - targetMainAxisExtent = bounds.width; - case AxisDirection.down: - mainAxisExtent = size.height; - leadingScrollOffset = bounds.top; - targetMainAxisExtent = bounds.height; - case AxisDirection.left: - mainAxisExtent = size.width; - leadingScrollOffset = contentSize.width - bounds.right; - targetMainAxisExtent = bounds.width; - } + final (double mainAxisExtent, double leadingScrollOffset, double targetMainAxisExtent) = switch (axisDirection) { + AxisDirection.up => (size.height, contentSize.height - bounds.bottom, bounds.height), + AxisDirection.left => (size.width, contentSize.width - bounds.right, bounds.width), + AxisDirection.right => (size.width, bounds.left, bounds.width), + AxisDirection.down => (size.height, bounds.top, bounds.height), + }; final double targetOffset = leadingScrollOffset - (mainAxisExtent - targetMainAxisExtent) * alignment; final Rect targetRect = bounds.shift(_paintOffsetForPosition(targetOffset)); diff --git a/packages/flutter/lib/src/widgets/sliver_fill.dart b/packages/flutter/lib/src/widgets/sliver_fill.dart index f39a5f1b1a1..994f7755b19 100644 --- a/packages/flutter/lib/src/widgets/sliver_fill.dart +++ b/packages/flutter/lib/src/widgets/sliver_fill.dart @@ -144,12 +144,10 @@ class _RenderSliverFractionalPadding extends RenderSliverEdgeInsetsPadding { final double paddingValue = constraints.viewportMainAxisExtent * viewportFraction; _lastResolvedConstraints = constraints; - switch (constraints.axis) { - case Axis.horizontal: - _resolvedPadding = EdgeInsets.symmetric(horizontal: paddingValue); - case Axis.vertical: - _resolvedPadding = EdgeInsets.symmetric(vertical: paddingValue); - } + _resolvedPadding = switch (constraints.axis) { + Axis.horizontal => EdgeInsets.symmetric(horizontal: paddingValue), + Axis.vertical => EdgeInsets.symmetric(vertical: paddingValue), + }; return; }