Skip to content

Commit

Permalink
if chains → switch expressions (#147793)
Browse files Browse the repository at this point in the history
Previous "if-chains" pull requests:
- flutter/flutter#144905
- flutter/flutter#144977
- flutter/flutter#145194
- flutter/flutter#146293
- flutter/flutter#147472

<br>

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

fixes flutter/flutter#144903

---------

Co-authored-by: Victor Sanni <victorsanniay@gmail.com>
  • Loading branch information
nate-thegrate and victorsanni authored May 10, 2024
1 parent c90e18c commit 4734d80
Show file tree
Hide file tree
Showing 33 changed files with 194 additions and 297 deletions.
12 changes: 5 additions & 7 deletions dev/benchmarks/macrobenchmarks/lib/src/picture_cache.dart
Original file line number Diff line number Diff line change
Expand Up @@ -209,13 +209,11 @@ class ListItem extends StatelessWidget {
}

String _convertCountToStr(int count) {
if (count < 10000) {
return count.toString();
} else if (count < 100000) {
return '${(count / 10000).toStringAsPrecision(2)}w';
} else {
return '${(count / 10000).floor()}w';
}
return switch (count) {
< 10000 => count.toString(),
< 100000 => '${(count / 10000).toStringAsPrecision(2)}w',
_ => '${(count / 10000).floor()}w',
};
}

Widget _buildUserInfo() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,11 @@ class BenchBuildMaterialCheckbox extends WidgetBuildRecorder {
}

Row _buildRow() {
if (_isChecked == null) {
_isChecked = true;
} else if (_isChecked!) {
_isChecked = false;
} else {
_isChecked = null;
}
_isChecked = switch (_isChecked) {
null => true,
true => false,
false => null,
};

return Row(
children: List<Widget>.generate(10, (int i) {
Expand Down
14 changes: 6 additions & 8 deletions dev/conductor/core/lib/src/start.dart
Original file line number Diff line number Diff line change
Expand Up @@ -255,16 +255,14 @@ class StartContext extends Context {
if (atBranchPoint) {
return ReleaseType.BETA_INITIAL;
}

if (releaseChannel == 'stable') {
if (lastVersion.type == VersionType.stable) {
return ReleaseType.STABLE_HOTFIX;
} else {
return ReleaseType.STABLE_INITIAL;
}
if (releaseChannel != 'stable') {
return ReleaseType.BETA_HOTFIX;
}

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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -307,13 +307,11 @@ class _BackdropDemoState extends State<BackdropDemo> with SingleTickerProviderSt
}

final double flingVelocity = details.velocity.pixelsPerSecond.dy / _backdropHeight;
if (flingVelocity < 0.0) {
_controller.fling(velocity: math.max(2.0, -flingVelocity));
} else if (flingVelocity > 0.0) {
_controller.fling(velocity: math.min(-2.0, -flingVelocity));
} else {
_controller.fling(velocity: _controller.value < 0.5 ? -2.0 : 2.0);
}
_controller.fling(velocity: switch (flingVelocity) {
< 0.0 => math.max(2.0, -flingVelocity),
> 0.0 => math.min(-2.0, -flingVelocity),
_ => _controller.value < 0.5 ? -2.0 : 2.0,
});
}

// Stacks a BackdropPanel, which displays the selected category, on top
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -184,21 +184,18 @@ class _ListDemoState extends State<ListDemo> {
}

Widget buildListTile(BuildContext context, String item) {
Widget? secondary;
if (_itemType == _MaterialListType.twoLine) {
secondary = const Text('Additional item information.');
} else if (_itemType == _MaterialListType.threeLine) {
secondary = const Text(
'Even more additional list item information appears on line three.',
);
}
final String? subtitle = switch (_itemType) {
_MaterialListType.oneLine || _MaterialListType.oneLineWithAvatar || null => null,
_MaterialListType.twoLine => 'Additional item information.',
_MaterialListType.threeLine => 'Even more additional list item information appears on line three.',
};
return MergeSemantics(
child: ListTile(
isThreeLine: _itemType == _MaterialListType.threeLine,
dense: _dense,
leading: _showAvatars != null ? ExcludeSemantics(child: CircleAvatar(child: Text(item))) : null,
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,
),
);
Expand Down
12 changes: 5 additions & 7 deletions dev/integration_tests/flutter_gallery/lib/gallery/backdrop.dart
Original file line number Diff line number Diff line change
Expand Up @@ -246,13 +246,11 @@ class _BackdropState extends State<Backdrop> with SingleTickerProviderStateMixin
}

final double flingVelocity = details.velocity.pixelsPerSecond.dy / _backdropHeight;
if (flingVelocity < 0.0) {
_controller!.fling(velocity: math.max(2.0, -flingVelocity));
} else if (flingVelocity > 0.0) {
_controller!.fling(velocity: math.min(-2.0, -flingVelocity));
} else {
_controller!.fling(velocity: _controller!.value < 0.5 ? -2.0 : 2.0);
}
_controller!.fling(velocity: switch (flingVelocity) {
< 0.0 => math.max(2.0, -flingVelocity),
> 0.0 => math.min(-2.0, -flingVelocity),
_ => _controller!.value < 0.5 ? -2.0 : 2.0,
});
}

void _toggleFrontLayer() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -337,22 +337,14 @@ class _HighlightSpan {
}

TextStyle? textStyle(SyntaxHighlighterStyle? style) {
if (type == _HighlightType.number) {
return style!.numberStyle;
} else if (type == _HighlightType.comment) {
return style!.commentStyle;
} else if (type == _HighlightType.keyword) {
return style!.keywordStyle;
} else if (type == _HighlightType.string) {
return style!.stringStyle;
} 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;
}
return switch (type) {
_HighlightType.number => style!.numberStyle,
_HighlightType.comment => style!.commentStyle,
_HighlightType.keyword => style!.keywordStyle,
_HighlightType.string => style!.stringStyle,
_HighlightType.punctuation => style!.punctuationStyle,
_HighlightType.klass => style!.classStyle,
_HighlightType.constant => style!.constantStyle,
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -416,20 +416,15 @@ class _CardsDemoState extends State<CardsDemo> with RestorationMixin {
for (final TravelDestination destination in destinations(context))
Container(
margin: const EdgeInsets.only(bottom: 8),
child: (destination.cardType == CardType.standard)
? TravelDestinationItem(destination: destination)
: destination.cardType == CardType.tappable
? TappableTravelDestinationItem(
destination: destination)
: SelectableTravelDestinationItem(
destination: destination,
isSelected: _isSelected.value,
onSelected: () {
setState(() {
_isSelected.value = !_isSelected.value;
});
},
),
child: switch (destination.cardType) {
CardType.standard => TravelDestinationItem(destination: destination),
CardType.tappable => TappableTravelDestinationItem(destination: destination),
CardType.selectable => SelectableTravelDestinationItem(
destination: destination,
isSelected: _isSelected.value,
onSelected: () => setState(() { _isSelected.value = !_isSelected.value; }),
),
},
),
],
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,13 +69,10 @@ class TwoPaneDemoState extends State<TwoPaneDemo> with RestorationMixin {
),
endPane: DetailsPane(
selectedIndex: _currentIndex.value,
onClose: widget.type == TwoPaneDemoType.smallScreen
? () {
setState(() {
_currentIndex.value = -1;
});
}
: null,
onClose: switch (widget.type) {
TwoPaneDemoType.smallScreen => () => setState(() { _currentIndex.value = -1; }),
TwoPaneDemoType.foldable || TwoPaneDemoType.tablet => null,
},
),
),
);
Expand Down Expand Up @@ -190,11 +187,11 @@ class SimulateScreen extends StatelessWidget {
),
padding: const EdgeInsets.all(14),
child: AspectRatio(
aspectRatio: type == TwoPaneDemoType.foldable
? foldableAspectRatio
: type == TwoPaneDemoType.tablet
? tabletAspectRatio
: singleScreenAspectRatio,
aspectRatio: switch (type) {
TwoPaneDemoType.foldable => foldableAspectRatio,
TwoPaneDemoType.tablet => tabletAspectRatio,
TwoPaneDemoType.smallScreen => singleScreenAspectRatio,
},
child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
final Size size = Size(constraints.maxWidth, constraints.maxHeight);
final Size hingeSize = Size(size.width * hingeProportion, size.height);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@ class _SettingsIconPainter extends CustomPainter {
///
/// The icon is aligned to the bottom-start corner.
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);
_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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,21 +103,16 @@ bool _findBGR10Color(
return foundDeepRed;
}

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

void main() {
Expand Down
14 changes: 6 additions & 8 deletions dev/manual_tests/lib/density.dart
Original file line number Diff line number Diff line change
Expand Up @@ -163,14 +163,12 @@ class _OptionsState extends State<Options> {
double sliderValue = 0.0;

String _densityToProfile(VisualDensity density) {
if (density == VisualDensity.standard) {
return 'standard';
} else if (density == VisualDensity.compact) {
return 'compact';
} else if (density == VisualDensity.comfortable) {
return 'comfortable';
}
return 'custom';
return switch (density) {
VisualDensity.standard => 'standard',
VisualDensity.compact => 'compact',
VisualDensity.comfortable => 'comfortable',
_ => 'custom',
};
}

VisualDensity _profileToDensity(String? profile) {
Expand Down
8 changes: 2 additions & 6 deletions dev/manual_tests/lib/page_view.dart
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,7 @@ class PageViewAppState extends State<PageViewApp> {

void switchScrollDirection() {
setState(() {
scrollDirection = (scrollDirection == Axis.vertical)
? Axis.horizontal
: Axis.vertical;
scrollDirection = flipAxis(scrollDirection);
});
}

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

Expand Down
17 changes: 7 additions & 10 deletions dev/tools/gen_defaults/lib/template.dart
Original file line number Diff line number Diff line change
Expand Up @@ -169,16 +169,13 @@ abstract class TokenTemplate {
}

String? _numToString(Object? value, [int? digits]) {
if (value == null) {
return null;
}
if (value is num) {
if (value == double.infinity) {
return 'double.infinity';
}
return digits == null ? value.toString() : value.toStringAsFixed(digits);
}
return getToken(value as String).toString();
return switch (value) {
null => null,
double.infinity => 'double.infinity',
num() when digits == null => value.toString(),
num() => value.toStringAsFixed(digits!),
_ => getToken(value as String).toString(),
};
}

/// Generate an elevation value for the given component token.
Expand Down
17 changes: 5 additions & 12 deletions dev/tools/gen_keycodes/lib/utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -205,18 +205,11 @@ Map<String, String> reverseMapOfListOfString(Map<String, List<String>> inMap, vo
///
/// Will modify the input map.
Map<String, dynamic> removeEmptyValues(Map<String, dynamic> map) {
return map..removeWhere((String key, dynamic value) {
if (value == null) {
return true;
}
if (value is Map<String, dynamic>) {
final Map<String, dynamic> regularizedMap = removeEmptyValues(value);
return regularizedMap.isEmpty;
}
if (value is Iterable<dynamic>) {
return value.isEmpty;
}
return false;
return map..removeWhere((String key, dynamic value) => switch (value) {
null => true,
Map<String, dynamic>() => removeEmptyValues(value).isEmpty,
Iterable<dynamic>() => value.isEmpty,
_ => false,
});
}

Expand Down
22 changes: 8 additions & 14 deletions examples/api/lib/material/snack_bar/snack_bar.2.dart
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,10 @@ class _SnackBarExampleState extends State<SnackBarExample> {
const Text('Multi Line Text'),
Switch(
value: _multiLine,
onChanged: _snackBarBehavior == SnackBarBehavior.fixed
? null
: (bool value) {
setState(() {
_multiLine = !_multiLine;
});
},
onChanged: switch (_snackBarBehavior) {
SnackBarBehavior.fixed || null => null,
SnackBarBehavior.floating => (bool value) => setState(() { _multiLine = !_multiLine; }),
},
),
],
),
Expand All @@ -139,13 +136,10 @@ class _SnackBarExampleState extends State<SnackBarExample> {
value: _sliderValue,
divisions: 20,
label: _sliderValue.toStringAsFixed(2),
onChanged: _snackBarBehavior == SnackBarBehavior.fixed
? null
: (double value) {
setState(() {
_sliderValue = value;
});
},
onChanged: switch (_snackBarBehavior) {
SnackBarBehavior.fixed || null => null,
SnackBarBehavior.floating => (double value) => setState(() { _sliderValue = value; }),
},
),
]),
const SizedBox(height: 16.0),
Expand Down
Loading

0 comments on commit 4734d80

Please sign in to comment.