From 26e379e0fcd93981572d48d5b695ed6fa6279061 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 11 Mar 2024 17:04:57 -0600 Subject: [PATCH] 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
This change unfortunately increases the total line length, but it also improves readability. --- .../demo/material/bottom_navigation_demo.dart | 17 +-- dev/manual_tests/lib/overlay_geometry.dart | 17 +-- .../bottom_app_bar/bottom_app_bar.2.dart | 12 +- .../lib/src/cupertino/date_picker.dart | 32 ++--- .../lib/src/cupertino/form_section.dart | 43 ++++--- packages/flutter/lib/src/gestures/arena.dart | 31 ++--- .../flutter/lib/src/gestures/monodrag.dart | 80 +++++++------ packages/flutter/lib/src/material/about.dart | 9 +- .../lib/src/material/toggle_buttons.dart | 32 +++-- .../flutter/lib/src/services/text_input.dart | 47 ++++---- .../lib/src/widgets/interactive_viewer.dart | 109 +++++++++--------- .../material/mergeable_material_test.dart | 62 +++++----- .../lib/src/test_text_input_key_handler.dart | 89 +++++++------- .../src/android/android_device_discovery.dart | 39 ++++--- .../lib/src/commands/create.dart | 9 +- .../flutter_tools/lib/src/dart/analysis.dart | 13 ++- .../lib/src/resident_runner.dart | 28 +++-- packages/flutter_tools/lib/src/run_hot.dart | 27 ++--- .../lib/src/test/web_test_compiler.dart | 23 ++-- .../isolated/native_assets_test.dart | 34 +++--- 20 files changed, 404 insertions(+), 349 deletions(-) diff --git a/dev/integration_tests/flutter_gallery/lib/demo/material/bottom_navigation_demo.dart b/dev/integration_tests/flutter_gallery/lib/demo/material/bottom_navigation_demo.dart index df1a559c01be1..be4ea21053034 100644 --- a/dev/integration_tests/flutter_gallery/lib/demo/material/bottom_navigation_demo.dart +++ b/dev/integration_tests/flutter_gallery/lib/demo/material/bottom_navigation_demo.dart @@ -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( diff --git a/dev/manual_tests/lib/overlay_geometry.dart b/dev/manual_tests/lib/overlay_geometry.dart index 813b31303c0a1..edd784e65dcae 100644 --- a/dev/manual_tests/lib/overlay_geometry.dart +++ b/dev/manual_tests/lib/overlay_geometry.dart @@ -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; } } diff --git a/examples/api/lib/material/bottom_app_bar/bottom_app_bar.2.dart b/examples/api/lib/material/bottom_app_bar/bottom_app_bar.2.dart index 1aa6b981b8b51..35e03639130f8 100644 --- a/examples/api/lib/material/bottom_app_bar/bottom_app_bar.2.dart +++ b/examples/api/lib/material/bottom_app_bar/bottom_app_bar.2.dart @@ -41,11 +41,13 @@ class _BottomAppBarDemoState extends State { _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(); } } diff --git a/packages/flutter/lib/src/cupertino/date_picker.dart b/packages/flutter/lib/src/cupertino/date_picker.dart index 1e0fe079a5f1f..08a44fdc4a7d9 100644 --- a/packages/flutter/lib/src/cupertino/date_picker.dart +++ b/packages/flutter/lib/src/cupertino/date_picker.dart @@ -1021,25 +1021,29 @@ class _CupertinoDatePickerDateTimeState extends State { // 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)); } } diff --git a/packages/flutter/lib/src/cupertino/form_section.dart b/packages/flutter/lib/src/cupertino/form_section.dart index c3d662575a40a..6824a96d0d89e 100644 --- a/packages/flutter/lib/src/cupertino/form_section.dart +++ b/packages/flutter/lib/src/cupertino/form_section.dart @@ -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, + ); + } } } diff --git a/packages/flutter/lib/src/gestures/arena.dart b/packages/flutter/lib/src/gestures/arena.dart index 243f0691c79d6..c1d9939dc2730 100644 --- a/packages/flutter/lib/src/gestures/arena.dart +++ b/packages/flutter/lib/src/gestures/arena.dart @@ -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); + } } } diff --git a/packages/flutter/lib/src/gestures/monodrag.dart b/packages/flutter/lib/src/gestures/monodrag.dart index fbd9eff120d1f..571e0049234ac 100644 --- a/packages/flutter/lib/src/gestures/monodrag.dart +++ b/packages/flutter/lib/src/gestures/monodrag.dart @@ -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); } } @@ -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); } } diff --git a/packages/flutter/lib/src/material/about.dart b/packages/flutter/lib/src/material/about.dart index 84c3028d5368c..a61f3a0d79740 100644 --- a/packages/flutter/lib/src/material/about.dart +++ b/packages/flutter/lib/src/material/about.dart @@ -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; } } diff --git a/packages/flutter/lib/src/material/toggle_buttons.dart b/packages/flutter/lib/src/material/toggle_buttons.dart index 15117edf64210..06727bcee7b65 100644 --- a/packages/flutter/lib/src/material/toggle_buttons.dart +++ b/packages/flutter/lib/src/material/toggle_buttons.dart @@ -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( diff --git a/packages/flutter/lib/src/services/text_input.dart b/packages/flutter/lib/src/services/text_input.dart index 9bc5babad1c77..1db2dad2e55f1 100644 --- a/packages/flutter/lib/src/services/text_input.dart +++ b/packages/flutter/lib/src/services/text_input.dart @@ -1795,29 +1795,30 @@ class TextInput { Future _handleTextInputInvocation(MethodCall methodCall) async { final String method = methodCall.method; - if (method == 'TextInputClient.focusElement') { - final List args = methodCall.arguments as List; - _scribbleClients[args[0]]?.onScribbleFocus(Offset((args[1] as num).toDouble(), (args[2] as num).toDouble())); - return; - } else if (method == 'TextInputClient.requestElementsInRect') { - final List args = (methodCall.arguments as List).cast().map((num value) => value.toDouble()).toList(); - return _scribbleClients.keys.where((String elementIdentifier) { - final Rect rect = Rect.fromLTWH(args[0], args[1], args[2], args[3]); - if (!(_scribbleClients[elementIdentifier]?.isInScribbleRect(rect) ?? false)) { - return false; - } - final Rect bounds = _scribbleClients[elementIdentifier]?.bounds ?? Rect.zero; - return !(bounds == Rect.zero || bounds.hasNaN || bounds.isInfinite); - }).map((String elementIdentifier) { - final Rect bounds = _scribbleClients[elementIdentifier]!.bounds; - return [elementIdentifier, ...[bounds.left, bounds.top, bounds.width, bounds.height]]; - }).toList(); - } else if (method == 'TextInputClient.scribbleInteractionBegan') { - _scribbleInProgress = true; - return; - } else if (method == 'TextInputClient.scribbleInteractionFinished') { - _scribbleInProgress = false; - return; + switch (methodCall.method) { + case 'TextInputClient.focusElement': + final List args = methodCall.arguments as List; + _scribbleClients[args[0]]?.onScribbleFocus(Offset((args[1] as num).toDouble(), (args[2] as num).toDouble())); + return; + case 'TextInputClient.requestElementsInRect': + final List args = (methodCall.arguments as List).cast().map((num value) => value.toDouble()).toList(); + return _scribbleClients.keys.where((String elementIdentifier) { + final Rect rect = Rect.fromLTWH(args[0], args[1], args[2], args[3]); + if (!(_scribbleClients[elementIdentifier]?.isInScribbleRect(rect) ?? false)) { + return false; + } + final Rect bounds = _scribbleClients[elementIdentifier]?.bounds ?? Rect.zero; + return !(bounds == Rect.zero || bounds.hasNaN || bounds.isInfinite); + }).map((String elementIdentifier) { + final Rect bounds = _scribbleClients[elementIdentifier]!.bounds; + return [elementIdentifier, ...[bounds.left, bounds.top, bounds.width, bounds.height]]; + }).toList(); + case 'TextInputClient.scribbleInteractionBegan': + _scribbleInProgress = true; + return; + case 'TextInputClient.scribbleInteractionFinished': + _scribbleInProgress = false; + return; } if (_currentConnection == null) { return; diff --git a/packages/flutter/lib/src/widgets/interactive_viewer.dart b/packages/flutter/lib/src/widgets/interactive_viewer.dart index f6d30711007c4..80acec0064428 100644 --- a/packages/flutter/lib/src/widgets/interactive_viewer.dart +++ b/packages/flutter/lib/src/widgets/interactive_viewer.dart @@ -871,59 +871,62 @@ class _InteractiveViewerState extends State with TickerProvid return; } - if (_gestureType == _GestureType.pan) { - if (details.velocity.pixelsPerSecond.distance < kMinFlingVelocity) { - _currentAxis = null; - return; - } - final Vector3 translationVector = _transformationController!.value.getTranslation(); - final Offset translation = Offset(translationVector.x, translationVector.y); - final FrictionSimulation frictionSimulationX = FrictionSimulation( - widget.interactionEndFrictionCoefficient, - translation.dx, - details.velocity.pixelsPerSecond.dx, - ); - final FrictionSimulation frictionSimulationY = FrictionSimulation( - widget.interactionEndFrictionCoefficient, - translation.dy, - details.velocity.pixelsPerSecond.dy, - ); - final double tFinal = _getFinalTime( - details.velocity.pixelsPerSecond.distance, - widget.interactionEndFrictionCoefficient, - ); - _animation = Tween( - begin: translation, - end: Offset(frictionSimulationX.finalX, frictionSimulationY.finalX), - ).animate(CurvedAnimation( - parent: _controller, - curve: Curves.decelerate, - )); - _controller.duration = Duration(milliseconds: (tFinal * 1000).round()); - _animation!.addListener(_onAnimate); - _controller.forward(); - } else if (_gestureType == _GestureType.scale) { - if (details.scaleVelocity.abs() < 0.1) { - _currentAxis = null; - return; - } - final double scale = _transformationController!.value.getMaxScaleOnAxis(); - final FrictionSimulation frictionSimulation = FrictionSimulation( - widget.interactionEndFrictionCoefficient * widget.scaleFactor, - scale, - details.scaleVelocity / 10 - ); - final double tFinal = _getFinalTime(details.scaleVelocity.abs(), widget.interactionEndFrictionCoefficient, effectivelyMotionless: 0.1); - _scaleAnimation = Tween( - begin: scale, - end: frictionSimulation.x(tFinal) - ).animate(CurvedAnimation( - parent: _scaleController, - curve: Curves.decelerate - )); - _scaleController.duration = Duration(milliseconds: (tFinal * 1000).round()); - _scaleAnimation!.addListener(_onScaleAnimate); - _scaleController.forward(); + switch (_gestureType) { + case _GestureType.pan: + if (details.velocity.pixelsPerSecond.distance < kMinFlingVelocity) { + _currentAxis = null; + return; + } + final Vector3 translationVector = _transformationController!.value.getTranslation(); + final Offset translation = Offset(translationVector.x, translationVector.y); + final FrictionSimulation frictionSimulationX = FrictionSimulation( + widget.interactionEndFrictionCoefficient, + translation.dx, + details.velocity.pixelsPerSecond.dx, + ); + final FrictionSimulation frictionSimulationY = FrictionSimulation( + widget.interactionEndFrictionCoefficient, + translation.dy, + details.velocity.pixelsPerSecond.dy, + ); + final double tFinal = _getFinalTime( + details.velocity.pixelsPerSecond.distance, + widget.interactionEndFrictionCoefficient, + ); + _animation = Tween( + begin: translation, + end: Offset(frictionSimulationX.finalX, frictionSimulationY.finalX), + ).animate(CurvedAnimation( + parent: _controller, + curve: Curves.decelerate, + )); + _controller.duration = Duration(milliseconds: (tFinal * 1000).round()); + _animation!.addListener(_onAnimate); + _controller.forward(); + case _GestureType.scale: + if (details.scaleVelocity.abs() < 0.1) { + _currentAxis = null; + return; + } + final double scale = _transformationController!.value.getMaxScaleOnAxis(); + final FrictionSimulation frictionSimulation = FrictionSimulation( + widget.interactionEndFrictionCoefficient * widget.scaleFactor, + scale, + details.scaleVelocity / 10 + ); + final double tFinal = _getFinalTime(details.scaleVelocity.abs(), widget.interactionEndFrictionCoefficient, effectivelyMotionless: 0.1); + _scaleAnimation = Tween( + begin: scale, + end: frictionSimulation.x(tFinal) + ).animate(CurvedAnimation( + parent: _scaleController, + curve: Curves.decelerate + )); + _scaleController.duration = Duration(milliseconds: (tFinal * 1000).round()); + _scaleAnimation!.addListener(_onScaleAnimate); + _scaleController.forward(); + case _GestureType.rotate || null: + break; } } diff --git a/packages/flutter/test/material/mergeable_material_test.dart b/packages/flutter/test/material/mergeable_material_test.dart index b9de0f7f1ecfa..4b7c49ab2a55c 100644 --- a/packages/flutter/test/material/mergeable_material_test.dart +++ b/packages/flutter/test/material/mergeable_material_test.dart @@ -14,38 +14,40 @@ enum RadiusType { void matches(BorderRadius? borderRadius, RadiusType top, RadiusType bottom) { final Radius cardRadius = kMaterialEdges[MaterialType.card]!.topLeft; - if (top == RadiusType.Sharp) { - expect(borderRadius?.topLeft, equals(Radius.zero)); - expect(borderRadius?.topRight, equals(Radius.zero)); - } else if (top == RadiusType.Shifting) { - expect(borderRadius?.topLeft.x, greaterThan(0.0)); - expect(borderRadius?.topLeft.x, lessThan(cardRadius.x)); - expect(borderRadius?.topLeft.y, greaterThan(0.0)); - expect(borderRadius?.topLeft.y, lessThan(cardRadius.y)); - expect(borderRadius?.topRight.x, greaterThan(0.0)); - expect(borderRadius?.topRight.x, lessThan(cardRadius.x)); - expect(borderRadius?.topRight.y, greaterThan(0.0)); - expect(borderRadius?.topRight.y, lessThan(cardRadius.y)); - } else { - expect(borderRadius?.topLeft, equals(cardRadius)); - expect(borderRadius?.topRight, equals(cardRadius)); + switch (top) { + case RadiusType.Sharp: + expect(borderRadius?.topLeft, equals(Radius.zero)); + expect(borderRadius?.topRight, equals(Radius.zero)); + case RadiusType.Shifting: + expect(borderRadius?.topLeft.x, greaterThan(0.0)); + expect(borderRadius?.topLeft.x, lessThan(cardRadius.x)); + expect(borderRadius?.topLeft.y, greaterThan(0.0)); + expect(borderRadius?.topLeft.y, lessThan(cardRadius.y)); + expect(borderRadius?.topRight.x, greaterThan(0.0)); + expect(borderRadius?.topRight.x, lessThan(cardRadius.x)); + expect(borderRadius?.topRight.y, greaterThan(0.0)); + expect(borderRadius?.topRight.y, lessThan(cardRadius.y)); + case RadiusType.Round: + expect(borderRadius?.topLeft, equals(cardRadius)); + expect(borderRadius?.topRight, equals(cardRadius)); } - if (bottom == RadiusType.Sharp) { - expect(borderRadius?.bottomLeft, equals(Radius.zero)); - expect(borderRadius?.bottomRight, equals(Radius.zero)); - } else if (bottom == RadiusType.Shifting) { - expect(borderRadius?.bottomLeft.x, greaterThan(0.0)); - expect(borderRadius?.bottomLeft.x, lessThan(cardRadius.x)); - expect(borderRadius?.bottomLeft.y, greaterThan(0.0)); - expect(borderRadius?.bottomLeft.y, lessThan(cardRadius.y)); - expect(borderRadius?.bottomRight.x, greaterThan(0.0)); - expect(borderRadius?.bottomRight.x, lessThan(cardRadius.x)); - expect(borderRadius?.bottomRight.y, greaterThan(0.0)); - expect(borderRadius?.bottomRight.y, lessThan(cardRadius.y)); - } else { - expect(borderRadius?.bottomLeft, equals(cardRadius)); - expect(borderRadius?.bottomRight, equals(cardRadius)); + switch (bottom) { + case RadiusType.Sharp: + expect(borderRadius?.bottomLeft, equals(Radius.zero)); + expect(borderRadius?.bottomRight, equals(Radius.zero)); + case RadiusType.Shifting: + expect(borderRadius?.bottomLeft.x, greaterThan(0.0)); + expect(borderRadius?.bottomLeft.x, lessThan(cardRadius.x)); + expect(borderRadius?.bottomLeft.y, greaterThan(0.0)); + expect(borderRadius?.bottomLeft.y, lessThan(cardRadius.y)); + expect(borderRadius?.bottomRight.x, greaterThan(0.0)); + expect(borderRadius?.bottomRight.x, lessThan(cardRadius.x)); + expect(borderRadius?.bottomRight.y, greaterThan(0.0)); + expect(borderRadius?.bottomRight.y, lessThan(cardRadius.y)); + case RadiusType.Round: + expect(borderRadius?.bottomLeft, equals(cardRadius)); + expect(borderRadius?.bottomRight, equals(cardRadius)); } } diff --git a/packages/flutter_test/lib/src/test_text_input_key_handler.dart b/packages/flutter_test/lib/src/test_text_input_key_handler.dart index 7dba935d65794..1292fe3d12cb7 100644 --- a/packages/flutter_test/lib/src/test_text_input_key_handler.dart +++ b/packages/flutter_test/lib/src/test_text_input_key_handler.dart @@ -221,56 +221,57 @@ class MacOSTestTextInputKeyHandler extends TestTextInputKeyHandler { @override Future handleKeyDownEvent(LogicalKeyboardKey key) async { - if (key == LogicalKeyboardKey.shift || - key == LogicalKeyboardKey.shiftLeft || - key == LogicalKeyboardKey.shiftRight) { - _shift = true; - } else if (key == LogicalKeyboardKey.alt || - key == LogicalKeyboardKey.altLeft || - key == LogicalKeyboardKey.altRight) { - _alt = true; - } else if (key == LogicalKeyboardKey.meta || - key == LogicalKeyboardKey.metaLeft || - key == LogicalKeyboardKey.metaRight) { - _meta = true; - } else if (key == LogicalKeyboardKey.control || - key == LogicalKeyboardKey.controlLeft || - key == LogicalKeyboardKey.controlRight) { - _control = true; - } else { - for (final MapEntry> entry - in _macOSActivatorToSelectors.entries) { - final SingleActivator activator = entry.key; - if (activator.triggers.first == key && - activator.shift == _shift && - activator.alt == _alt && - activator.meta == _meta && - activator.control == _control) { - await _sendSelectors(entry.value); - return; + switch (key) { + case LogicalKeyboardKey.shift: + case LogicalKeyboardKey.shiftLeft: + case LogicalKeyboardKey.shiftRight: + _shift = true; + case LogicalKeyboardKey.alt: + case LogicalKeyboardKey.altLeft: + case LogicalKeyboardKey.altRight: + _alt = true; + case LogicalKeyboardKey.meta: + case LogicalKeyboardKey.metaLeft: + case LogicalKeyboardKey.metaRight: + _meta = true; + case LogicalKeyboardKey.control: + case LogicalKeyboardKey.controlLeft: + case LogicalKeyboardKey.controlRight: + _control = true; + default: + for (final MapEntry> entry in _macOSActivatorToSelectors.entries) { + final SingleActivator activator = entry.key; + if (activator.triggers.first == key && + activator.shift == _shift && + activator.alt == _alt && + activator.meta == _meta && + activator.control == _control) { + await _sendSelectors(entry.value); + return; + } } - } } } @override Future handleKeyUpEvent(LogicalKeyboardKey key) async { - if (key == LogicalKeyboardKey.shift || - key == LogicalKeyboardKey.shiftLeft || - key == LogicalKeyboardKey.shiftRight) { - _shift = false; - } else if (key == LogicalKeyboardKey.alt || - key == LogicalKeyboardKey.altLeft || - key == LogicalKeyboardKey.altRight) { - _alt = false; - } else if (key == LogicalKeyboardKey.meta || - key == LogicalKeyboardKey.metaLeft || - key == LogicalKeyboardKey.metaRight) { - _meta = false; - } else if (key == LogicalKeyboardKey.control || - key == LogicalKeyboardKey.controlLeft || - key == LogicalKeyboardKey.controlRight) { - _control = false; + switch (key) { + case LogicalKeyboardKey.shift: + case LogicalKeyboardKey.shiftLeft: + case LogicalKeyboardKey.shiftRight: + _shift = false; + case LogicalKeyboardKey.alt: + case LogicalKeyboardKey.altLeft: + case LogicalKeyboardKey.altRight: + _alt = false; + case LogicalKeyboardKey.meta: + case LogicalKeyboardKey.metaLeft: + case LogicalKeyboardKey.metaRight: + _meta = false; + case LogicalKeyboardKey.control: + case LogicalKeyboardKey.controlLeft: + case LogicalKeyboardKey.controlRight: + _control = false; } } diff --git a/packages/flutter_tools/lib/src/android/android_device_discovery.dart b/packages/flutter_tools/lib/src/android/android_device_discovery.dart index e41d0a061dfac..9d2fd5ef9981e 100644 --- a/packages/flutter_tools/lib/src/android/android_device_discovery.dart +++ b/packages/flutter_tools/lib/src/android/android_device_discovery.dart @@ -165,25 +165,26 @@ class AndroidDevices extends PollingDeviceDiscovery { info['model'] = cleanAdbDeviceName(model); } - if (deviceState == 'unauthorized') { - diagnostics?.add( - '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.'); - } else { - devices?.add(AndroidDevice( - deviceID, - productID: info['product'], - modelID: info['model'] ?? deviceID, - deviceCodeName: info['device'], - androidSdk: _androidSdk!, - fileSystem: _fileSystem, - logger: _logger, - platform: _platform, - processManager: _processManager, - )); + switch (deviceState) { + case 'unauthorized': + diagnostics?.add( + 'Device $deviceID is not authorized.\n' + 'You might need to check your device for an authorization dialog.' + ); + case 'offline': + diagnostics?.add('Device $deviceID is offline.'); + default: + devices?.add(AndroidDevice( + deviceID, + productID: info['product'], + modelID: info['model'] ?? deviceID, + deviceCodeName: info['device'], + androidSdk: _androidSdk!, + fileSystem: _fileSystem, + logger: _logger, + platform: _platform, + processManager: _processManager, + )); } } else { diagnostics?.add( diff --git a/packages/flutter_tools/lib/src/commands/create.dart b/packages/flutter_tools/lib/src/commands/create.dart index 0e3972e583402..e470fa222dce8 100644 --- a/packages/flutter_tools/lib/src/commands/create.dart +++ b/packages/flutter_tools/lib/src/commands/create.dart @@ -866,10 +866,11 @@ void _printWarningDisabledPlatform(List platforms) { final List web = []; for (final String platform in platforms) { - if (platform == 'web') { - web.add(platform); - } else if (platform == 'macos' || platform == 'windows' || platform == 'linux') { - desktop.add(platform); + switch (platform) { + case 'web': + web.add(platform); + case 'macos' || 'windows' || 'linux': + desktop.add(platform); } } diff --git a/packages/flutter_tools/lib/src/dart/analysis.dart b/packages/flutter_tools/lib/src/dart/analysis.dart index 5e3e01d1556de..119d1c4dd0023 100644 --- a/packages/flutter_tools/lib/src/dart/analysis.dart +++ b/packages/flutter_tools/lib/src/dart/analysis.dart @@ -152,12 +152,13 @@ class AnalysisServer { } if (paramsMap != null) { - if (event == 'server.status') { - _handleStatus(paramsMap); - } else if (event == 'analysis.errors') { - _handleAnalysisIssues(paramsMap); - } else if (event == 'server.error') { - _handleServerError(paramsMap); + switch (event) { + case 'server.status': + _handleStatus(paramsMap); + case 'analysis.errors': + _handleAnalysisIssues(paramsMap); + case 'server.error': + _handleServerError(paramsMap); } } } else if (response['error'] != null) { diff --git a/packages/flutter_tools/lib/src/resident_runner.dart b/packages/flutter_tools/lib/src/resident_runner.dart index 1e73e423259ce..4e9b38bfec196 100644 --- a/packages/flutter_tools/lib/src/resident_runner.dart +++ b/packages/flutter_tools/lib/src/resident_runner.dart @@ -120,18 +120,22 @@ class FlutterDevice { // TODO(zanderso): consistently provide these flags across platforms. final String platformDillName; final List extraFrontEndOptions = List.of(buildInfo.extraFrontEndOptions); - if (buildInfo.nullSafetyMode == NullSafetyMode.unsound) { - platformDillName = 'ddc_outline.dill'; - if (!extraFrontEndOptions.contains('--no-sound-null-safety')) { - extraFrontEndOptions.add('--no-sound-null-safety'); - } - } else if (buildInfo.nullSafetyMode == NullSafetyMode.sound) { - platformDillName = 'ddc_outline_sound.dill'; - 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}'); + switch (buildInfo.nullSafetyMode) { + case NullSafetyMode.unsound: + platformDillName = 'ddc_outline.dill'; + if (!extraFrontEndOptions.contains('--no-sound-null-safety')) { + extraFrontEndOptions.add('--no-sound-null-safety'); + } + case NullSafetyMode.sound: + platformDillName = 'ddc_outline_sound.dill'; + if (!extraFrontEndOptions.contains('--sound-null-safety')) { + extraFrontEndOptions.add('--sound-null-safety'); + } + 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( diff --git a/packages/flutter_tools/lib/src/run_hot.dart b/packages/flutter_tools/lib/src/run_hot.dart index d1ee30316b4e6..5552a4acaeb4f 100644 --- a/packages/flutter_tools/lib/src/run_hot.dart +++ b/packages/flutter_tools/lib/src/run_hot.dart @@ -146,19 +146,20 @@ class HotRunner extends ResidentRunner { return; } - if (flutterDevices.length == 1) { - final Device device = flutterDevices.first.device!; - _targetPlatform = getNameForTargetPlatform(await device.targetPlatform); - _sdkName = await device.sdkNameAndVersion; - _emulator = await device.isLocalEmulator; - } else if (flutterDevices.length > 1) { - _targetPlatform = 'multiple'; - _sdkName = 'multiple'; - _emulator = false; - } else { - _targetPlatform = 'unknown'; - _sdkName = 'unknown'; - _emulator = false; + switch (flutterDevices.length) { + case 1: + final Device device = flutterDevices.first.device!; + _targetPlatform = getNameForTargetPlatform(await device.targetPlatform); + _sdkName = await device.sdkNameAndVersion; + _emulator = await device.isLocalEmulator; + case > 1: + _targetPlatform = 'multiple'; + _sdkName = 'multiple'; + _emulator = false; + default: + _targetPlatform = 'unknown'; + _sdkName = 'unknown'; + _emulator = false; } } diff --git a/packages/flutter_tools/lib/src/test/web_test_compiler.dart b/packages/flutter_tools/lib/src/test/web_test_compiler.dart index 7787a5ff7bf43..0c82b7eaab5e8 100644 --- a/packages/flutter_tools/lib/src/test/web_test_compiler.dart +++ b/packages/flutter_tools/lib/src/test/web_test_compiler.dart @@ -57,17 +57,18 @@ class WebTestCompiler { // TODO(zanderso): to support autodetect this would need to partition the source code into // a sound and unsound set and perform separate compilations final List extraFrontEndOptions = List.of(buildInfo.extraFrontEndOptions); - if (buildInfo.nullSafetyMode == NullSafetyMode.unsound || buildInfo.nullSafetyMode == NullSafetyMode.autodetect) { - platformDillName = 'ddc_outline.dill'; - if (!extraFrontEndOptions.contains('--no-sound-null-safety')) { - extraFrontEndOptions.add('--no-sound-null-safety'); - } - } else if (buildInfo.nullSafetyMode == NullSafetyMode.sound) { - languageVersion = currentLanguageVersion(_fileSystem, Cache.flutterRoot!); - platformDillName = 'ddc_outline_sound.dill'; - if (!extraFrontEndOptions.contains('--sound-null-safety')) { - extraFrontEndOptions.add('--sound-null-safety'); - } + switch (buildInfo.nullSafetyMode) { + case NullSafetyMode.unsound || NullSafetyMode.autodetect: + platformDillName = 'ddc_outline.dill'; + if (!extraFrontEndOptions.contains('--no-sound-null-safety')) { + extraFrontEndOptions.add('--no-sound-null-safety'); + } + case NullSafetyMode.sound: + languageVersion = currentLanguageVersion(_fileSystem, Cache.flutterRoot!); + platformDillName = 'ddc_outline_sound.dill'; + if (!extraFrontEndOptions.contains('--sound-null-safety')) { + extraFrontEndOptions.add('--sound-null-safety'); + } } final String platformDillPath = _fileSystem.path.join( diff --git a/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart b/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart index eb5f9f1e7266f..898fa92185ac7 100644 --- a/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart +++ b/packages/flutter_tools/test/integration.shard/isolated/native_assets_test.dart @@ -147,12 +147,13 @@ void main() { // shadow the exception we would have gotten. expect(stdout, isNot(contains('EXCEPTION CAUGHT BY WIDGETS LIBRARY'))); - if (device == 'macos') { - expectDylibIsBundledMacOS(exampleDirectory, buildMode); - } else if (device == 'linux') { - expectDylibIsBundledLinux(exampleDirectory, buildMode); - } else if (device == 'windows') { - expectDylibIsBundledWindows(exampleDirectory, buildMode); + switch (device) { + case 'macos': + expectDylibIsBundledMacOS(exampleDirectory, buildMode); + case 'linux': + expectDylibIsBundledLinux(exampleDirectory, buildMode); + case 'windows': + expectDylibIsBundledWindows(exampleDirectory, buildMode); } if (device == hostOs) { expectCCompilerIsConfigured(exampleDirectory); @@ -203,16 +204,17 @@ void main() { throw Exception('flutter build failed: ${result.exitCode}\n${result.stderr}\n${result.stdout}'); } - if (buildSubcommand == 'macos') { - expectDylibIsBundledMacOS(exampleDirectory, buildMode); - } else if (buildSubcommand == 'ios') { - expectDylibIsBundledIos(exampleDirectory, buildMode); - } else if (buildSubcommand == 'linux') { - expectDylibIsBundledLinux(exampleDirectory, buildMode); - } else if (buildSubcommand == 'windows') { - expectDylibIsBundledWindows(exampleDirectory, buildMode); - } else if (buildSubcommand == 'apk') { - expectDylibIsBundledAndroid(exampleDirectory, buildMode); + switch (buildSubcommand) { + case 'macos': + expectDylibIsBundledMacOS(exampleDirectory, buildMode); + case 'ios': + expectDylibIsBundledIos(exampleDirectory, buildMode); + case 'linux': + expectDylibIsBundledLinux(exampleDirectory, buildMode); + case 'windows': + expectDylibIsBundledWindows(exampleDirectory, buildMode); + case 'apk': + expectDylibIsBundledAndroid(exampleDirectory, buildMode); } expectCCompilerIsConfigured(exampleDirectory); });