Skip to content

Commit

Permalink
Refactoring if chains into switch statements (#144905)
Browse files Browse the repository at this point in the history
Based on issue #144903, this PR 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

<br>

This change unfortunately increases the total line length, but it also improves readability.
  • Loading branch information
nate-thegrate committed Mar 11, 2024
1 parent 187ec75 commit 26e379e
Show file tree
Hide file tree
Showing 20 changed files with 404 additions and 349 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,15 @@ class NavigationIconView {

FadeTransition transition(BottomNavigationBarType type, BuildContext context) {
Color? iconColor;
if (type == BottomNavigationBarType.shifting) {
iconColor = _color;
} else {
final ThemeData theme = Theme.of(context);
final ColorScheme colorScheme = theme.colorScheme;
iconColor = theme.brightness == Brightness.light
? colorScheme.primary
: colorScheme.secondary;
switch (type) {
case BottomNavigationBarType.shifting:
iconColor = _color;
case BottomNavigationBarType.fixed:
final ThemeData theme = Theme.of(context);
iconColor = switch (theme.brightness) {
Brightness.light => theme.colorScheme.primary,
Brightness.dark => theme.colorScheme.secondary,
};
}

return FadeTransition(
Expand Down
17 changes: 10 additions & 7 deletions dev/manual_tests/lib/overlay_geometry.dart
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,16 @@ class _MarkerPainter extends CustomPainter {
..color = const Color(0xFFFFFFFF)
..style = PaintingStyle.stroke
..strokeWidth = 1.0;
if (type == MarkerType.topLeft) {
canvas.drawLine(Offset(r, r), Offset(r + r - 1.0, r), paint);
canvas.drawLine(Offset(r, r), Offset(r, r + r - 1.0), paint);
}
if (type == MarkerType.bottomRight) {
canvas.drawLine(Offset(r, r), Offset(1.0, r), paint);
canvas.drawLine(Offset(r, r), Offset(r, 1.0), paint);

switch (type) {
case MarkerType.topLeft:
canvas.drawLine(Offset(r, r), Offset(r + r - 1.0, r), paint);
canvas.drawLine(Offset(r, r), Offset(r, r + r - 1.0), paint);
case MarkerType.bottomRight:
canvas.drawLine(Offset(r, r), Offset(1.0, r), paint);
canvas.drawLine(Offset(r, r), Offset(r, 1.0), paint);
case MarkerType.touch:
break;
}
}

Expand Down
12 changes: 7 additions & 5 deletions examples/api/lib/material/bottom_app_bar/bottom_app_bar.2.dart
Original file line number Diff line number Diff line change
Expand Up @@ -41,11 +41,13 @@ class _BottomAppBarDemoState extends State<BottomAppBarDemo> {
_isVisible ? FloatingActionButtonLocation.endContained : FloatingActionButtonLocation.endFloat;

void _listen() {
final ScrollDirection direction = _controller.position.userScrollDirection;
if (direction == ScrollDirection.forward) {
_show();
} else if (direction == ScrollDirection.reverse) {
_hide();
switch (_controller.position.userScrollDirection) {
case ScrollDirection.idle:
break;
case ScrollDirection.forward:
_show();
case ScrollDirection.reverse:
_hide();
}
}

Expand Down
32 changes: 18 additions & 14 deletions packages/flutter/lib/src/cupertino/date_picker.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1021,25 +1021,29 @@ class _CupertinoDatePickerDateTimeState extends State<CupertinoDatePicker> {

// Adds am/pm column if the picker is not using 24h format.
if (!widget.use24hFormat) {
if (localizations.datePickerDateTimeOrder == DatePickerDateTimeOrder.date_time_dayPeriod
|| localizations.datePickerDateTimeOrder == DatePickerDateTimeOrder.time_dayPeriod_date) {
pickerBuilders.add(_buildAmPmPicker);
columnWidths.add(_getEstimatedColumnWidth(_PickerColumnType.dayPeriod));
} else {
pickerBuilders.insert(0, _buildAmPmPicker);
columnWidths.insert(0, _getEstimatedColumnWidth(_PickerColumnType.dayPeriod));
switch (localizations.datePickerDateTimeOrder) {
case DatePickerDateTimeOrder.date_time_dayPeriod:
case DatePickerDateTimeOrder.time_dayPeriod_date:
pickerBuilders.add(_buildAmPmPicker);
columnWidths.add(_getEstimatedColumnWidth(_PickerColumnType.dayPeriod));
case DatePickerDateTimeOrder.date_dayPeriod_time:
case DatePickerDateTimeOrder.dayPeriod_time_date:
pickerBuilders.insert(0, _buildAmPmPicker);
columnWidths.insert(0, _getEstimatedColumnWidth(_PickerColumnType.dayPeriod));
}
}

// Adds medium date column if the picker's mode is date and time.
if (widget.mode == CupertinoDatePickerMode.dateAndTime) {
if (localizations.datePickerDateTimeOrder == DatePickerDateTimeOrder.time_dayPeriod_date
|| localizations.datePickerDateTimeOrder == DatePickerDateTimeOrder.dayPeriod_time_date) {
pickerBuilders.add(_buildMediumDatePicker);
columnWidths.add(_getEstimatedColumnWidth(_PickerColumnType.date));
} else {
pickerBuilders.insert(0, _buildMediumDatePicker);
columnWidths.insert(0, _getEstimatedColumnWidth(_PickerColumnType.date));
switch (localizations.datePickerDateTimeOrder) {
case DatePickerDateTimeOrder.time_dayPeriod_date:
case DatePickerDateTimeOrder.dayPeriod_time_date:
pickerBuilders.add(_buildMediumDatePicker);
columnWidths.add(_getEstimatedColumnWidth(_PickerColumnType.date));
case DatePickerDateTimeOrder.date_time_dayPeriod:
case DatePickerDateTimeOrder.date_dayPeriod_time:
pickerBuilders.insert(0, _buildMediumDatePicker);
columnWidths.insert(0, _getEstimatedColumnWidth(_PickerColumnType.date));
}
}

Expand Down
43 changes: 24 additions & 19 deletions packages/flutter/lib/src/cupertino/form_section.dart
Original file line number Diff line number Diff line change
Expand Up @@ -210,24 +210,29 @@ class CupertinoFormSection extends StatelessWidget {
),
child: footer!);

return _type == CupertinoListSectionType.base
? CupertinoListSection(
header: headerWidget,
footer: footerWidget,
margin: margin,
backgroundColor: backgroundColor,
decoration: decoration,
clipBehavior: clipBehavior,
hasLeading: false,
children: children)
: CupertinoListSection.insetGrouped(
header: headerWidget,
footer: footerWidget,
margin: margin,
backgroundColor: backgroundColor,
decoration: decoration,
clipBehavior: clipBehavior,
hasLeading: false,
children: children);
switch (_type) {
case CupertinoListSectionType.base:
return CupertinoListSection(
header: headerWidget,
footer: footerWidget,
margin: margin,
backgroundColor: backgroundColor,
decoration: decoration,
clipBehavior: clipBehavior,
hasLeading: false,
children: children,
);
case CupertinoListSectionType.insetGrouped:
return CupertinoListSection.insetGrouped(
header: headerWidget,
footer: footerWidget,
margin: margin,
backgroundColor: backgroundColor,
decoration: decoration,
clipBehavior: clipBehavior,
hasLeading: false,
children: children,
);
}
}
}
31 changes: 16 additions & 15 deletions packages/flutter/lib/src/gestures/arena.dart
Original file line number Diff line number Diff line change
Expand Up @@ -222,22 +222,23 @@ class GestureArenaManager {
if (state == null) {
return; // This arena has already resolved.
}
assert(_debugLogDiagnostic(pointer, '${ disposition == GestureDisposition.accepted ? "Accepting" : "Rejecting" }: $member'));
assert(state.members.contains(member));
if (disposition == GestureDisposition.rejected) {
state.members.remove(member);
member.rejectGesture(pointer);
if (!state.isOpen) {
_tryToResolveArena(pointer, state);
}
} else {
assert(disposition == GestureDisposition.accepted);
if (state.isOpen) {
state.eagerWinner ??= member;
} else {
assert(_debugLogDiagnostic(pointer, 'Self-declared winner: $member'));
_resolveInFavorOf(pointer, state, member);
}
switch (disposition) {
case GestureDisposition.accepted:
assert(_debugLogDiagnostic(pointer, 'Accepting: $member'));
if (state.isOpen) {
state.eagerWinner ??= member;
} else {
assert(_debugLogDiagnostic(pointer, 'Self-declared winner: $member'));
_resolveInFavorOf(pointer, state, member);
}
case GestureDisposition.rejected:
assert(_debugLogDiagnostic(pointer, 'Rejecting: $member'));
state.members.remove(member);
member.rejectGesture(pointer);
if (!state.isOpen) {
_tryToResolveArena(pointer, state);
}
}
}

Expand Down
80 changes: 42 additions & 38 deletions packages/flutter/lib/src/gestures/monodrag.dart
Original file line number Diff line number Diff line change
Expand Up @@ -349,17 +349,20 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer {

void _addPointer(PointerEvent event) {
_velocityTrackers[event.pointer] = velocityTrackerBuilder(event);
if (_state == _DragState.ready) {
_state = _DragState.possible;
_initialPosition = OffsetPair(global: event.position, local: event.localPosition);
_finalPosition = _initialPosition;
_pendingDragOffset = OffsetPair.zero;
_globalDistanceMoved = 0.0;
_lastPendingEventTimestamp = event.timeStamp;
_lastTransform = event.transform;
_checkDown();
} else if (_state == _DragState.accepted) {
resolve(GestureDisposition.accepted);
switch (_state) {
case _DragState.ready:
_state = _DragState.possible;
_initialPosition = OffsetPair(global: event.position, local: event.localPosition);
_finalPosition = _initialPosition;
_pendingDragOffset = OffsetPair.zero;
_globalDistanceMoved = 0.0;
_lastPendingEventTimestamp = event.timeStamp;
_lastTransform = event.transform;
_checkDown();
case _DragState.possible:
break;
case _DragState.accepted:
resolve(GestureDisposition.accepted);
}
}

Expand Down Expand Up @@ -421,36 +424,37 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer {
final Offset position = (event is PointerMoveEvent) ? event.position : (event.position + (event as PointerPanZoomUpdateEvent).pan);
final Offset localPosition = (event is PointerMoveEvent) ? event.localPosition : (event.localPosition + (event as PointerPanZoomUpdateEvent).localPan);
_finalPosition = OffsetPair(local: localPosition, global: position);
if (_state == _DragState.accepted) {
_checkUpdate(
sourceTimeStamp: event.timeStamp,
delta: _getDeltaForDetails(localDelta),
primaryDelta: _getPrimaryValueFromOffset(localDelta),
globalPosition: position,
localPosition: localPosition,
);
} else {
_pendingDragOffset += OffsetPair(local: localDelta, global: delta);
_lastPendingEventTimestamp = event.timeStamp;
_lastTransform = event.transform;
final Offset movedLocally = _getDeltaForDetails(localDelta);
final Matrix4? localToGlobalTransform = event.transform == null ? null : Matrix4.tryInvert(event.transform!);
_globalDistanceMoved += PointerEvent.transformDeltaViaPositions(
transform: localToGlobalTransform,
untransformedDelta: movedLocally,
untransformedEndPosition: localPosition
).distance * (_getPrimaryValueFromOffset(movedLocally) ?? 1).sign;
if (_hasSufficientGlobalDistanceToAccept(event.kind, gestureSettings?.touchSlop)) {
_hasDragThresholdBeenMet = true;
if (_acceptedActivePointers.contains(event.pointer)) {
_checkDrag(event.pointer);
} else {
resolve(GestureDisposition.accepted);
switch (_state) {
case _DragState.ready || _DragState.possible:
_pendingDragOffset += OffsetPair(local: localDelta, global: delta);
_lastPendingEventTimestamp = event.timeStamp;
_lastTransform = event.transform;
final Offset movedLocally = _getDeltaForDetails(localDelta);
final Matrix4? localToGlobalTransform = event.transform == null ? null : Matrix4.tryInvert(event.transform!);
_globalDistanceMoved += PointerEvent.transformDeltaViaPositions(
transform: localToGlobalTransform,
untransformedDelta: movedLocally,
untransformedEndPosition: localPosition
).distance * (_getPrimaryValueFromOffset(movedLocally) ?? 1).sign;
if (_hasSufficientGlobalDistanceToAccept(event.kind, gestureSettings?.touchSlop)) {
_hasDragThresholdBeenMet = true;
if (_acceptedActivePointers.contains(event.pointer)) {
_checkDrag(event.pointer);
} else {
resolve(GestureDisposition.accepted);
}
}
}
case _DragState.accepted:
_checkUpdate(
sourceTimeStamp: event.timeStamp,
delta: _getDeltaForDetails(localDelta),
primaryDelta: _getPrimaryValueFromOffset(localDelta),
globalPosition: position,
localPosition: localPosition,
);
}
}
if (event is PointerUpEvent || event is PointerCancelEvent || event is PointerPanZoomEndEvent) {
if (event case PointerUpEvent() || PointerCancelEvent() || PointerPanZoomEndEvent()) {
_giveUpPointer(event.pointer);
}
}
Expand Down
9 changes: 5 additions & 4 deletions packages/flutter/lib/src/material/about.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1152,10 +1152,11 @@ class _MasterDetailFlowState extends State<_MasterDetailFlow> implements _PageOp
@override
void openDetailPage(Object arguments) {
_cachedDetailArguments = arguments;
if (_builtLayout == _LayoutMode.nested) {
_navigatorKey.currentState!.pushNamed(_navDetail, arguments: arguments);
} else {
focus = _Focus.detail;
switch (_builtLayout) {
case _LayoutMode.nested:
_navigatorKey.currentState!.pushNamed(_navDetail, arguments: arguments);
case _LayoutMode.lateral || null:
focus = _Focus.detail;
}
}

Expand Down
32 changes: 24 additions & 8 deletions packages/flutter/lib/src/material/toggle_buttons.dart
Original file line number Diff line number Diff line change
Expand Up @@ -455,19 +455,35 @@ class ToggleButtons extends StatelessWidget {
// Determines if this is the first child that is being laid out
// by the render object, _not_ the order of the children in its list.
bool _isFirstButton(int index, int length, TextDirection textDirection) {
return index == 0 && ((direction == Axis.horizontal && textDirection == TextDirection.ltr) ||
(direction == Axis.vertical && verticalDirection == VerticalDirection.down))
|| index == length - 1 && ((direction == Axis.horizontal && textDirection == TextDirection.rtl) ||
(direction == Axis.vertical && verticalDirection == VerticalDirection.up));
switch (direction) {
case Axis.horizontal:
return switch (textDirection) {
TextDirection.rtl => index == length - 1,
TextDirection.ltr => index == 0,
};
case Axis.vertical:
return switch (verticalDirection) {
VerticalDirection.up => index == length - 1,
VerticalDirection.down => index == 0,
};
}
}

// Determines if this is the last child that is being laid out
// by the render object, _not_ the order of the children in its list.
bool _isLastButton(int index, int length, TextDirection textDirection) {
return index == length - 1 && ((direction == Axis.horizontal && textDirection == TextDirection.ltr) ||
(direction == Axis.vertical && verticalDirection == VerticalDirection.down))
|| index == 0 && ((direction == Axis.horizontal && textDirection == TextDirection.rtl) ||
(direction == Axis.vertical && verticalDirection == VerticalDirection.up));
switch (direction) {
case Axis.horizontal:
return switch (textDirection) {
TextDirection.rtl => index == 0,
TextDirection.ltr => index == length - 1,
};
case Axis.vertical:
return switch (verticalDirection) {
VerticalDirection.up => index == 0,
VerticalDirection.down => index == length - 1,
};
}
}

BorderRadius _getEdgeBorderRadius(
Expand Down

0 comments on commit 26e379e

Please sign in to comment.