Skip to content

Commit 4734d80

Browse files
if chains → switch expressions (#147793)
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 <[email protected]>
1 parent c90e18c commit 4734d80

File tree

33 files changed

+194
-297
lines changed

33 files changed

+194
-297
lines changed

dev/benchmarks/macrobenchmarks/lib/src/picture_cache.dart

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -209,13 +209,11 @@ class ListItem extends StatelessWidget {
209209
}
210210

211211
String _convertCountToStr(int count) {
212-
if (count < 10000) {
213-
return count.toString();
214-
} else if (count < 100000) {
215-
return '${(count / 10000).toStringAsPrecision(2)}w';
216-
} else {
217-
return '${(count / 10000).floor()}w';
218-
}
212+
return switch (count) {
213+
< 10000 => count.toString(),
214+
< 100000 => '${(count / 10000).toStringAsPrecision(2)}w',
215+
_ => '${(count / 10000).floor()}w',
216+
};
219217
}
220218

221219
Widget _buildUserInfo() {

dev/benchmarks/macrobenchmarks/lib/src/web/bench_build_material_checkbox.dart

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -31,13 +31,11 @@ class BenchBuildMaterialCheckbox extends WidgetBuildRecorder {
3131
}
3232

3333
Row _buildRow() {
34-
if (_isChecked == null) {
35-
_isChecked = true;
36-
} else if (_isChecked!) {
37-
_isChecked = false;
38-
} else {
39-
_isChecked = null;
40-
}
34+
_isChecked = switch (_isChecked) {
35+
null => true,
36+
true => false,
37+
false => null,
38+
};
4139

4240
return Row(
4341
children: List<Widget>.generate(10, (int i) {

dev/conductor/core/lib/src/start.dart

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -255,16 +255,14 @@ class StartContext extends Context {
255255
if (atBranchPoint) {
256256
return ReleaseType.BETA_INITIAL;
257257
}
258-
259-
if (releaseChannel == 'stable') {
260-
if (lastVersion.type == VersionType.stable) {
261-
return ReleaseType.STABLE_HOTFIX;
262-
} else {
263-
return ReleaseType.STABLE_INITIAL;
264-
}
258+
if (releaseChannel != 'stable') {
259+
return ReleaseType.BETA_HOTFIX;
265260
}
266261

267-
return ReleaseType.BETA_HOTFIX;
262+
return switch (lastVersion.type) {
263+
VersionType.stable => ReleaseType.STABLE_HOTFIX,
264+
VersionType.development || VersionType.gitDescribe || VersionType.latest => ReleaseType.STABLE_INITIAL,
265+
};
268266
}
269267

270268
Future<void> run() async {

dev/integration_tests/flutter_gallery/lib/demo/material/backdrop_demo.dart

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -307,13 +307,11 @@ class _BackdropDemoState extends State<BackdropDemo> with SingleTickerProviderSt
307307
}
308308

309309
final double flingVelocity = details.velocity.pixelsPerSecond.dy / _backdropHeight;
310-
if (flingVelocity < 0.0) {
311-
_controller.fling(velocity: math.max(2.0, -flingVelocity));
312-
} else if (flingVelocity > 0.0) {
313-
_controller.fling(velocity: math.min(-2.0, -flingVelocity));
314-
} else {
315-
_controller.fling(velocity: _controller.value < 0.5 ? -2.0 : 2.0);
316-
}
310+
_controller.fling(velocity: switch (flingVelocity) {
311+
< 0.0 => math.max(2.0, -flingVelocity),
312+
> 0.0 => math.min(-2.0, -flingVelocity),
313+
_ => _controller.value < 0.5 ? -2.0 : 2.0,
314+
});
317315
}
318316

319317
// Stacks a BackdropPanel, which displays the selected category, on top

dev/integration_tests/flutter_gallery/lib/demo/material/list_demo.dart

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -184,21 +184,18 @@ class _ListDemoState extends State<ListDemo> {
184184
}
185185

186186
Widget buildListTile(BuildContext context, String item) {
187-
Widget? secondary;
188-
if (_itemType == _MaterialListType.twoLine) {
189-
secondary = const Text('Additional item information.');
190-
} else if (_itemType == _MaterialListType.threeLine) {
191-
secondary = const Text(
192-
'Even more additional list item information appears on line three.',
193-
);
194-
}
187+
final String? subtitle = switch (_itemType) {
188+
_MaterialListType.oneLine || _MaterialListType.oneLineWithAvatar || null => null,
189+
_MaterialListType.twoLine => 'Additional item information.',
190+
_MaterialListType.threeLine => 'Even more additional list item information appears on line three.',
191+
};
195192
return MergeSemantics(
196193
child: ListTile(
197194
isThreeLine: _itemType == _MaterialListType.threeLine,
198195
dense: _dense,
199196
leading: _showAvatars != null ? ExcludeSemantics(child: CircleAvatar(child: Text(item))) : null,
200197
title: Text('This item represents $item.'),
201-
subtitle: secondary,
198+
subtitle: subtitle != null ? Text(subtitle) : null,
202199
trailing: _showIcons != null ? Icon(Icons.info, color: Theme.of(context).disabledColor) : null,
203200
),
204201
);

dev/integration_tests/flutter_gallery/lib/gallery/backdrop.dart

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -246,13 +246,11 @@ class _BackdropState extends State<Backdrop> with SingleTickerProviderStateMixin
246246
}
247247

248248
final double flingVelocity = details.velocity.pixelsPerSecond.dy / _backdropHeight;
249-
if (flingVelocity < 0.0) {
250-
_controller!.fling(velocity: math.max(2.0, -flingVelocity));
251-
} else if (flingVelocity > 0.0) {
252-
_controller!.fling(velocity: math.min(-2.0, -flingVelocity));
253-
} else {
254-
_controller!.fling(velocity: _controller!.value < 0.5 ? -2.0 : 2.0);
255-
}
249+
_controller!.fling(velocity: switch (flingVelocity) {
250+
< 0.0 => math.max(2.0, -flingVelocity),
251+
> 0.0 => math.min(-2.0, -flingVelocity),
252+
_ => _controller!.value < 0.5 ? -2.0 : 2.0,
253+
});
256254
}
257255

258256
void _toggleFrontLayer() {

dev/integration_tests/flutter_gallery/lib/gallery/syntax_highlighter.dart

Lines changed: 9 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -337,22 +337,14 @@ class _HighlightSpan {
337337
}
338338

339339
TextStyle? textStyle(SyntaxHighlighterStyle? style) {
340-
if (type == _HighlightType.number) {
341-
return style!.numberStyle;
342-
} else if (type == _HighlightType.comment) {
343-
return style!.commentStyle;
344-
} else if (type == _HighlightType.keyword) {
345-
return style!.keywordStyle;
346-
} else if (type == _HighlightType.string) {
347-
return style!.stringStyle;
348-
} else if (type == _HighlightType.punctuation) {
349-
return style!.punctuationStyle;
350-
} else if (type == _HighlightType.klass) {
351-
return style!.classStyle;
352-
} else if (type == _HighlightType.constant) {
353-
return style!.constantStyle;
354-
} else {
355-
return style!.baseStyle;
356-
}
340+
return switch (type) {
341+
_HighlightType.number => style!.numberStyle,
342+
_HighlightType.comment => style!.commentStyle,
343+
_HighlightType.keyword => style!.keywordStyle,
344+
_HighlightType.string => style!.stringStyle,
345+
_HighlightType.punctuation => style!.punctuationStyle,
346+
_HighlightType.klass => style!.classStyle,
347+
_HighlightType.constant => style!.constantStyle,
348+
};
357349
}
358350
}

dev/integration_tests/new_gallery/lib/demos/material/cards_demo.dart

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -416,20 +416,15 @@ class _CardsDemoState extends State<CardsDemo> with RestorationMixin {
416416
for (final TravelDestination destination in destinations(context))
417417
Container(
418418
margin: const EdgeInsets.only(bottom: 8),
419-
child: (destination.cardType == CardType.standard)
420-
? TravelDestinationItem(destination: destination)
421-
: destination.cardType == CardType.tappable
422-
? TappableTravelDestinationItem(
423-
destination: destination)
424-
: SelectableTravelDestinationItem(
425-
destination: destination,
426-
isSelected: _isSelected.value,
427-
onSelected: () {
428-
setState(() {
429-
_isSelected.value = !_isSelected.value;
430-
});
431-
},
432-
),
419+
child: switch (destination.cardType) {
420+
CardType.standard => TravelDestinationItem(destination: destination),
421+
CardType.tappable => TappableTravelDestinationItem(destination: destination),
422+
CardType.selectable => SelectableTravelDestinationItem(
423+
destination: destination,
424+
isSelected: _isSelected.value,
425+
onSelected: () => setState(() { _isSelected.value = !_isSelected.value; }),
426+
),
427+
},
433428
),
434429
],
435430
),

dev/integration_tests/new_gallery/lib/demos/reference/two_pane_demo.dart

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -69,13 +69,10 @@ class TwoPaneDemoState extends State<TwoPaneDemo> with RestorationMixin {
6969
),
7070
endPane: DetailsPane(
7171
selectedIndex: _currentIndex.value,
72-
onClose: widget.type == TwoPaneDemoType.smallScreen
73-
? () {
74-
setState(() {
75-
_currentIndex.value = -1;
76-
});
77-
}
78-
: null,
72+
onClose: switch (widget.type) {
73+
TwoPaneDemoType.smallScreen => () => setState(() { _currentIndex.value = -1; }),
74+
TwoPaneDemoType.foldable || TwoPaneDemoType.tablet => null,
75+
},
7976
),
8077
),
8178
);
@@ -190,11 +187,11 @@ class SimulateScreen extends StatelessWidget {
190187
),
191188
padding: const EdgeInsets.all(14),
192189
child: AspectRatio(
193-
aspectRatio: type == TwoPaneDemoType.foldable
194-
? foldableAspectRatio
195-
: type == TwoPaneDemoType.tablet
196-
? tabletAspectRatio
197-
: singleScreenAspectRatio,
190+
aspectRatio: switch (type) {
191+
TwoPaneDemoType.foldable => foldableAspectRatio,
192+
TwoPaneDemoType.tablet => tabletAspectRatio,
193+
TwoPaneDemoType.smallScreen => singleScreenAspectRatio,
194+
},
198195
child: LayoutBuilder(builder: (BuildContext context, BoxConstraints constraints) {
199196
final Size size = Size(constraints.maxWidth, constraints.maxHeight);
200197
final Size hingeSize = Size(size.width * hingeProportion, size.height);

dev/integration_tests/new_gallery/lib/pages/settings_icon/icon.dart

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,12 +34,12 @@ class _SettingsIconPainter extends CustomPainter {
3434
///
3535
/// The icon is aligned to the bottom-start corner.
3636
void _computeCenterAndScaling(Size size) {
37+
final double dx = switch (Directionality.of(context)) {
38+
TextDirection.rtl => size.width - unitWidth * _scaling / 2,
39+
TextDirection.ltr => unitWidth * _scaling / 2,
40+
};
41+
_center = Offset(dx, size.height - unitHeight * _scaling / 2);
3742
_scaling = min(size.width / unitWidth, size.height / unitHeight);
38-
_center = Directionality.of(context) == TextDirection.ltr
39-
? Offset(
40-
unitWidth * _scaling / 2, size.height - unitHeight * _scaling / 2)
41-
: Offset(size.width - unitWidth * _scaling / 2,
42-
size.height - unitHeight * _scaling / 2);
4343
}
4444

4545
/// Transforms an offset in relative units into an offset in logical pixels.

dev/integration_tests/wide_gamut_test/integration_test/app_test.dart

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -103,21 +103,16 @@ bool _findBGR10Color(
103103
return foundDeepRed;
104104
}
105105

106-
bool _findColor(List<Object?> result, List<double> color) {
106+
bool _findColor(List<dynamic> result, List<double> color) {
107107
expect(result, isNotNull);
108108
expect(result.length, 4);
109-
final int width = (result[0] as int?)!;
110-
final int height = (result[1] as int?)!;
111-
final String format = (result[2] as String?)!;
112-
if (format == 'MTLPixelFormatBGR10_XR') {
113-
return _findBGR10Color((result[3] as Uint8List?)!, width, height, color);
114-
} else if (format == 'MTLPixelFormatBGRA10_XR') {
115-
return _findBGRA10Color((result[3] as Uint8List?)!, width, height, color);
116-
} else if (format == 'MTLPixelFormatRGBA16Float') {
117-
return _findRGBAF16Color((result[3] as Uint8List?)!, width, height, color);
118-
} else {
119-
fail('Unsupported pixel format: $format');
120-
}
109+
final [int width, int height, String format, Uint8List bytes] = result;
110+
return switch (format) {
111+
'MTLPixelFormatBGR10_XR' => _findBGR10Color(bytes, width, height, color),
112+
'MTLPixelFormatBGRA10_XR' => _findBGRA10Color(bytes, width, height, color),
113+
'MTLPixelFormatRGBA16Float' => _findRGBAF16Color(bytes, width, height, color),
114+
_ => fail('Unsupported pixel format: $format'),
115+
};
121116
}
122117

123118
void main() {

dev/manual_tests/lib/density.dart

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -163,14 +163,12 @@ class _OptionsState extends State<Options> {
163163
double sliderValue = 0.0;
164164

165165
String _densityToProfile(VisualDensity density) {
166-
if (density == VisualDensity.standard) {
167-
return 'standard';
168-
} else if (density == VisualDensity.compact) {
169-
return 'compact';
170-
} else if (density == VisualDensity.comfortable) {
171-
return 'comfortable';
172-
}
173-
return 'custom';
166+
return switch (density) {
167+
VisualDensity.standard => 'standard',
168+
VisualDensity.compact => 'compact',
169+
VisualDensity.comfortable => 'comfortable',
170+
_ => 'custom',
171+
};
174172
}
175173

176174
VisualDensity _profileToDensity(String? profile) {

dev/manual_tests/lib/page_view.dart

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,7 @@ class PageViewAppState extends State<PageViewApp> {
7070

7171
void switchScrollDirection() {
7272
setState(() {
73-
scrollDirection = (scrollDirection == Axis.vertical)
74-
? Axis.horizontal
75-
: Axis.vertical;
73+
scrollDirection = flipAxis(scrollDirection);
7674
});
7775
}
7876

@@ -113,9 +111,7 @@ class PageViewAppState extends State<PageViewApp> {
113111
AppBar _buildAppBar() {
114112
return AppBar(
115113
title: const Text('PageView'),
116-
actions: <Widget>[
117-
Text(scrollDirection == Axis.horizontal ? 'horizontal' : 'vertical'),
118-
],
114+
actions: <Widget>[Text(scrollDirection.name)],
119115
);
120116
}
121117

dev/tools/gen_defaults/lib/template.dart

Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -169,16 +169,13 @@ abstract class TokenTemplate {
169169
}
170170

171171
String? _numToString(Object? value, [int? digits]) {
172-
if (value == null) {
173-
return null;
174-
}
175-
if (value is num) {
176-
if (value == double.infinity) {
177-
return 'double.infinity';
178-
}
179-
return digits == null ? value.toString() : value.toStringAsFixed(digits);
180-
}
181-
return getToken(value as String).toString();
172+
return switch (value) {
173+
null => null,
174+
double.infinity => 'double.infinity',
175+
num() when digits == null => value.toString(),
176+
num() => value.toStringAsFixed(digits!),
177+
_ => getToken(value as String).toString(),
178+
};
182179
}
183180

184181
/// Generate an elevation value for the given component token.

dev/tools/gen_keycodes/lib/utils.dart

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -205,18 +205,11 @@ Map<String, String> reverseMapOfListOfString(Map<String, List<String>> inMap, vo
205205
///
206206
/// Will modify the input map.
207207
Map<String, dynamic> removeEmptyValues(Map<String, dynamic> map) {
208-
return map..removeWhere((String key, dynamic value) {
209-
if (value == null) {
210-
return true;
211-
}
212-
if (value is Map<String, dynamic>) {
213-
final Map<String, dynamic> regularizedMap = removeEmptyValues(value);
214-
return regularizedMap.isEmpty;
215-
}
216-
if (value is Iterable<dynamic>) {
217-
return value.isEmpty;
218-
}
219-
return false;
208+
return map..removeWhere((String key, dynamic value) => switch (value) {
209+
null => true,
210+
Map<String, dynamic>() => removeEmptyValues(value).isEmpty,
211+
Iterable<dynamic>() => value.isEmpty,
212+
_ => false,
220213
});
221214
}
222215

examples/api/lib/material/snack_bar/snack_bar.2.dart

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -123,13 +123,10 @@ class _SnackBarExampleState extends State<SnackBarExample> {
123123
const Text('Multi Line Text'),
124124
Switch(
125125
value: _multiLine,
126-
onChanged: _snackBarBehavior == SnackBarBehavior.fixed
127-
? null
128-
: (bool value) {
129-
setState(() {
130-
_multiLine = !_multiLine;
131-
});
132-
},
126+
onChanged: switch (_snackBarBehavior) {
127+
SnackBarBehavior.fixed || null => null,
128+
SnackBarBehavior.floating => (bool value) => setState(() { _multiLine = !_multiLine; }),
129+
},
133130
),
134131
],
135132
),
@@ -139,13 +136,10 @@ class _SnackBarExampleState extends State<SnackBarExample> {
139136
value: _sliderValue,
140137
divisions: 20,
141138
label: _sliderValue.toStringAsFixed(2),
142-
onChanged: _snackBarBehavior == SnackBarBehavior.fixed
143-
? null
144-
: (double value) {
145-
setState(() {
146-
_sliderValue = value;
147-
});
148-
},
139+
onChanged: switch (_snackBarBehavior) {
140+
SnackBarBehavior.fixed || null => null,
141+
SnackBarBehavior.floating => (double value) => setState(() { _sliderValue = value; }),
142+
},
149143
),
150144
]),
151145
const SizedBox(height: 16.0),

0 commit comments

Comments
 (0)