Skip to content

Commit

Permalink
flutter/lib/src/: refactoring if-chains into switch expressions (fl…
Browse files Browse the repository at this point in the history
…utter#146293)

Based on issue flutter#144903, this pull request aims to bring the codebase more in line with the [Flutter repo style guide](https://github.com/flutter/flutter/wiki/Style-guide-for-Flutter-repo#avoid-using-if-chains-or--or--with-enum-values):

> ### Avoid using `if` chains or `?:` or `==` with enum values
  • Loading branch information
nate-thegrate authored Apr 23, 2024
1 parent a91c62d commit a83e111
Show file tree
Hide file tree
Showing 19 changed files with 111 additions and 203 deletions.
14 changes: 5 additions & 9 deletions packages/flutter/lib/src/cupertino/dialog.dart
Original file line number Diff line number Diff line change
Expand Up @@ -639,14 +639,10 @@ class _CupertinoActionSheetState extends State<CupertinoActionSheet> {
),
if (widget.cancelButton != null) _buildCancelButton(),
];

final Orientation orientation = MediaQuery.orientationOf(context);
final double actionSheetWidth;
if (orientation == Orientation.portrait) {
actionSheetWidth = MediaQuery.sizeOf(context).width - (_kActionSheetEdgeHorizontalPadding * 2);
} else {
actionSheetWidth = MediaQuery.sizeOf(context).height - (_kActionSheetEdgeHorizontalPadding * 2);
}
final double actionSheetWidth = switch (MediaQuery.orientationOf(context)) {
Orientation.portrait => MediaQuery.sizeOf(context).width,
Orientation.landscape => MediaQuery.sizeOf(context).height,
};

return SafeArea(
child: ScrollConfiguration(
Expand All @@ -660,7 +656,7 @@ class _CupertinoActionSheetState extends State<CupertinoActionSheet> {
child: CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.elevated,
child: Container(
width: actionSheetWidth,
width: actionSheetWidth - _kActionSheetEdgeHorizontalPadding * 2,
margin: const EdgeInsets.symmetric(
horizontal: _kActionSheetEdgeHorizontalPadding,
vertical: _kActionSheetEdgeVerticalPadding,
Expand Down
31 changes: 10 additions & 21 deletions packages/flutter/lib/src/foundation/diagnostics.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2113,16 +2113,11 @@ class FlagProperty extends DiagnosticsProperty<bool> {

@override
String valueToString({ TextTreeConfiguration? parentConfiguration }) {
if (value ?? false) {
if (ifTrue != null) {
return ifTrue!;
}
} else if (value == false) {
if (ifFalse != null) {
return ifFalse!;
}
}
return super.valueToString(parentConfiguration: parentConfiguration);
return switch (value) {
true when ifTrue != null => ifTrue!,
false when ifFalse != null => ifFalse!,
_ => super.valueToString(parentConfiguration: parentConfiguration),
};
}

@override
Expand All @@ -2139,17 +2134,11 @@ class FlagProperty extends DiagnosticsProperty<bool> {

@override
DiagnosticLevel get level {
if (value ?? false) {
if (ifTrue == null) {
return DiagnosticLevel.hidden;
}
}
if (value == false) {
if (ifFalse == null) {
return DiagnosticLevel.hidden;
}
}
return super.level;
return switch (value) {
true when ifTrue == null => DiagnosticLevel.hidden,
false when ifFalse == null => DiagnosticLevel.hidden,
_ => super.level,
};
}
}

Expand Down
18 changes: 6 additions & 12 deletions packages/flutter/lib/src/material/calendar_date_picker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -211,18 +211,12 @@ class _CalendarDatePickerState extends State<CalendarDatePicker> {
_vibrate();
setState(() {
_mode = mode;
if (_selectedDate != null) {
if (_mode == DatePickerMode.day) {
SemanticsService.announce(
_localizations.formatMonthYear(_selectedDate!),
_textDirection,
);
} else {
SemanticsService.announce(
_localizations.formatYear(_selectedDate!),
_textDirection,
);
}
if (_selectedDate case final DateTime selected) {
final String message = switch (mode) {
DatePickerMode.day => _localizations.formatMonthYear(selected),
DatePickerMode.year => _localizations.formatYear(selected),
};
SemanticsService.announce(message, _textDirection);
}
});
}
Expand Down
12 changes: 5 additions & 7 deletions packages/flutter/lib/src/material/input_decorator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -562,13 +562,11 @@ class FloatingLabelAlignment {
}

static String _stringify(double x) {
if (x == -1.0) {
return 'FloatingLabelAlignment.start';
}
if (x == 0.0) {
return 'FloatingLabelAlignment.center';
}
return 'FloatingLabelAlignment(x: ${x.toStringAsFixed(1)})';
return switch (x) {
-1.0 => 'FloatingLabelAlignment.start',
0.0 => 'FloatingLabelAlignment.center',
_ => 'FloatingLabelAlignment(x: ${x.toStringAsFixed(1)})',
};
}

@override
Expand Down
10 changes: 4 additions & 6 deletions packages/flutter/lib/src/material/mergeable_material.dart
Original file line number Diff line number Diff line change
Expand Up @@ -579,12 +579,10 @@ class _MergeableMaterialState extends State<MergeableMaterial> with TickerProvid
);
slices = <Widget>[];

widgets.add(
SizedBox(
width: widget.mainAxis == Axis.horizontal ? _getGapSize(i) : null,
height: widget.mainAxis == Axis.vertical ? _getGapSize(i) : null,
),
);
widgets.add(switch (widget.mainAxis) {
Axis.horizontal => SizedBox(width: _getGapSize(i)),
Axis.vertical => SizedBox(height: _getGapSize(i)),
});
} else {
final MaterialSlice slice = _children[i] as MaterialSlice;
Widget child = slice.child;
Expand Down
18 changes: 8 additions & 10 deletions packages/flutter/lib/src/material/range_slider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1230,11 +1230,10 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix
// a tap, it consists of a call to onChangeStart with the previous value and
// a call to onChangeEnd with the new value.
final RangeValues currentValues = _discretizeRangeValues(values);
if (_lastThumbSelection == Thumb.start) {
_newValues = RangeValues(tapValue, currentValues.end);
} else if (_lastThumbSelection == Thumb.end) {
_newValues = RangeValues(currentValues.start, tapValue);
}
_newValues = switch (_lastThumbSelection!) {
Thumb.start => RangeValues(tapValue, currentValues.end),
Thumb.end => RangeValues(currentValues.start, tapValue),
};
_updateLabelPainter(_lastThumbSelection!);

onChangeStart?.call(currentValues);
Expand Down Expand Up @@ -1286,11 +1285,10 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix
}
final double currentDragValue = _discretize(dragValue);

if (_lastThumbSelection == Thumb.start) {
_newValues = RangeValues(math.min(currentDragValue, currentValues.end - _minThumbSeparationValue), currentValues.end);
} else if (_lastThumbSelection == Thumb.end) {
_newValues = RangeValues(currentValues.start, math.max(currentDragValue, currentValues.start + _minThumbSeparationValue));
}
_newValues = switch (_lastThumbSelection!) {
Thumb.start => RangeValues(math.min(currentDragValue, currentValues.end - _minThumbSeparationValue), currentValues.end),
Thumb.end => RangeValues(currentValues.start, math.max(currentDragValue, currentValues.start + _minThumbSeparationValue)),
};
onChanged!(_newValues);
}
}
Expand Down
10 changes: 4 additions & 6 deletions packages/flutter/lib/src/material/selectable_text.dart
Original file line number Diff line number Diff line change
Expand Up @@ -117,12 +117,10 @@ class _SelectableTextSelectionGestureDetectorBuilder extends TextSelectionGestur
final Offset editableOffset = renderEditable.maxLines == 1
? Offset(renderEditable.offset.pixels - _dragStartViewportOffset, 0.0)
: Offset(0.0, renderEditable.offset.pixels - _dragStartViewportOffset);
final double effectiveScrollPosition = _scrollPosition - _dragStartScrollOffset;
final bool scrollingOnVerticalAxis = _scrollDirection == AxisDirection.up || _scrollDirection == AxisDirection.down;
final Offset scrollableOffset = Offset(
!scrollingOnVerticalAxis ? effectiveScrollPosition : 0.0,
scrollingOnVerticalAxis ? effectiveScrollPosition : 0.0,
);
final Offset scrollableOffset = switch (axisDirectionToAxis(_scrollDirection ?? AxisDirection.left)) {
Axis.horizontal => Offset(_scrollPosition - _dragStartScrollOffset, 0),
Axis.vertical => Offset(0, _scrollPosition - _dragStartScrollOffset),
};
renderEditable.selectWordsInRange(
from: details.globalPosition - details.offsetFromOrigin - editableOffset - scrollableOffset,
to: details.globalPosition,
Expand Down
18 changes: 8 additions & 10 deletions packages/flutter/lib/src/material/slider_theme.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1619,20 +1619,18 @@ class RectangularSliderTrackShape extends SliderTrackShape with BaseSliderTrackS
context.canvas.drawRect(rightTrackSegment, rightTrackPaint);
}

final bool showSecondaryTrack = (secondaryOffset != null) &&
((textDirection == TextDirection.ltr)
? (secondaryOffset.dx > thumbCenter.dx)
: (secondaryOffset.dx < thumbCenter.dx));
final bool showSecondaryTrack = secondaryOffset != null && switch (textDirection) {
TextDirection.rtl => secondaryOffset.dx < thumbCenter.dx,
TextDirection.ltr => secondaryOffset.dx > thumbCenter.dx,
};

if (showSecondaryTrack) {
final ColorTween secondaryTrackColorTween = ColorTween(begin: sliderTheme.disabledSecondaryActiveTrackColor, end: sliderTheme.secondaryActiveTrackColor);
final Paint secondaryTrackPaint = Paint()..color = secondaryTrackColorTween.evaluate(enableAnimation)!;
final Rect secondaryTrackSegment = Rect.fromLTRB(
(textDirection == TextDirection.ltr) ? thumbCenter.dx : secondaryOffset.dx,
trackRect.top,
(textDirection == TextDirection.ltr) ? secondaryOffset.dx : thumbCenter.dx,
trackRect.bottom,
);
final Rect secondaryTrackSegment = switch (textDirection) {
TextDirection.rtl => Rect.fromLTRB(secondaryOffset.dx, trackRect.top, thumbCenter.dx, trackRect.bottom),
TextDirection.ltr => Rect.fromLTRB(thumbCenter.dx, trackRect.top, secondaryOffset.dx, trackRect.bottom),
};
if (!secondaryTrackSegment.isEmpty) {
context.canvas.drawRect(secondaryTrackSegment, secondaryTrackPaint);
}
Expand Down
20 changes: 8 additions & 12 deletions packages/flutter/lib/src/material/tabs.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1536,18 +1536,14 @@ class _TabBarState extends State<TabBar> {

final double index = _controller!.index.toDouble();
final double value = _controller!.animation!.value;
final double offset;
if (value == index - 1.0) {
offset = leadingPosition ?? middlePosition;
} else if (value == index + 1.0) {
offset = trailingPosition ?? middlePosition;
} else if (value == index) {
offset = middlePosition;
} else if (value < index) {
offset = leadingPosition == null ? middlePosition : lerpDouble(middlePosition, leadingPosition, index - value)!;
} else {
offset = trailingPosition == null ? middlePosition : lerpDouble(middlePosition, trailingPosition, value - index)!;
}
final double offset = switch (value - index) {
-1.0 || 1.0 => leadingPosition ?? middlePosition,
0 => middlePosition,
< 0 when leadingPosition == null => middlePosition,
> 0 when trailingPosition == null => middlePosition,
< 0 => lerpDouble(middlePosition, leadingPosition, index - value)!,
_ => lerpDouble(middlePosition, trailingPosition, value - index)!,
};

_scrollController!.jumpTo(offset);
}
Expand Down
34 changes: 11 additions & 23 deletions packages/flutter/lib/src/material/toggle_buttons.dart
Original file line number Diff line number Diff line change
Expand Up @@ -738,26 +738,16 @@ class ToggleButtons extends StatelessWidget {
?? theme.textTheme.bodyMedium!;
final BoxConstraints? currentConstraints = constraints
?? toggleButtonsTheme.constraints;
final Size minimumSize = currentConstraints == null
? const Size.square(kMinInteractiveDimension)
: Size(currentConstraints.minWidth, currentConstraints.minHeight);
final Size? maximumSize = currentConstraints == null
? null
: Size(currentConstraints.maxWidth, currentConstraints.maxHeight);
final Size minimumSize = currentConstraints?.smallest
?? const Size.square(kMinInteractiveDimension);
final Size? maximumSize = currentConstraints?.biggest;
final Size minPaddingSize;
switch (tapTargetSize ?? theme.materialTapTargetSize) {
case MaterialTapTargetSize.padded:
if (direction == Axis.horizontal) {
minPaddingSize = const Size(
0.0,
kMinInteractiveDimension,
);
} else {
minPaddingSize = const Size(
kMinInteractiveDimension,
0.0,
);
}
minPaddingSize = switch (direction) {
Axis.horizontal => const Size(0.0, kMinInteractiveDimension),
Axis.vertical => const Size(kMinInteractiveDimension, 0.0),
};
assert(minPaddingSize.width >= 0.0);
assert(minPaddingSize.height >= 0.0);
case MaterialTapTargetSize.shrinkWrap:
Expand Down Expand Up @@ -1658,12 +1648,10 @@ class _RenderInputPadding extends RenderShiftedBox {
}

// Only adjust one axis to ensure the correct button is tapped.
Offset center;
if (direction == Axis.horizontal) {
center = Offset(position.dx, child!.size.height / 2);
} else {
center = Offset(child!.size.width / 2, position.dy);
}
final Offset center = switch (direction) {
Axis.horizontal => Offset(position.dx, child!.size.height / 2),
Axis.vertical => Offset(child!.size.width / 2, position.dy),
};
return result.addWithRawTransform(
transform: MatrixUtils.forceToPoint(center),
position: center,
Expand Down
36 changes: 8 additions & 28 deletions packages/flutter/lib/src/painting/colors.dart
Original file line number Diff line number Diff line change
Expand Up @@ -31,34 +31,14 @@ Color _colorFromHue(
double secondary,
double match,
) {
double red;
double green;
double blue;
if (hue < 60.0) {
red = chroma;
green = secondary;
blue = 0.0;
} else if (hue < 120.0) {
red = secondary;
green = chroma;
blue = 0.0;
} else if (hue < 180.0) {
red = 0.0;
green = chroma;
blue = secondary;
} else if (hue < 240.0) {
red = 0.0;
green = secondary;
blue = chroma;
} else if (hue < 300.0) {
red = secondary;
green = 0.0;
blue = chroma;
} else {
red = chroma;
green = 0.0;
blue = secondary;
}
final (double red, double green, double blue) = switch (hue) {
< 60.0 => (chroma, secondary, 0.0),
< 120.0 => (secondary, chroma, 0.0),
< 180.0 => (0.0, chroma, secondary),
< 240.0 => (0.0, secondary, chroma),
< 300.0 => (secondary, 0.0, chroma),
_ => (chroma, 0.0, secondary),
};
return Color.fromARGB((alpha * 0xFF).round(), ((red + match) * 0xFF).round(), ((green + match) * 0xFF).round(), ((blue + match) * 0xFF).round());
}

Expand Down
16 changes: 5 additions & 11 deletions packages/flutter/lib/src/painting/flutter_logo.dart
Original file line number Diff line number Diff line change
Expand Up @@ -330,17 +330,11 @@ class _FlutterLogoPainter extends BoxPainter {
if (canvasSize.isEmpty) {
return;
}
final Size logoSize;
if (_config._position > 0.0) {
// horizontal style
logoSize = const Size(820.0, 232.0);
} else if (_config._position < 0.0) {
// stacked style
logoSize = const Size(252.0, 306.0);
} else {
// only the mark
logoSize = const Size(202.0, 202.0);
}
final Size logoSize = switch (_config._position) {
> 0.0 => const Size(820.0, 232.0), // horizontal style
< 0.0 => const Size(252.0, 306.0), // stacked style
_ => const Size(202.0, 202.0), // only the mark
};
final FittedSizes fittedSize = applyBoxFit(BoxFit.contain, logoSize, canvasSize);
assert(fittedSize.source == logoSize);
final Rect rect = Alignment.center.inscribe(fittedSize.destination, offset & canvasSize);
Expand Down
13 changes: 5 additions & 8 deletions packages/flutter/lib/src/physics/spring_simulation.dart
Original file line number Diff line number Diff line change
Expand Up @@ -153,14 +153,11 @@ abstract class _SpringSolution {
double initialPosition,
double initialVelocity,
) {
final double cmk = spring.damping * spring.damping - 4 * spring.mass * spring.stiffness;
if (cmk == 0.0) {
return _CriticalSolution(spring, initialPosition, initialVelocity);
}
if (cmk > 0.0) {
return _OverdampedSolution(spring, initialPosition, initialVelocity);
}
return _UnderdampedSolution(spring, initialPosition, initialVelocity);
return switch (spring.damping * spring.damping - 4 * spring.mass * spring.stiffness) {
> 0.0 => _OverdampedSolution(spring, initialPosition, initialVelocity),
< 0.0 => _UnderdampedSolution(spring, initialPosition, initialVelocity),
_ => _CriticalSolution(spring, initialPosition, initialVelocity),
};
}

double x(double time);
Expand Down
13 changes: 5 additions & 8 deletions packages/flutter/lib/src/rendering/box.dart
Original file line number Diff line number Diff line change
Expand Up @@ -540,14 +540,11 @@ class BoxConstraints extends Constraints {
if (affectedFieldsList.length > 1) {
affectedFieldsList.add('and ${affectedFieldsList.removeLast()}');
}
String whichFields = '';
if (affectedFieldsList.length > 2) {
whichFields = affectedFieldsList.join(', ');
} else if (affectedFieldsList.length == 2) {
whichFields = affectedFieldsList.join(' ');
} else {
whichFields = affectedFieldsList.single;
}
final String whichFields = switch (affectedFieldsList.length) {
1 => affectedFieldsList.single,
2 => affectedFieldsList.join(' '),
_ => affectedFieldsList.join(', '),
};
throwError(ErrorSummary('BoxConstraints has ${affectedFieldsList.length == 1 ? 'a NaN value' : 'NaN values' } in $whichFields.'));
}
if (minWidth < 0.0 && minHeight < 0.0) {
Expand Down
Loading

0 comments on commit a83e111

Please sign in to comment.