Refactoring if chains into switch statements (#144905)

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.
This commit is contained in:
Nate 2024-03-11 17:04:57 -06:00 committed by GitHub
parent 187ec75eb5
commit 26e379e0fc
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 404 additions and 349 deletions

View file

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

View file

@ -37,13 +37,16 @@ class _MarkerPainter extends CustomPainter {
..color = const Color(0xFFFFFFFF) ..color = const Color(0xFFFFFFFF)
..style = PaintingStyle.stroke ..style = PaintingStyle.stroke
..strokeWidth = 1.0; ..strokeWidth = 1.0;
if (type == MarkerType.topLeft) {
canvas.drawLine(Offset(r, r), Offset(r + r - 1.0, r), paint); switch (type) {
canvas.drawLine(Offset(r, r), Offset(r, r + r - 1.0), paint); case MarkerType.topLeft:
} canvas.drawLine(Offset(r, r), Offset(r + r - 1.0, r), paint);
if (type == MarkerType.bottomRight) { canvas.drawLine(Offset(r, r), Offset(r, r + r - 1.0), paint);
canvas.drawLine(Offset(r, r), Offset(1.0, r), paint); case MarkerType.bottomRight:
canvas.drawLine(Offset(r, r), Offset(r, 1.0), paint); canvas.drawLine(Offset(r, r), Offset(1.0, r), paint);
canvas.drawLine(Offset(r, r), Offset(r, 1.0), paint);
case MarkerType.touch:
break;
} }
} }

View file

@ -41,11 +41,13 @@ class _BottomAppBarDemoState extends State<BottomAppBarDemo> {
_isVisible ? FloatingActionButtonLocation.endContained : FloatingActionButtonLocation.endFloat; _isVisible ? FloatingActionButtonLocation.endContained : FloatingActionButtonLocation.endFloat;
void _listen() { void _listen() {
final ScrollDirection direction = _controller.position.userScrollDirection; switch (_controller.position.userScrollDirection) {
if (direction == ScrollDirection.forward) { case ScrollDirection.idle:
_show(); break;
} else if (direction == ScrollDirection.reverse) { case ScrollDirection.forward:
_hide(); _show();
case ScrollDirection.reverse:
_hide();
} }
} }

View file

@ -1021,25 +1021,29 @@ class _CupertinoDatePickerDateTimeState extends State<CupertinoDatePicker> {
// Adds am/pm column if the picker is not using 24h format. // Adds am/pm column if the picker is not using 24h format.
if (!widget.use24hFormat) { if (!widget.use24hFormat) {
if (localizations.datePickerDateTimeOrder == DatePickerDateTimeOrder.date_time_dayPeriod switch (localizations.datePickerDateTimeOrder) {
|| localizations.datePickerDateTimeOrder == DatePickerDateTimeOrder.time_dayPeriod_date) { case DatePickerDateTimeOrder.date_time_dayPeriod:
pickerBuilders.add(_buildAmPmPicker); case DatePickerDateTimeOrder.time_dayPeriod_date:
columnWidths.add(_getEstimatedColumnWidth(_PickerColumnType.dayPeriod)); pickerBuilders.add(_buildAmPmPicker);
} else { columnWidths.add(_getEstimatedColumnWidth(_PickerColumnType.dayPeriod));
pickerBuilders.insert(0, _buildAmPmPicker); case DatePickerDateTimeOrder.date_dayPeriod_time:
columnWidths.insert(0, _getEstimatedColumnWidth(_PickerColumnType.dayPeriod)); 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. // Adds medium date column if the picker's mode is date and time.
if (widget.mode == CupertinoDatePickerMode.dateAndTime) { if (widget.mode == CupertinoDatePickerMode.dateAndTime) {
if (localizations.datePickerDateTimeOrder == DatePickerDateTimeOrder.time_dayPeriod_date switch (localizations.datePickerDateTimeOrder) {
|| localizations.datePickerDateTimeOrder == DatePickerDateTimeOrder.dayPeriod_time_date) { case DatePickerDateTimeOrder.time_dayPeriod_date:
pickerBuilders.add(_buildMediumDatePicker); case DatePickerDateTimeOrder.dayPeriod_time_date:
columnWidths.add(_getEstimatedColumnWidth(_PickerColumnType.date)); pickerBuilders.add(_buildMediumDatePicker);
} else { columnWidths.add(_getEstimatedColumnWidth(_PickerColumnType.date));
pickerBuilders.insert(0, _buildMediumDatePicker); case DatePickerDateTimeOrder.date_time_dayPeriod:
columnWidths.insert(0, _getEstimatedColumnWidth(_PickerColumnType.date)); case DatePickerDateTimeOrder.date_dayPeriod_time:
pickerBuilders.insert(0, _buildMediumDatePicker);
columnWidths.insert(0, _getEstimatedColumnWidth(_PickerColumnType.date));
} }
} }

View file

@ -210,24 +210,29 @@ class CupertinoFormSection extends StatelessWidget {
), ),
child: footer!); child: footer!);
return _type == CupertinoListSectionType.base switch (_type) {
? CupertinoListSection( case CupertinoListSectionType.base:
header: headerWidget, return CupertinoListSection(
footer: footerWidget, header: headerWidget,
margin: margin, footer: footerWidget,
backgroundColor: backgroundColor, margin: margin,
decoration: decoration, backgroundColor: backgroundColor,
clipBehavior: clipBehavior, decoration: decoration,
hasLeading: false, clipBehavior: clipBehavior,
children: children) hasLeading: false,
: CupertinoListSection.insetGrouped( children: children,
header: headerWidget, );
footer: footerWidget, case CupertinoListSectionType.insetGrouped:
margin: margin, return CupertinoListSection.insetGrouped(
backgroundColor: backgroundColor, header: headerWidget,
decoration: decoration, footer: footerWidget,
clipBehavior: clipBehavior, margin: margin,
hasLeading: false, backgroundColor: backgroundColor,
children: children); decoration: decoration,
clipBehavior: clipBehavior,
hasLeading: false,
children: children,
);
}
} }
} }

View file

@ -222,22 +222,23 @@ class GestureArenaManager {
if (state == null) { if (state == null) {
return; // This arena has already resolved. return; // This arena has already resolved.
} }
assert(_debugLogDiagnostic(pointer, '${ disposition == GestureDisposition.accepted ? "Accepting" : "Rejecting" }: $member'));
assert(state.members.contains(member)); assert(state.members.contains(member));
if (disposition == GestureDisposition.rejected) { switch (disposition) {
state.members.remove(member); case GestureDisposition.accepted:
member.rejectGesture(pointer); assert(_debugLogDiagnostic(pointer, 'Accepting: $member'));
if (!state.isOpen) { if (state.isOpen) {
_tryToResolveArena(pointer, state); state.eagerWinner ??= member;
} } else {
} else { assert(_debugLogDiagnostic(pointer, 'Self-declared winner: $member'));
assert(disposition == GestureDisposition.accepted); _resolveInFavorOf(pointer, state, member);
if (state.isOpen) { }
state.eagerWinner ??= member; case GestureDisposition.rejected:
} else { assert(_debugLogDiagnostic(pointer, 'Rejecting: $member'));
assert(_debugLogDiagnostic(pointer, 'Self-declared winner: $member')); state.members.remove(member);
_resolveInFavorOf(pointer, state, member); member.rejectGesture(pointer);
} if (!state.isOpen) {
_tryToResolveArena(pointer, state);
}
} }
} }

View file

@ -349,17 +349,20 @@ abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer {
void _addPointer(PointerEvent event) { void _addPointer(PointerEvent event) {
_velocityTrackers[event.pointer] = velocityTrackerBuilder(event); _velocityTrackers[event.pointer] = velocityTrackerBuilder(event);
if (_state == _DragState.ready) { switch (_state) {
_state = _DragState.possible; case _DragState.ready:
_initialPosition = OffsetPair(global: event.position, local: event.localPosition); _state = _DragState.possible;
_finalPosition = _initialPosition; _initialPosition = OffsetPair(global: event.position, local: event.localPosition);
_pendingDragOffset = OffsetPair.zero; _finalPosition = _initialPosition;
_globalDistanceMoved = 0.0; _pendingDragOffset = OffsetPair.zero;
_lastPendingEventTimestamp = event.timeStamp; _globalDistanceMoved = 0.0;
_lastTransform = event.transform; _lastPendingEventTimestamp = event.timeStamp;
_checkDown(); _lastTransform = event.transform;
} else if (_state == _DragState.accepted) { _checkDown();
resolve(GestureDisposition.accepted); case _DragState.possible:
break;
case _DragState.accepted:
resolve(GestureDisposition.accepted);
} }
} }
@ -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 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); final Offset localPosition = (event is PointerMoveEvent) ? event.localPosition : (event.localPosition + (event as PointerPanZoomUpdateEvent).localPan);
_finalPosition = OffsetPair(local: localPosition, global: position); _finalPosition = OffsetPair(local: localPosition, global: position);
if (_state == _DragState.accepted) { switch (_state) {
_checkUpdate( case _DragState.ready || _DragState.possible:
sourceTimeStamp: event.timeStamp, _pendingDragOffset += OffsetPair(local: localDelta, global: delta);
delta: _getDeltaForDetails(localDelta), _lastPendingEventTimestamp = event.timeStamp;
primaryDelta: _getPrimaryValueFromOffset(localDelta), _lastTransform = event.transform;
globalPosition: position, final Offset movedLocally = _getDeltaForDetails(localDelta);
localPosition: localPosition, final Matrix4? localToGlobalTransform = event.transform == null ? null : Matrix4.tryInvert(event.transform!);
); _globalDistanceMoved += PointerEvent.transformDeltaViaPositions(
} else { transform: localToGlobalTransform,
_pendingDragOffset += OffsetPair(local: localDelta, global: delta); untransformedDelta: movedLocally,
_lastPendingEventTimestamp = event.timeStamp; untransformedEndPosition: localPosition
_lastTransform = event.transform; ).distance * (_getPrimaryValueFromOffset(movedLocally) ?? 1).sign;
final Offset movedLocally = _getDeltaForDetails(localDelta); if (_hasSufficientGlobalDistanceToAccept(event.kind, gestureSettings?.touchSlop)) {
final Matrix4? localToGlobalTransform = event.transform == null ? null : Matrix4.tryInvert(event.transform!); _hasDragThresholdBeenMet = true;
_globalDistanceMoved += PointerEvent.transformDeltaViaPositions( if (_acceptedActivePointers.contains(event.pointer)) {
transform: localToGlobalTransform, _checkDrag(event.pointer);
untransformedDelta: movedLocally, } else {
untransformedEndPosition: localPosition resolve(GestureDisposition.accepted);
).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); _giveUpPointer(event.pointer);
} }
} }

View file

@ -1152,10 +1152,11 @@ class _MasterDetailFlowState extends State<_MasterDetailFlow> implements _PageOp
@override @override
void openDetailPage(Object arguments) { void openDetailPage(Object arguments) {
_cachedDetailArguments = arguments; _cachedDetailArguments = arguments;
if (_builtLayout == _LayoutMode.nested) { switch (_builtLayout) {
_navigatorKey.currentState!.pushNamed(_navDetail, arguments: arguments); case _LayoutMode.nested:
} else { _navigatorKey.currentState!.pushNamed(_navDetail, arguments: arguments);
focus = _Focus.detail; case _LayoutMode.lateral || null:
focus = _Focus.detail;
} }
} }

View file

@ -455,19 +455,35 @@ class ToggleButtons extends StatelessWidget {
// Determines if this is the first child that is being laid out // 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. // by the render object, _not_ the order of the children in its list.
bool _isFirstButton(int index, int length, TextDirection textDirection) { bool _isFirstButton(int index, int length, TextDirection textDirection) {
return index == 0 && ((direction == Axis.horizontal && textDirection == TextDirection.ltr) || switch (direction) {
(direction == Axis.vertical && verticalDirection == VerticalDirection.down)) case Axis.horizontal:
|| index == length - 1 && ((direction == Axis.horizontal && textDirection == TextDirection.rtl) || return switch (textDirection) {
(direction == Axis.vertical && verticalDirection == VerticalDirection.up)); 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 // 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. // by the render object, _not_ the order of the children in its list.
bool _isLastButton(int index, int length, TextDirection textDirection) { bool _isLastButton(int index, int length, TextDirection textDirection) {
return index == length - 1 && ((direction == Axis.horizontal && textDirection == TextDirection.ltr) || switch (direction) {
(direction == Axis.vertical && verticalDirection == VerticalDirection.down)) case Axis.horizontal:
|| index == 0 && ((direction == Axis.horizontal && textDirection == TextDirection.rtl) || return switch (textDirection) {
(direction == Axis.vertical && verticalDirection == VerticalDirection.up)); 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( BorderRadius _getEdgeBorderRadius(

View file

@ -1795,29 +1795,30 @@ class TextInput {
Future<dynamic> _handleTextInputInvocation(MethodCall methodCall) async { Future<dynamic> _handleTextInputInvocation(MethodCall methodCall) async {
final String method = methodCall.method; final String method = methodCall.method;
if (method == 'TextInputClient.focusElement') { switch (methodCall.method) {
final List<dynamic> args = methodCall.arguments as List<dynamic>; case 'TextInputClient.focusElement':
_scribbleClients[args[0]]?.onScribbleFocus(Offset((args[1] as num).toDouble(), (args[2] as num).toDouble())); final List<dynamic> args = methodCall.arguments as List<dynamic>;
return; _scribbleClients[args[0]]?.onScribbleFocus(Offset((args[1] as num).toDouble(), (args[2] as num).toDouble()));
} else if (method == 'TextInputClient.requestElementsInRect') { return;
final List<double> args = (methodCall.arguments as List<dynamic>).cast<num>().map<double>((num value) => value.toDouble()).toList(); case 'TextInputClient.requestElementsInRect':
return _scribbleClients.keys.where((String elementIdentifier) { final List<double> args = (methodCall.arguments as List<dynamic>).cast<num>().map<double>((num value) => value.toDouble()).toList();
final Rect rect = Rect.fromLTWH(args[0], args[1], args[2], args[3]); return _scribbleClients.keys.where((String elementIdentifier) {
if (!(_scribbleClients[elementIdentifier]?.isInScribbleRect(rect) ?? false)) { final Rect rect = Rect.fromLTWH(args[0], args[1], args[2], args[3]);
return false; if (!(_scribbleClients[elementIdentifier]?.isInScribbleRect(rect) ?? false)) {
} return false;
final Rect bounds = _scribbleClients[elementIdentifier]?.bounds ?? Rect.zero; }
return !(bounds == Rect.zero || bounds.hasNaN || bounds.isInfinite); final Rect bounds = _scribbleClients[elementIdentifier]?.bounds ?? Rect.zero;
}).map((String elementIdentifier) { return !(bounds == Rect.zero || bounds.hasNaN || bounds.isInfinite);
final Rect bounds = _scribbleClients[elementIdentifier]!.bounds; }).map((String elementIdentifier) {
return <dynamic>[elementIdentifier, ...<dynamic>[bounds.left, bounds.top, bounds.width, bounds.height]]; final Rect bounds = _scribbleClients[elementIdentifier]!.bounds;
}).toList(); return <dynamic>[elementIdentifier, ...<dynamic>[bounds.left, bounds.top, bounds.width, bounds.height]];
} else if (method == 'TextInputClient.scribbleInteractionBegan') { }).toList();
_scribbleInProgress = true; case 'TextInputClient.scribbleInteractionBegan':
return; _scribbleInProgress = true;
} else if (method == 'TextInputClient.scribbleInteractionFinished') { return;
_scribbleInProgress = false; case 'TextInputClient.scribbleInteractionFinished':
return; _scribbleInProgress = false;
return;
} }
if (_currentConnection == null) { if (_currentConnection == null) {
return; return;

View file

@ -871,59 +871,62 @@ class _InteractiveViewerState extends State<InteractiveViewer> with TickerProvid
return; return;
} }
if (_gestureType == _GestureType.pan) { switch (_gestureType) {
if (details.velocity.pixelsPerSecond.distance < kMinFlingVelocity) { case _GestureType.pan:
_currentAxis = null; if (details.velocity.pixelsPerSecond.distance < kMinFlingVelocity) {
return; _currentAxis = null;
} return;
final Vector3 translationVector = _transformationController!.value.getTranslation(); }
final Offset translation = Offset(translationVector.x, translationVector.y); final Vector3 translationVector = _transformationController!.value.getTranslation();
final FrictionSimulation frictionSimulationX = FrictionSimulation( final Offset translation = Offset(translationVector.x, translationVector.y);
widget.interactionEndFrictionCoefficient, final FrictionSimulation frictionSimulationX = FrictionSimulation(
translation.dx, widget.interactionEndFrictionCoefficient,
details.velocity.pixelsPerSecond.dx, translation.dx,
); details.velocity.pixelsPerSecond.dx,
final FrictionSimulation frictionSimulationY = FrictionSimulation( );
widget.interactionEndFrictionCoefficient, final FrictionSimulation frictionSimulationY = FrictionSimulation(
translation.dy, widget.interactionEndFrictionCoefficient,
details.velocity.pixelsPerSecond.dy, translation.dy,
); details.velocity.pixelsPerSecond.dy,
final double tFinal = _getFinalTime( );
details.velocity.pixelsPerSecond.distance, final double tFinal = _getFinalTime(
widget.interactionEndFrictionCoefficient, details.velocity.pixelsPerSecond.distance,
); widget.interactionEndFrictionCoefficient,
_animation = Tween<Offset>( );
begin: translation, _animation = Tween<Offset>(
end: Offset(frictionSimulationX.finalX, frictionSimulationY.finalX), begin: translation,
).animate(CurvedAnimation( end: Offset(frictionSimulationX.finalX, frictionSimulationY.finalX),
parent: _controller, ).animate(CurvedAnimation(
curve: Curves.decelerate, parent: _controller,
)); curve: Curves.decelerate,
_controller.duration = Duration(milliseconds: (tFinal * 1000).round()); ));
_animation!.addListener(_onAnimate); _controller.duration = Duration(milliseconds: (tFinal * 1000).round());
_controller.forward(); _animation!.addListener(_onAnimate);
} else if (_gestureType == _GestureType.scale) { _controller.forward();
if (details.scaleVelocity.abs() < 0.1) { case _GestureType.scale:
_currentAxis = null; if (details.scaleVelocity.abs() < 0.1) {
return; _currentAxis = null;
} return;
final double scale = _transformationController!.value.getMaxScaleOnAxis(); }
final FrictionSimulation frictionSimulation = FrictionSimulation( final double scale = _transformationController!.value.getMaxScaleOnAxis();
widget.interactionEndFrictionCoefficient * widget.scaleFactor, final FrictionSimulation frictionSimulation = FrictionSimulation(
scale, widget.interactionEndFrictionCoefficient * widget.scaleFactor,
details.scaleVelocity / 10 scale,
); details.scaleVelocity / 10
final double tFinal = _getFinalTime(details.scaleVelocity.abs(), widget.interactionEndFrictionCoefficient, effectivelyMotionless: 0.1); );
_scaleAnimation = Tween<double>( final double tFinal = _getFinalTime(details.scaleVelocity.abs(), widget.interactionEndFrictionCoefficient, effectivelyMotionless: 0.1);
begin: scale, _scaleAnimation = Tween<double>(
end: frictionSimulation.x(tFinal) begin: scale,
).animate(CurvedAnimation( end: frictionSimulation.x(tFinal)
parent: _scaleController, ).animate(CurvedAnimation(
curve: Curves.decelerate parent: _scaleController,
)); curve: Curves.decelerate
_scaleController.duration = Duration(milliseconds: (tFinal * 1000).round()); ));
_scaleAnimation!.addListener(_onScaleAnimate); _scaleController.duration = Duration(milliseconds: (tFinal * 1000).round());
_scaleController.forward(); _scaleAnimation!.addListener(_onScaleAnimate);
_scaleController.forward();
case _GestureType.rotate || null:
break;
} }
} }

View file

@ -14,38 +14,40 @@ enum RadiusType {
void matches(BorderRadius? borderRadius, RadiusType top, RadiusType bottom) { void matches(BorderRadius? borderRadius, RadiusType top, RadiusType bottom) {
final Radius cardRadius = kMaterialEdges[MaterialType.card]!.topLeft; final Radius cardRadius = kMaterialEdges[MaterialType.card]!.topLeft;
if (top == RadiusType.Sharp) { switch (top) {
expect(borderRadius?.topLeft, equals(Radius.zero)); case RadiusType.Sharp:
expect(borderRadius?.topRight, equals(Radius.zero)); expect(borderRadius?.topLeft, equals(Radius.zero));
} else if (top == RadiusType.Shifting) { expect(borderRadius?.topRight, equals(Radius.zero));
expect(borderRadius?.topLeft.x, greaterThan(0.0)); case RadiusType.Shifting:
expect(borderRadius?.topLeft.x, lessThan(cardRadius.x)); expect(borderRadius?.topLeft.x, greaterThan(0.0));
expect(borderRadius?.topLeft.y, greaterThan(0.0)); expect(borderRadius?.topLeft.x, lessThan(cardRadius.x));
expect(borderRadius?.topLeft.y, lessThan(cardRadius.y)); expect(borderRadius?.topLeft.y, greaterThan(0.0));
expect(borderRadius?.topRight.x, greaterThan(0.0)); expect(borderRadius?.topLeft.y, lessThan(cardRadius.y));
expect(borderRadius?.topRight.x, lessThan(cardRadius.x)); expect(borderRadius?.topRight.x, greaterThan(0.0));
expect(borderRadius?.topRight.y, greaterThan(0.0)); expect(borderRadius?.topRight.x, lessThan(cardRadius.x));
expect(borderRadius?.topRight.y, lessThan(cardRadius.y)); expect(borderRadius?.topRight.y, greaterThan(0.0));
} else { expect(borderRadius?.topRight.y, lessThan(cardRadius.y));
expect(borderRadius?.topLeft, equals(cardRadius)); case RadiusType.Round:
expect(borderRadius?.topRight, equals(cardRadius)); expect(borderRadius?.topLeft, equals(cardRadius));
expect(borderRadius?.topRight, equals(cardRadius));
} }
if (bottom == RadiusType.Sharp) { switch (bottom) {
expect(borderRadius?.bottomLeft, equals(Radius.zero)); case RadiusType.Sharp:
expect(borderRadius?.bottomRight, equals(Radius.zero)); expect(borderRadius?.bottomLeft, equals(Radius.zero));
} else if (bottom == RadiusType.Shifting) { expect(borderRadius?.bottomRight, equals(Radius.zero));
expect(borderRadius?.bottomLeft.x, greaterThan(0.0)); case RadiusType.Shifting:
expect(borderRadius?.bottomLeft.x, lessThan(cardRadius.x)); expect(borderRadius?.bottomLeft.x, greaterThan(0.0));
expect(borderRadius?.bottomLeft.y, greaterThan(0.0)); expect(borderRadius?.bottomLeft.x, lessThan(cardRadius.x));
expect(borderRadius?.bottomLeft.y, lessThan(cardRadius.y)); expect(borderRadius?.bottomLeft.y, greaterThan(0.0));
expect(borderRadius?.bottomRight.x, greaterThan(0.0)); expect(borderRadius?.bottomLeft.y, lessThan(cardRadius.y));
expect(borderRadius?.bottomRight.x, lessThan(cardRadius.x)); expect(borderRadius?.bottomRight.x, greaterThan(0.0));
expect(borderRadius?.bottomRight.y, greaterThan(0.0)); expect(borderRadius?.bottomRight.x, lessThan(cardRadius.x));
expect(borderRadius?.bottomRight.y, lessThan(cardRadius.y)); expect(borderRadius?.bottomRight.y, greaterThan(0.0));
} else { expect(borderRadius?.bottomRight.y, lessThan(cardRadius.y));
expect(borderRadius?.bottomLeft, equals(cardRadius)); case RadiusType.Round:
expect(borderRadius?.bottomRight, equals(cardRadius)); expect(borderRadius?.bottomLeft, equals(cardRadius));
expect(borderRadius?.bottomRight, equals(cardRadius));
} }
} }

View file

@ -221,56 +221,57 @@ class MacOSTestTextInputKeyHandler extends TestTextInputKeyHandler {
@override @override
Future<void> handleKeyDownEvent(LogicalKeyboardKey key) async { Future<void> handleKeyDownEvent(LogicalKeyboardKey key) async {
if (key == LogicalKeyboardKey.shift || switch (key) {
key == LogicalKeyboardKey.shiftLeft || case LogicalKeyboardKey.shift:
key == LogicalKeyboardKey.shiftRight) { case LogicalKeyboardKey.shiftLeft:
_shift = true; case LogicalKeyboardKey.shiftRight:
} else if (key == LogicalKeyboardKey.alt || _shift = true;
key == LogicalKeyboardKey.altLeft || case LogicalKeyboardKey.alt:
key == LogicalKeyboardKey.altRight) { case LogicalKeyboardKey.altLeft:
_alt = true; case LogicalKeyboardKey.altRight:
} else if (key == LogicalKeyboardKey.meta || _alt = true;
key == LogicalKeyboardKey.metaLeft || case LogicalKeyboardKey.meta:
key == LogicalKeyboardKey.metaRight) { case LogicalKeyboardKey.metaLeft:
_meta = true; case LogicalKeyboardKey.metaRight:
} else if (key == LogicalKeyboardKey.control || _meta = true;
key == LogicalKeyboardKey.controlLeft || case LogicalKeyboardKey.control:
key == LogicalKeyboardKey.controlRight) { case LogicalKeyboardKey.controlLeft:
_control = true; case LogicalKeyboardKey.controlRight:
} else { _control = true;
for (final MapEntry<SingleActivator, List<String>> entry default:
in _macOSActivatorToSelectors.entries) { for (final MapEntry<SingleActivator, List<String>> entry in _macOSActivatorToSelectors.entries) {
final SingleActivator activator = entry.key; final SingleActivator activator = entry.key;
if (activator.triggers.first == key && if (activator.triggers.first == key &&
activator.shift == _shift && activator.shift == _shift &&
activator.alt == _alt && activator.alt == _alt &&
activator.meta == _meta && activator.meta == _meta &&
activator.control == _control) { activator.control == _control) {
await _sendSelectors(entry.value); await _sendSelectors(entry.value);
return; return;
}
} }
}
} }
} }
@override @override
Future<void> handleKeyUpEvent(LogicalKeyboardKey key) async { Future<void> handleKeyUpEvent(LogicalKeyboardKey key) async {
if (key == LogicalKeyboardKey.shift || switch (key) {
key == LogicalKeyboardKey.shiftLeft || case LogicalKeyboardKey.shift:
key == LogicalKeyboardKey.shiftRight) { case LogicalKeyboardKey.shiftLeft:
_shift = false; case LogicalKeyboardKey.shiftRight:
} else if (key == LogicalKeyboardKey.alt || _shift = false;
key == LogicalKeyboardKey.altLeft || case LogicalKeyboardKey.alt:
key == LogicalKeyboardKey.altRight) { case LogicalKeyboardKey.altLeft:
_alt = false; case LogicalKeyboardKey.altRight:
} else if (key == LogicalKeyboardKey.meta || _alt = false;
key == LogicalKeyboardKey.metaLeft || case LogicalKeyboardKey.meta:
key == LogicalKeyboardKey.metaRight) { case LogicalKeyboardKey.metaLeft:
_meta = false; case LogicalKeyboardKey.metaRight:
} else if (key == LogicalKeyboardKey.control || _meta = false;
key == LogicalKeyboardKey.controlLeft || case LogicalKeyboardKey.control:
key == LogicalKeyboardKey.controlRight) { case LogicalKeyboardKey.controlLeft:
_control = false; case LogicalKeyboardKey.controlRight:
_control = false;
} }
} }

View file

@ -165,25 +165,26 @@ class AndroidDevices extends PollingDeviceDiscovery {
info['model'] = cleanAdbDeviceName(model); info['model'] = cleanAdbDeviceName(model);
} }
if (deviceState == 'unauthorized') { switch (deviceState) {
diagnostics?.add( case 'unauthorized':
'Device $deviceID is not authorized.\n' diagnostics?.add(
'You might need to check your device for an authorization dialog.' 'Device $deviceID is not authorized.\n'
); 'You might need to check your device for an authorization dialog.'
} else if (deviceState == 'offline') { );
diagnostics?.add('Device $deviceID is offline.'); case 'offline':
} else { diagnostics?.add('Device $deviceID is offline.');
devices?.add(AndroidDevice( default:
deviceID, devices?.add(AndroidDevice(
productID: info['product'], deviceID,
modelID: info['model'] ?? deviceID, productID: info['product'],
deviceCodeName: info['device'], modelID: info['model'] ?? deviceID,
androidSdk: _androidSdk!, deviceCodeName: info['device'],
fileSystem: _fileSystem, androidSdk: _androidSdk!,
logger: _logger, fileSystem: _fileSystem,
platform: _platform, logger: _logger,
processManager: _processManager, platform: _platform,
)); processManager: _processManager,
));
} }
} else { } else {
diagnostics?.add( diagnostics?.add(

View file

@ -866,10 +866,11 @@ void _printWarningDisabledPlatform(List<String> platforms) {
final List<String> web = <String>[]; final List<String> web = <String>[];
for (final String platform in platforms) { for (final String platform in platforms) {
if (platform == 'web') { switch (platform) {
web.add(platform); case 'web':
} else if (platform == 'macos' || platform == 'windows' || platform == 'linux') { web.add(platform);
desktop.add(platform); case 'macos' || 'windows' || 'linux':
desktop.add(platform);
} }
} }

View file

@ -152,12 +152,13 @@ class AnalysisServer {
} }
if (paramsMap != null) { if (paramsMap != null) {
if (event == 'server.status') { switch (event) {
_handleStatus(paramsMap); case 'server.status':
} else if (event == 'analysis.errors') { _handleStatus(paramsMap);
_handleAnalysisIssues(paramsMap); case 'analysis.errors':
} else if (event == 'server.error') { _handleAnalysisIssues(paramsMap);
_handleServerError(paramsMap); case 'server.error':
_handleServerError(paramsMap);
} }
} }
} else if (response['error'] != null) { } else if (response['error'] != null) {

View file

@ -120,18 +120,22 @@ class FlutterDevice {
// TODO(zanderso): consistently provide these flags across platforms. // TODO(zanderso): consistently provide these flags across platforms.
final String platformDillName; final String platformDillName;
final List<String> extraFrontEndOptions = List<String>.of(buildInfo.extraFrontEndOptions); final List<String> extraFrontEndOptions = List<String>.of(buildInfo.extraFrontEndOptions);
if (buildInfo.nullSafetyMode == NullSafetyMode.unsound) { switch (buildInfo.nullSafetyMode) {
platformDillName = 'ddc_outline.dill'; case NullSafetyMode.unsound:
if (!extraFrontEndOptions.contains('--no-sound-null-safety')) { platformDillName = 'ddc_outline.dill';
extraFrontEndOptions.add('--no-sound-null-safety'); if (!extraFrontEndOptions.contains('--no-sound-null-safety')) {
} extraFrontEndOptions.add('--no-sound-null-safety');
} else if (buildInfo.nullSafetyMode == NullSafetyMode.sound) { }
platformDillName = 'ddc_outline_sound.dill'; case NullSafetyMode.sound:
if (!extraFrontEndOptions.contains('--sound-null-safety')) { platformDillName = 'ddc_outline_sound.dill';
extraFrontEndOptions.add('--sound-null-safety'); if (!extraFrontEndOptions.contains('--sound-null-safety')) {
} extraFrontEndOptions.add('--sound-null-safety');
} else { }
throw StateError('Expected buildInfo.nullSafetyMode to be one of unsound or sound, got ${buildInfo.nullSafetyMode}'); case NullSafetyMode.autodetect:
throw StateError(
'Expected buildInfo.nullSafetyMode to be one of unsound or sound, '
'got NullSafetyMode.autodetect',
);
} }
final String platformDillPath = globals.fs.path.join( final String platformDillPath = globals.fs.path.join(

View file

@ -146,19 +146,20 @@ class HotRunner extends ResidentRunner {
return; return;
} }
if (flutterDevices.length == 1) { switch (flutterDevices.length) {
final Device device = flutterDevices.first.device!; case 1:
_targetPlatform = getNameForTargetPlatform(await device.targetPlatform); final Device device = flutterDevices.first.device!;
_sdkName = await device.sdkNameAndVersion; _targetPlatform = getNameForTargetPlatform(await device.targetPlatform);
_emulator = await device.isLocalEmulator; _sdkName = await device.sdkNameAndVersion;
} else if (flutterDevices.length > 1) { _emulator = await device.isLocalEmulator;
_targetPlatform = 'multiple'; case > 1:
_sdkName = 'multiple'; _targetPlatform = 'multiple';
_emulator = false; _sdkName = 'multiple';
} else { _emulator = false;
_targetPlatform = 'unknown'; default:
_sdkName = 'unknown'; _targetPlatform = 'unknown';
_emulator = false; _sdkName = 'unknown';
_emulator = false;
} }
} }

View file

@ -57,17 +57,18 @@ class WebTestCompiler {
// TODO(zanderso): to support autodetect this would need to partition the source code into // TODO(zanderso): to support autodetect this would need to partition the source code into
// a sound and unsound set and perform separate compilations // a sound and unsound set and perform separate compilations
final List<String> extraFrontEndOptions = List<String>.of(buildInfo.extraFrontEndOptions); final List<String> extraFrontEndOptions = List<String>.of(buildInfo.extraFrontEndOptions);
if (buildInfo.nullSafetyMode == NullSafetyMode.unsound || buildInfo.nullSafetyMode == NullSafetyMode.autodetect) { switch (buildInfo.nullSafetyMode) {
platformDillName = 'ddc_outline.dill'; case NullSafetyMode.unsound || NullSafetyMode.autodetect:
if (!extraFrontEndOptions.contains('--no-sound-null-safety')) { platformDillName = 'ddc_outline.dill';
extraFrontEndOptions.add('--no-sound-null-safety'); if (!extraFrontEndOptions.contains('--no-sound-null-safety')) {
} extraFrontEndOptions.add('--no-sound-null-safety');
} else if (buildInfo.nullSafetyMode == NullSafetyMode.sound) { }
languageVersion = currentLanguageVersion(_fileSystem, Cache.flutterRoot!); case NullSafetyMode.sound:
platformDillName = 'ddc_outline_sound.dill'; languageVersion = currentLanguageVersion(_fileSystem, Cache.flutterRoot!);
if (!extraFrontEndOptions.contains('--sound-null-safety')) { platformDillName = 'ddc_outline_sound.dill';
extraFrontEndOptions.add('--sound-null-safety'); if (!extraFrontEndOptions.contains('--sound-null-safety')) {
} extraFrontEndOptions.add('--sound-null-safety');
}
} }
final String platformDillPath = _fileSystem.path.join( final String platformDillPath = _fileSystem.path.join(

View file

@ -147,12 +147,13 @@ void main() {
// shadow the exception we would have gotten. // shadow the exception we would have gotten.
expect(stdout, isNot(contains('EXCEPTION CAUGHT BY WIDGETS LIBRARY'))); expect(stdout, isNot(contains('EXCEPTION CAUGHT BY WIDGETS LIBRARY')));
if (device == 'macos') { switch (device) {
expectDylibIsBundledMacOS(exampleDirectory, buildMode); case 'macos':
} else if (device == 'linux') { expectDylibIsBundledMacOS(exampleDirectory, buildMode);
expectDylibIsBundledLinux(exampleDirectory, buildMode); case 'linux':
} else if (device == 'windows') { expectDylibIsBundledLinux(exampleDirectory, buildMode);
expectDylibIsBundledWindows(exampleDirectory, buildMode); case 'windows':
expectDylibIsBundledWindows(exampleDirectory, buildMode);
} }
if (device == hostOs) { if (device == hostOs) {
expectCCompilerIsConfigured(exampleDirectory); expectCCompilerIsConfigured(exampleDirectory);
@ -203,16 +204,17 @@ void main() {
throw Exception('flutter build failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}'); throw Exception('flutter build failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}');
} }
if (buildSubcommand == 'macos') { switch (buildSubcommand) {
expectDylibIsBundledMacOS(exampleDirectory, buildMode); case 'macos':
} else if (buildSubcommand == 'ios') { expectDylibIsBundledMacOS(exampleDirectory, buildMode);
expectDylibIsBundledIos(exampleDirectory, buildMode); case 'ios':
} else if (buildSubcommand == 'linux') { expectDylibIsBundledIos(exampleDirectory, buildMode);
expectDylibIsBundledLinux(exampleDirectory, buildMode); case 'linux':
} else if (buildSubcommand == 'windows') { expectDylibIsBundledLinux(exampleDirectory, buildMode);
expectDylibIsBundledWindows(exampleDirectory, buildMode); case 'windows':
} else if (buildSubcommand == 'apk') { expectDylibIsBundledWindows(exampleDirectory, buildMode);
expectDylibIsBundledAndroid(exampleDirectory, buildMode); case 'apk':
expectDylibIsBundledAndroid(exampleDirectory, buildMode);
} }
expectCCompilerIsConfigured(exampleDirectory); expectCCompilerIsConfigured(exampleDirectory);
}); });