if chains → switch expressions (#147793)

Previous "if-chains" pull requests:
- https://github.com/flutter/flutter/pull/144905
- https://github.com/flutter/flutter/pull/144977
- https://github.com/flutter/flutter/pull/145194
- https://github.com/flutter/flutter/pull/146293
- https://github.com/flutter/flutter/pull/147472

<br>

I think this one should be enough to wrap things up!

fixes https://github.com/flutter/flutter/issues/144903

---------

Co-authored-by: Victor Sanni <victorsanniay@gmail.com>
This commit is contained in:
Nate 2024-05-10 00:55:48 -06:00 committed by GitHub
parent c90e18c6f5
commit 4734d80f22
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
33 changed files with 194 additions and 297 deletions

View File

@ -209,13 +209,11 @@ class ListItem extends StatelessWidget {
} }
String _convertCountToStr(int count) { String _convertCountToStr(int count) {
if (count < 10000) { return switch (count) {
return count.toString(); < 10000 => count.toString(),
} else if (count < 100000) { < 100000 => '${(count / 10000).toStringAsPrecision(2)}w',
return '${(count / 10000).toStringAsPrecision(2)}w'; _ => '${(count / 10000).floor()}w',
} else { };
return '${(count / 10000).floor()}w';
}
} }
Widget _buildUserInfo() { Widget _buildUserInfo() {

View File

@ -31,13 +31,11 @@ class BenchBuildMaterialCheckbox extends WidgetBuildRecorder {
} }
Row _buildRow() { Row _buildRow() {
if (_isChecked == null) { _isChecked = switch (_isChecked) {
_isChecked = true; null => true,
} else if (_isChecked!) { true => false,
_isChecked = false; false => null,
} else { };
_isChecked = null;
}
return Row( return Row(
children: List<Widget>.generate(10, (int i) { children: List<Widget>.generate(10, (int i) {

View File

@ -255,16 +255,14 @@ class StartContext extends Context {
if (atBranchPoint) { if (atBranchPoint) {
return ReleaseType.BETA_INITIAL; return ReleaseType.BETA_INITIAL;
} }
if (releaseChannel != 'stable') {
if (releaseChannel == 'stable') { return ReleaseType.BETA_HOTFIX;
if (lastVersion.type == VersionType.stable) {
return ReleaseType.STABLE_HOTFIX;
} else {
return ReleaseType.STABLE_INITIAL;
}
} }
return ReleaseType.BETA_HOTFIX; return switch (lastVersion.type) {
VersionType.stable => ReleaseType.STABLE_HOTFIX,
VersionType.development || VersionType.gitDescribe || VersionType.latest => ReleaseType.STABLE_INITIAL,
};
} }
Future<void> run() async { Future<void> run() async {

View File

@ -307,13 +307,11 @@ class _BackdropDemoState extends State<BackdropDemo> with SingleTickerProviderSt
} }
final double flingVelocity = details.velocity.pixelsPerSecond.dy / _backdropHeight; final double flingVelocity = details.velocity.pixelsPerSecond.dy / _backdropHeight;
if (flingVelocity < 0.0) { _controller.fling(velocity: switch (flingVelocity) {
_controller.fling(velocity: math.max(2.0, -flingVelocity)); < 0.0 => math.max(2.0, -flingVelocity),
} else if (flingVelocity > 0.0) { > 0.0 => math.min(-2.0, -flingVelocity),
_controller.fling(velocity: math.min(-2.0, -flingVelocity)); _ => _controller.value < 0.5 ? -2.0 : 2.0,
} else { });
_controller.fling(velocity: _controller.value < 0.5 ? -2.0 : 2.0);
}
} }
// Stacks a BackdropPanel, which displays the selected category, on top // Stacks a BackdropPanel, which displays the selected category, on top

View File

@ -184,21 +184,18 @@ class _ListDemoState extends State<ListDemo> {
} }
Widget buildListTile(BuildContext context, String item) { Widget buildListTile(BuildContext context, String item) {
Widget? secondary; final String? subtitle = switch (_itemType) {
if (_itemType == _MaterialListType.twoLine) { _MaterialListType.oneLine || _MaterialListType.oneLineWithAvatar || null => null,
secondary = const Text('Additional item information.'); _MaterialListType.twoLine => 'Additional item information.',
} else if (_itemType == _MaterialListType.threeLine) { _MaterialListType.threeLine => 'Even more additional list item information appears on line three.',
secondary = const Text( };
'Even more additional list item information appears on line three.',
);
}
return MergeSemantics( return MergeSemantics(
child: ListTile( child: ListTile(
isThreeLine: _itemType == _MaterialListType.threeLine, isThreeLine: _itemType == _MaterialListType.threeLine,
dense: _dense, dense: _dense,
leading: _showAvatars != null ? ExcludeSemantics(child: CircleAvatar(child: Text(item))) : null, leading: _showAvatars != null ? ExcludeSemantics(child: CircleAvatar(child: Text(item))) : null,
title: Text('This item represents $item.'), title: Text('This item represents $item.'),
subtitle: secondary, subtitle: subtitle != null ? Text(subtitle) : null,
trailing: _showIcons != null ? Icon(Icons.info, color: Theme.of(context).disabledColor) : null, trailing: _showIcons != null ? Icon(Icons.info, color: Theme.of(context).disabledColor) : null,
), ),
); );

View File

@ -246,13 +246,11 @@ class _BackdropState extends State<Backdrop> with SingleTickerProviderStateMixin
} }
final double flingVelocity = details.velocity.pixelsPerSecond.dy / _backdropHeight; final double flingVelocity = details.velocity.pixelsPerSecond.dy / _backdropHeight;
if (flingVelocity < 0.0) { _controller!.fling(velocity: switch (flingVelocity) {
_controller!.fling(velocity: math.max(2.0, -flingVelocity)); < 0.0 => math.max(2.0, -flingVelocity),
} else if (flingVelocity > 0.0) { > 0.0 => math.min(-2.0, -flingVelocity),
_controller!.fling(velocity: math.min(-2.0, -flingVelocity)); _ => _controller!.value < 0.5 ? -2.0 : 2.0,
} else { });
_controller!.fling(velocity: _controller!.value < 0.5 ? -2.0 : 2.0);
}
} }
void _toggleFrontLayer() { void _toggleFrontLayer() {

View File

@ -337,22 +337,14 @@ class _HighlightSpan {
} }
TextStyle? textStyle(SyntaxHighlighterStyle? style) { TextStyle? textStyle(SyntaxHighlighterStyle? style) {
if (type == _HighlightType.number) { return switch (type) {
return style!.numberStyle; _HighlightType.number => style!.numberStyle,
} else if (type == _HighlightType.comment) { _HighlightType.comment => style!.commentStyle,
return style!.commentStyle; _HighlightType.keyword => style!.keywordStyle,
} else if (type == _HighlightType.keyword) { _HighlightType.string => style!.stringStyle,
return style!.keywordStyle; _HighlightType.punctuation => style!.punctuationStyle,
} else if (type == _HighlightType.string) { _HighlightType.klass => style!.classStyle,
return style!.stringStyle; _HighlightType.constant => style!.constantStyle,
} else if (type == _HighlightType.punctuation) { };
return style!.punctuationStyle;
} else if (type == _HighlightType.klass) {
return style!.classStyle;
} else if (type == _HighlightType.constant) {
return style!.constantStyle;
} else {
return style!.baseStyle;
}
} }
} }

View File

@ -416,20 +416,15 @@ class _CardsDemoState extends State<CardsDemo> with RestorationMixin {
for (final TravelDestination destination in destinations(context)) for (final TravelDestination destination in destinations(context))
Container( Container(
margin: const EdgeInsets.only(bottom: 8), margin: const EdgeInsets.only(bottom: 8),
child: (destination.cardType == CardType.standard) child: switch (destination.cardType) {
? TravelDestinationItem(destination: destination) CardType.standard => TravelDestinationItem(destination: destination),
: destination.cardType == CardType.tappable CardType.tappable => TappableTravelDestinationItem(destination: destination),
? TappableTravelDestinationItem( CardType.selectable => SelectableTravelDestinationItem(
destination: destination) destination: destination,
: SelectableTravelDestinationItem( isSelected: _isSelected.value,
destination: destination, onSelected: () => setState(() { _isSelected.value = !_isSelected.value; }),
isSelected: _isSelected.value, ),
onSelected: () { },
setState(() {
_isSelected.value = !_isSelected.value;
});
},
),
), ),
], ],
), ),

View File

@ -69,13 +69,10 @@ class TwoPaneDemoState extends State<TwoPaneDemo> with RestorationMixin {
), ),
endPane: DetailsPane( endPane: DetailsPane(
selectedIndex: _currentIndex.value, selectedIndex: _currentIndex.value,
onClose: widget.type == TwoPaneDemoType.smallScreen onClose: switch (widget.type) {
? () { TwoPaneDemoType.smallScreen => () => setState(() { _currentIndex.value = -1; }),
setState(() { TwoPaneDemoType.foldable || TwoPaneDemoType.tablet => null,
_currentIndex.value = -1; },
});
}
: null,
), ),
), ),
); );
@ -190,11 +187,11 @@ class SimulateScreen extends StatelessWidget {
), ),
padding: const EdgeInsets.all(14), padding: const EdgeInsets.all(14),
child: AspectRatio( child: AspectRatio(
aspectRatio: type == TwoPaneDemoType.foldable aspectRatio: switch (type) {
? foldableAspectRatio TwoPaneDemoType.foldable => foldableAspectRatio,
: type == TwoPaneDemoType.tablet TwoPaneDemoType.tablet => tabletAspectRatio,
? tabletAspectRatio TwoPaneDemoType.smallScreen => singleScreenAspectRatio,
: singleScreenAspectRatio, },
child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) { child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
final Size size = Size(constraints.maxWidth, constraints.maxHeight); final Size size = Size(constraints.maxWidth, constraints.maxHeight);
final Size hingeSize = Size(size.width * hingeProportion, size.height); final Size hingeSize = Size(size.width * hingeProportion, size.height);

View File

@ -34,12 +34,12 @@ class _SettingsIconPainter extends CustomPainter {
/// ///
/// The icon is aligned to the bottom-start corner. /// The icon is aligned to the bottom-start corner.
void _computeCenterAndScaling(Size size) { void _computeCenterAndScaling(Size size) {
final double dx = switch (Directionality.of(context)) {
TextDirection.rtl => size.width - unitWidth * _scaling / 2,
TextDirection.ltr => unitWidth * _scaling / 2,
};
_center = Offset(dx, size.height - unitHeight * _scaling / 2);
_scaling = min(size.width / unitWidth, size.height / unitHeight); _scaling = min(size.width / unitWidth, size.height / unitHeight);
_center = Directionality.of(context) == TextDirection.ltr
? Offset(
unitWidth * _scaling / 2, size.height - unitHeight * _scaling / 2)
: Offset(size.width - unitWidth * _scaling / 2,
size.height - unitHeight * _scaling / 2);
} }
/// Transforms an offset in relative units into an offset in logical pixels. /// Transforms an offset in relative units into an offset in logical pixels.

View File

@ -103,21 +103,16 @@ bool _findBGR10Color(
return foundDeepRed; return foundDeepRed;
} }
bool _findColor(List<Object?> result, List<double> color) { bool _findColor(List<dynamic> result, List<double> color) {
expect(result, isNotNull); expect(result, isNotNull);
expect(result.length, 4); expect(result.length, 4);
final int width = (result[0] as int?)!; final [int width, int height, String format, Uint8List bytes] = result;
final int height = (result[1] as int?)!; return switch (format) {
final String format = (result[2] as String?)!; 'MTLPixelFormatBGR10_XR' => _findBGR10Color(bytes, width, height, color),
if (format == 'MTLPixelFormatBGR10_XR') { 'MTLPixelFormatBGRA10_XR' => _findBGRA10Color(bytes, width, height, color),
return _findBGR10Color((result[3] as Uint8List?)!, width, height, color); 'MTLPixelFormatRGBA16Float' => _findRGBAF16Color(bytes, width, height, color),
} else if (format == 'MTLPixelFormatBGRA10_XR') { _ => fail('Unsupported pixel format: $format'),
return _findBGRA10Color((result[3] as Uint8List?)!, width, height, color); };
} else if (format == 'MTLPixelFormatRGBA16Float') {
return _findRGBAF16Color((result[3] as Uint8List?)!, width, height, color);
} else {
fail('Unsupported pixel format: $format');
}
} }
void main() { void main() {

View File

@ -163,14 +163,12 @@ class _OptionsState extends State<Options> {
double sliderValue = 0.0; double sliderValue = 0.0;
String _densityToProfile(VisualDensity density) { String _densityToProfile(VisualDensity density) {
if (density == VisualDensity.standard) { return switch (density) {
return 'standard'; VisualDensity.standard => 'standard',
} else if (density == VisualDensity.compact) { VisualDensity.compact => 'compact',
return 'compact'; VisualDensity.comfortable => 'comfortable',
} else if (density == VisualDensity.comfortable) { _ => 'custom',
return 'comfortable'; };
}
return 'custom';
} }
VisualDensity _profileToDensity(String? profile) { VisualDensity _profileToDensity(String? profile) {

View File

@ -70,9 +70,7 @@ class PageViewAppState extends State<PageViewApp> {
void switchScrollDirection() { void switchScrollDirection() {
setState(() { setState(() {
scrollDirection = (scrollDirection == Axis.vertical) scrollDirection = flipAxis(scrollDirection);
? Axis.horizontal
: Axis.vertical;
}); });
} }
@ -113,9 +111,7 @@ class PageViewAppState extends State<PageViewApp> {
AppBar _buildAppBar() { AppBar _buildAppBar() {
return AppBar( return AppBar(
title: const Text('PageView'), title: const Text('PageView'),
actions: <Widget>[ actions: <Widget>[Text(scrollDirection.name)],
Text(scrollDirection == Axis.horizontal ? 'horizontal' : 'vertical'),
],
); );
} }

View File

@ -169,16 +169,13 @@ abstract class TokenTemplate {
} }
String? _numToString(Object? value, [int? digits]) { String? _numToString(Object? value, [int? digits]) {
if (value == null) { return switch (value) {
return null; null => null,
} double.infinity => 'double.infinity',
if (value is num) { num() when digits == null => value.toString(),
if (value == double.infinity) { num() => value.toStringAsFixed(digits!),
return 'double.infinity'; _ => getToken(value as String).toString(),
} };
return digits == null ? value.toString() : value.toStringAsFixed(digits);
}
return getToken(value as String).toString();
} }
/// Generate an elevation value for the given component token. /// Generate an elevation value for the given component token.

View File

@ -205,18 +205,11 @@ Map<String, String> reverseMapOfListOfString(Map<String, List<String>> inMap, vo
/// ///
/// Will modify the input map. /// Will modify the input map.
Map<String, dynamic> removeEmptyValues(Map<String, dynamic> map) { Map<String, dynamic> removeEmptyValues(Map<String, dynamic> map) {
return map..removeWhere((String key, dynamic value) { return map..removeWhere((String key, dynamic value) => switch (value) {
if (value == null) { null => true,
return true; Map<String, dynamic>() => removeEmptyValues(value).isEmpty,
} Iterable<dynamic>() => value.isEmpty,
if (value is Map<String, dynamic>) { _ => false,
final Map<String, dynamic> regularizedMap = removeEmptyValues(value);
return regularizedMap.isEmpty;
}
if (value is Iterable<dynamic>) {
return value.isEmpty;
}
return false;
}); });
} }

View File

@ -123,13 +123,10 @@ class _SnackBarExampleState extends State<SnackBarExample> {
const Text('Multi Line Text'), const Text('Multi Line Text'),
Switch( Switch(
value: _multiLine, value: _multiLine,
onChanged: _snackBarBehavior == SnackBarBehavior.fixed onChanged: switch (_snackBarBehavior) {
? null SnackBarBehavior.fixed || null => null,
: (bool value) { SnackBarBehavior.floating => (bool value) => setState(() { _multiLine = !_multiLine; }),
setState(() { },
_multiLine = !_multiLine;
});
},
), ),
], ],
), ),
@ -139,13 +136,10 @@ class _SnackBarExampleState extends State<SnackBarExample> {
value: _sliderValue, value: _sliderValue,
divisions: 20, divisions: 20,
label: _sliderValue.toStringAsFixed(2), label: _sliderValue.toStringAsFixed(2),
onChanged: _snackBarBehavior == SnackBarBehavior.fixed onChanged: switch (_snackBarBehavior) {
? null SnackBarBehavior.fixed || null => null,
: (double value) { SnackBarBehavior.floating => (double value) => setState(() { _sliderValue = value; }),
setState(() { },
_sliderValue = value;
});
},
), ),
]), ]),
const SizedBox(height: 16.0), const SizedBox(height: 16.0),

View File

@ -91,17 +91,14 @@ class LinkedScrollController extends ScrollController {
@override @override
void debugFillDescription(List<String> description) { void debugFillDescription(List<String> description) {
super.debugFillDescription(description); super.debugFillDescription(description);
if (before != null && after != null) { final String linkSymbol = switch ((before, after)) {
description.add('links: ⬌'); (null, null) => 'none',
} else if (before != null) { (null, _) => '',
description.add('links: ⬅'); (_, null) => '',
} else if (after != null) { (_, _) => '',
description.add('links: ➡'); };
} else { description.add('links: $linkSymbol');
description.add('links: none');
}
} }
} }
class LinkedScrollPosition extends ScrollPositionWithSingleContext { class LinkedScrollPosition extends ScrollPositionWithSingleContext {

View File

@ -27,11 +27,10 @@ void main() {
final AxisDirection axisDirection; final AxisDirection axisDirection;
switch (axis) { switch (axis) {
case Axis.horizontal: case Axis.horizontal:
if (textDirection == TextDirection.rtl) { axisDirection = switch (textDirection) {
axisDirection = reverse ? AxisDirection.right : AxisDirection.left; TextDirection.rtl => reverse ? AxisDirection.right : AxisDirection.left,
} else { TextDirection.ltr => reverse ? AxisDirection.left : AxisDirection.right,
axisDirection = reverse ? AxisDirection.left : AxisDirection.right; };
}
case Axis.vertical: case Axis.vertical:
axisDirection = reverse ? AxisDirection.up : AxisDirection.down; axisDirection = reverse ? AxisDirection.up : AxisDirection.down;
} }

View File

@ -2722,13 +2722,11 @@ void main() {
addAutomaticKeepAlives: false, addAutomaticKeepAlives: false,
addRepaintBoundaries: false, addRepaintBoundaries: false,
builder: (BuildContext context, ChildVicinity vicinity) { builder: (BuildContext context, ChildVicinity vicinity) {
ValueKey<int>? key; final ValueKey<int>? key = switch (vicinity) {
if (vicinity == const ChildVicinity(xIndex: 1, yIndex: 1)) { ChildVicinity(xIndex: 1, yIndex: 1) => const ValueKey<int>(1),
key = const ValueKey<int>(1); ChildVicinity(xIndex: 1, yIndex: 2) => const ValueKey<int>(2),
} else if (vicinity == _ => null,
const ChildVicinity(xIndex: 1, yIndex: 2)) { };
key = const ValueKey<int>(2);
}
return SizedBox.square(key: key, dimension: 200); return SizedBox.square(key: key, dimension: 200);
}); });
final TwoDimensionalChildBuilderDelegate delegate2 = final TwoDimensionalChildBuilderDelegate delegate2 =
@ -2770,13 +2768,11 @@ void main() {
addAutomaticKeepAlives: false, addAutomaticKeepAlives: false,
addRepaintBoundaries: false, addRepaintBoundaries: false,
builder: (BuildContext context, ChildVicinity vicinity) { builder: (BuildContext context, ChildVicinity vicinity) {
ValueKey<int>? key; final ValueKey<int>? key = switch (vicinity) {
if (vicinity == const ChildVicinity(xIndex: 1, yIndex: 1)) { ChildVicinity(xIndex: 0, yIndex: 0) => const ValueKey<int>(1),
key = const ValueKey<int>(1); ChildVicinity(xIndex: 1, yIndex: 1) => const ValueKey<int>(2),
} else if (vicinity == _ => null,
const ChildVicinity(xIndex: 1, yIndex: 2)) { };
key = const ValueKey<int>(2);
}
return Checkbox(key: key, value: false, onChanged: (_) {}); return Checkbox(key: key, value: false, onChanged: (_) {});
}); });
final TwoDimensionalChildBuilderDelegate delegate2 = final TwoDimensionalChildBuilderDelegate delegate2 =

View File

@ -118,19 +118,12 @@ List<TimelineEvent>? _parseEvents(Map<String, dynamic> json) {
.toList(); .toList();
timelineEvents.sort((TimelineEvent e1, TimelineEvent e2) { timelineEvents.sort((TimelineEvent e1, TimelineEvent e2) {
final int? ts1 = e1.timestampMicros; return switch ((e1.timestampMicros, e2.timestampMicros)) {
final int? ts2 = e2.timestampMicros; (null, null) => 0,
if (ts1 == null) { (_, null) => 1,
if (ts2 == null) { (null, _) => -1,
return 0; (final int ts1, final int ts2) => ts1.compareTo(ts2),
} else { };
return -1;
}
} else if (ts2 == null) {
return 1;
} else {
return ts1.compareTo(ts2);
}
}); });
return timelineEvents; return timelineEvents;

View File

@ -546,12 +546,11 @@ Matcher coversSameAreaAs(Path expectedPath, { required Rect areaToCompare, int s
/// * [flutter_test] for a discussion of test configurations, whereby callers /// * [flutter_test] for a discussion of test configurations, whereby callers
/// may swap out the backend for this matcher. /// may swap out the backend for this matcher.
AsyncMatcher matchesGoldenFile(Object key, {int? version}) { AsyncMatcher matchesGoldenFile(Object key, {int? version}) {
if (key is Uri) { return switch (key) {
return MatchesGoldenFile(key, version); Uri() => MatchesGoldenFile(key, version),
} else if (key is String) { String() => MatchesGoldenFile.forStringPath(key, version),
return MatchesGoldenFile.forStringPath(key, version); _ => throw ArgumentError('Unexpected type for golden file: ${key.runtimeType}'),
} };
throw ArgumentError('Unexpected type for golden file: ${key.runtimeType}');
} }
/// Asserts that a [Finder], [Future<ui.Image>], or [ui.Image] matches a /// Asserts that a [Finder], [Future<ui.Image>], or [ui.Image] matches a

View File

@ -932,14 +932,11 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
final Key? key = widget.key; final Key? key = widget.key;
if (key is ValueKey<dynamic>) { if (key is ValueKey<dynamic>) {
String? keyLabel; final String? keyLabel = switch (key.value) {
if (key is ValueKey<int> || int() || double() || bool() => 'const ${key.runtimeType}(${key.value})',
key is ValueKey<double> || final String value => "const Key('$value')",
key is ValueKey<bool>) { _ => null,
keyLabel = 'const ${key.runtimeType}(${key.value})'; };
} else if (key is ValueKey<String>) {
keyLabel = "const Key('${key.value}')";
}
if (keyLabel != null) { if (keyLabel != null) {
final Iterable<Element> matches = find.byKey(key).evaluate(); final Iterable<Element> matches = find.byKey(key).evaluate();
if (matches.length == 1) { if (matches.length == 1) {

View File

@ -131,12 +131,11 @@ abstract class DeferredComponentsValidator {
if (line.startsWith('Only in android')) { if (line.startsWith('Only in android')) {
continue; continue;
} }
TerminalColor color = TerminalColor.grey; final TerminalColor color = switch (line[0]) {
if (line.startsWith('+')) { '+' => TerminalColor.green,
color = TerminalColor.green; '-' => TerminalColor.red,
} else if (line.startsWith('-')) { _ => TerminalColor.grey,
color = TerminalColor.red; };
}
logger.printStatus(line, color: color); logger.printStatus(line, color: color);
} }
logger.printStatus(''); logger.printStatus('');

View File

@ -115,18 +115,15 @@ class MultiRootFileSystem extends ForwardingFileSystem {
/// If the path is a multiroot uri, resolve to the actual path of the /// If the path is a multiroot uri, resolve to the actual path of the
/// underlying file system. Otherwise, return as is. /// underlying file system. Otherwise, return as is.
dynamic _resolve(dynamic path) { dynamic _resolve(dynamic path) {
Uri uri;
if (path == null) { if (path == null) {
return null; return null;
} else if (path is String) {
uri = Uri.parse(path);
} else if (path is Uri) {
uri = path;
} else if (path is FileSystemEntity) {
uri = path.uri;
} else {
throw ArgumentError('Invalid type for "path": ${(path as Object?)?.runtimeType}');
} }
final Uri uri = switch (path) {
String() => Uri.parse(path),
Uri() => path,
FileSystemEntity() => path.uri,
_ => throw ArgumentError('Invalid type for "path": ${(path as Object?)?.runtimeType}'),
};
if (!uri.hasScheme || uri.scheme != _scheme) { if (!uri.hasScheme || uri.scheme != _scheme) {
return path; return path;

View File

@ -666,11 +666,10 @@ abstract class _BuildIOSSubCommand extends BuildSubCommand {
final String logTarget = environmentType == EnvironmentType.simulator ? 'simulator' : 'device'; final String logTarget = environmentType == EnvironmentType.simulator ? 'simulator' : 'device';
final String typeName = globals.artifacts!.getEngineType(TargetPlatform.ios, buildInfo.mode); final String typeName = globals.artifacts!.getEngineType(TargetPlatform.ios, buildInfo.mode);
if (xcodeBuildAction == XcodeBuildAction.build) { globals.printStatus(switch (xcodeBuildAction) {
globals.printStatus('Building $app for $logTarget ($typeName)...'); XcodeBuildAction.build => 'Building $app for $logTarget ($typeName)...',
} else { XcodeBuildAction.archive => 'Archiving $app...',
globals.printStatus('Archiving $app...'); });
}
final XcodeBuildResult result = await buildXcodeProject( final XcodeBuildResult result = await buildXcodeProject(
app: app, app: app,
buildInfo: buildInfo, buildInfo: buildInfo,

View File

@ -429,22 +429,17 @@ end
Directory simulatorBuildOutput, Directory simulatorBuildOutput,
) async { ) async {
const String appFrameworkName = 'App.framework'; const String appFrameworkName = 'App.framework';
final Status status = globals.logger.startProgress( final Status status = globals.logger.startProgress(
' ├─Building App.xcframework...', ' ├─Building App.xcframework...',
); );
final List<EnvironmentType> environmentTypes = <EnvironmentType>[
EnvironmentType.physical,
EnvironmentType.simulator,
];
final List<Directory> frameworks = <Directory>[]; final List<Directory> frameworks = <Directory>[];
try { try {
for (final EnvironmentType sdkType in environmentTypes) { for (final EnvironmentType sdkType in EnvironmentType.values) {
final Directory outputBuildDirectory = final Directory outputBuildDirectory = switch (sdkType) {
sdkType == EnvironmentType.physical EnvironmentType.physical => iPhoneBuildOutput,
? iPhoneBuildOutput EnvironmentType.simulator => simulatorBuildOutput,
: simulatorBuildOutput; };
frameworks.add(outputBuildDirectory.childDirectory(appFrameworkName)); frameworks.add(outputBuildDirectory.childDirectory(appFrameworkName));
final Environment environment = Environment( final Environment environment = Environment(
projectDir: globals.fs.currentDirectory, projectDir: globals.fs.currentDirectory,

View File

@ -1429,16 +1429,12 @@ Map<String, Object?> _operationResultToMap(OperationResult result) {
} }
Object? _toJsonable(Object? obj) { Object? _toJsonable(Object? obj) {
if (obj is String || obj is int || obj is bool || obj is Map<Object?, Object?> || obj is List<Object?> || obj == null) { return switch (obj) {
return obj; String() || int() || bool() || Map<Object?, Object?>() || List<Object?>() || null => obj,
} OperationResult() => _operationResultToMap(obj),
if (obj is OperationResult) { ToolExit() => obj.message,
return _operationResultToMap(obj); _ => obj.toString(),
} };
if (obj is ToolExit) {
return obj.message;
}
return '$obj';
} }
class NotifyingLogger extends DelegatingLogger { class NotifyingLogger extends DelegatingLogger {

View File

@ -942,12 +942,11 @@ enum ImpellerStatus {
const ImpellerStatus._(this.asBool); const ImpellerStatus._(this.asBool);
factory ImpellerStatus.fromBool(bool? b) { factory ImpellerStatus.fromBool(bool? b) => switch (b) {
if (b == null) { true => enabled,
return platformDefault; false => disabled,
} null => platformDefault,
return b ? enabled : disabled; };
}
final bool? asBool; final bool? asBool;
} }

View File

@ -439,15 +439,11 @@ class IOSCoreDevice {
String? get udid => hardwareProperties?.udid; String? get udid => hardwareProperties?.udid;
DeviceConnectionInterface? get connectionInterface { DeviceConnectionInterface? get connectionInterface {
final String? transportType = connectionProperties?.transportType; return switch (connectionProperties?.transportType?.toLowerCase()) {
if (transportType != null) { 'localnetwork' => DeviceConnectionInterface.wireless,
if (transportType.toLowerCase() == 'localnetwork') { 'wired' => DeviceConnectionInterface.attached,
return DeviceConnectionInterface.wireless; _ => null,
} else if (transportType.toLowerCase() == 'wired') { };
return DeviceConnectionInterface.attached;
}
}
return null;
} }
@visibleForTesting @visibleForTesting

View File

@ -96,16 +96,12 @@ class Node {
// Token constructors. // Token constructors.
Node.openBrace(this.positionInMessage): type = ST.openBrace, value = '{'; Node.openBrace(this.positionInMessage): type = ST.openBrace, value = '{';
Node.closeBrace(this.positionInMessage): type = ST.closeBrace, value = '}'; Node.closeBrace(this.positionInMessage): type = ST.closeBrace, value = '}';
Node.brace(this.positionInMessage, String this.value) { Node.brace(this.positionInMessage, String this.value)
if (value == '{') { : type = switch (value) {
type = ST.openBrace; '{' => ST.openBrace,
} else if (value == '}') { '}' => ST.closeBrace,
type = ST.closeBrace; _ => throw L10nException('Provided value $value is not a brace.')
} else { };
// We should never arrive here.
throw L10nException('Provided value $value is not a brace.');
}
}
Node.equalSign(this.positionInMessage): type = ST.equalSign, value = '='; Node.equalSign(this.positionInMessage): type = ST.equalSign, value = '=';
Node.comma(this.positionInMessage): type = ST.comma, value = ','; Node.comma(this.positionInMessage): type = ST.comma, value = ',';
Node.string(this.positionInMessage, String this.value): type = ST.string; Node.string(this.positionInMessage, String this.value): type = ST.string;

View File

@ -914,12 +914,10 @@ abstract class ResidentHandlers {
final Brightness? current = await flutterDevices.first!.vmService!.flutterBrightnessOverride( final Brightness? current = await flutterDevices.first!.vmService!.flutterBrightnessOverride(
isolateId: views.first.uiIsolate!.id!, isolateId: views.first.uiIsolate!.id!,
); );
Brightness next; final Brightness next = switch (current) {
if (current == Brightness.light) { Brightness.light => Brightness.dark,
next = Brightness.dark; Brightness.dark || null => Brightness.light,
} else { };
next = Brightness.light;
}
for (final FlutterDevice? device in flutterDevices) { for (final FlutterDevice? device in flutterDevices) {
final List<FlutterView> views = await device!.vmService!.getFlutterViews(); final List<FlutterView> views = await device!.vmService!.getFlutterViews();
for (final FlutterView view in views) { for (final FlutterView view in views) {

View File

@ -772,15 +772,14 @@ abstract class FlutterCommand extends Command<void> {
return null; return null;
}(); }();
DeviceConnectionInterface? get deviceConnectionInterface { DeviceConnectionInterface? get deviceConnectionInterface {
if ((argResults?.options.contains(FlutterOptions.kDeviceConnection) ?? false) if ((argResults?.options.contains(FlutterOptions.kDeviceConnection) ?? false)
&& (argResults?.wasParsed(FlutterOptions.kDeviceConnection) ?? false)) { && (argResults?.wasParsed(FlutterOptions.kDeviceConnection) ?? false)) {
final String? connectionType = stringArg(FlutterOptions.kDeviceConnection); return switch (stringArg(FlutterOptions.kDeviceConnection)) {
if (connectionType == 'attached') { 'attached' => DeviceConnectionInterface.attached,
return DeviceConnectionInterface.attached; 'wireless' => DeviceConnectionInterface.wireless,
} else if (connectionType == 'wireless') { _ => null,
return DeviceConnectionInterface.wireless; };
}
} }
return null; return null;
} }

View File

@ -290,13 +290,11 @@ class FakeDeviceManager implements DeviceManager {
Device? getSingleEphemeralDevice(List<Device> devices) => null; Device? getSingleEphemeralDevice(List<Device> devices) => null;
List<Device> filteredDevices(DeviceDiscoveryFilter? filter) { List<Device> filteredDevices(DeviceDiscoveryFilter? filter) {
if (filter?.deviceConnectionInterface == DeviceConnectionInterface.attached) { return switch (filter?.deviceConnectionInterface) {
return attachedDevices; DeviceConnectionInterface.attached => attachedDevices,
} DeviceConnectionInterface.wireless => wirelessDevices,
if (filter?.deviceConnectionInterface == DeviceConnectionInterface.wireless) { null => attachedDevices + wirelessDevices,
return wirelessDevices; };
}
return attachedDevices + wirelessDevices;
} }
} }