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) {
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(

View file

@ -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;
}
}

View file

@ -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();
}
}

View file

@ -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));
}
}

View file

@ -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,
);
}
}
}

View file

@ -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);
}
}
}

View file

@ -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);
}
}

View file

@ -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;
}
}

View file

@ -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(

View file

@ -1795,29 +1795,30 @@ class TextInput {
Future<dynamic> _handleTextInputInvocation(MethodCall methodCall) async {
final String method = methodCall.method;
if (method == 'TextInputClient.focusElement') {
final List<dynamic> args = methodCall.arguments as List<dynamic>;
_scribbleClients[args[0]]?.onScribbleFocus(Offset((args[1] as num).toDouble(), (args[2] as num).toDouble()));
return;
} else if (method == 'TextInputClient.requestElementsInRect') {
final List<double> args = (methodCall.arguments as List<dynamic>).cast<num>().map<double>((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 <dynamic>[elementIdentifier, ...<dynamic>[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<dynamic> args = methodCall.arguments as List<dynamic>;
_scribbleClients[args[0]]?.onScribbleFocus(Offset((args[1] as num).toDouble(), (args[2] as num).toDouble()));
return;
case 'TextInputClient.requestElementsInRect':
final List<double> args = (methodCall.arguments as List<dynamic>).cast<num>().map<double>((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 <dynamic>[elementIdentifier, ...<dynamic>[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;

View file

@ -871,59 +871,62 @@ class _InteractiveViewerState extends State<InteractiveViewer> 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<Offset>(
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<double>(
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<Offset>(
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<double>(
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;
}
}

View file

@ -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));
}
}

View file

@ -221,56 +221,57 @@ class MacOSTestTextInputKeyHandler extends TestTextInputKeyHandler {
@override
Future<void> 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<SingleActivator, List<String>> 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<SingleActivator, List<String>> 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<void> 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;
}
}

View file

@ -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(

View file

@ -866,10 +866,11 @@ void _printWarningDisabledPlatform(List<String> platforms) {
final List<String> web = <String>[];
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);
}
}

View file

@ -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) {

View file

@ -120,18 +120,22 @@ class FlutterDevice {
// TODO(zanderso): consistently provide these flags across platforms.
final String platformDillName;
final List<String> extraFrontEndOptions = List<String>.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(

View file

@ -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;
}
}

View file

@ -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<String> extraFrontEndOptions = List<String>.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(

View file

@ -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);
});