Implementing a few switch statements (#150946)

I really like how patterns can be used for variable assignment and avoiding duplicated logic. (related: #150942)

```dart
// before
final GestureRecognizer? recognizer = info.recognizer;
if (recognizer is TapGestureRecognizer) {
  if (recognizer.onTap != null) {
    configuration.onTap = recognizer.onTap;
    configuration.isLink = true;
  }
} else if (recognizer is DoubleTapGestureRecognizer) {
  if (recognizer.onDoubleTap != null) {
    configuration.onTap = recognizer.onDoubleTap;
    configuration.isLink = true;
  }
}

// after
switch (info.recognizer) {
  case TapGestureRecognizer(:final VoidCallback? onTap):
  case DoubleTapGestureRecognizer(onDoubleTap: final VoidCallback? onTap):
    if (onTap != null) {
      configuration.onTap = onTap;
      configuration.isLink = true;
    }
}
```
This commit is contained in:
Nate Wilson 2024-07-01 17:36:32 -06:00 committed by GitHub
parent dbc2dc88bc
commit d07a165d22
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 107 additions and 175 deletions

View File

@ -1884,13 +1884,8 @@ Stream<File> _allFiles(String workingDirectory, String? extension, { required in
if (_isGeneratedPluginRegistrant(entity)) { if (_isGeneratedPluginRegistrant(entity)) {
continue; continue;
} }
if (path.basename(entity.path) == 'flutter_export_environment.sh') { switch (path.basename(entity.path)) {
continue; case 'flutter_export_environment.sh' || 'gradlew.bat' || '.DS_Store':
}
if (path.basename(entity.path) == 'gradlew.bat') {
continue;
}
if (path.basename(entity.path) == '.DS_Store') {
continue; continue;
} }
if (extension == null || path.extension(entity.path) == '.$extension') { if (extension == null || path.extension(entity.path) == '.$extension') {
@ -1901,22 +1896,8 @@ Stream<File> _allFiles(String workingDirectory, String? extension, { required in
if (File(path.join(entity.path, '.dartignore')).existsSync()) { if (File(path.join(entity.path, '.dartignore')).existsSync()) {
continue; continue;
} }
if (path.basename(entity.path) == '.git') { switch (path.basename(entity.path)) {
continue; case '.git' || '.idea' || '.gradle' || '.dart_tool' || 'build':
}
if (path.basename(entity.path) == '.idea') {
continue;
}
if (path.basename(entity.path) == '.gradle') {
continue;
}
if (path.basename(entity.path) == '.dart_tool') {
continue;
}
if (path.basename(entity.path) == '.idea') {
continue;
}
if (path.basename(entity.path) == 'build') {
continue; continue;
} }
pending.addAll(entity.listSync()); pending.addAll(entity.listSync());

View File

@ -164,25 +164,20 @@ String _jsonToMapEntry(String key, dynamic value) {
} }
String _jsonToObject(dynamic json) { String _jsonToObject(dynamic json) {
if (json == null || json is num || json is bool) { switch (json) {
case null || num() || bool():
return '$json'; return '$json';
} case String():
if (json is String) {
return generateEncodedString(currentLocale, json); return generateEncodedString(currentLocale, json);
} case Iterable<Object?>():
final Type type = json.first.runtimeType;
if (json is Iterable<Object?>) {
final String type = json.first.runtimeType.toString();
final StringBuffer buffer = StringBuffer('const <$type>['); final StringBuffer buffer = StringBuffer('const <$type>[');
for (final dynamic value in json) { for (final dynamic value in json) {
buffer.writeln('${_jsonToMap(value)},'); buffer.writeln('${_jsonToMap(value)},');
} }
buffer.write(']'); buffer.write(']');
return buffer.toString(); return buffer.toString();
} case Map<String, dynamic>():
if (json is Map<String, dynamic>) {
final StringBuffer buffer = StringBuffer('<String, Object>{'); final StringBuffer buffer = StringBuffer('<String, Object>{');
json.forEach((String key, dynamic value) { json.forEach((String key, dynamic value) {
buffer.writeln(_jsonToMapEntry(key, value)); buffer.writeln(_jsonToMapEntry(key, value));
@ -195,24 +190,19 @@ String _jsonToObject(dynamic json) {
} }
String _jsonToMap(dynamic json) { String _jsonToMap(dynamic json) {
if (json == null || json is num || json is bool) { switch (json) {
case null || num() || bool():
return '$json'; return '$json';
} case String():
if (json is String) {
return generateEncodedString(currentLocale, json); return generateEncodedString(currentLocale, json);
} case Iterable<dynamic>():
if (json is Iterable) {
final StringBuffer buffer = StringBuffer('<String>['); final StringBuffer buffer = StringBuffer('<String>[');
for (final dynamic value in json) { for (final dynamic value in json) {
buffer.writeln('${_jsonToMap(value)},'); buffer.writeln('${_jsonToMap(value)},');
} }
buffer.write(']'); buffer.write(']');
return buffer.toString(); return buffer.toString();
} case Map<String, dynamic>():
if (json is Map<String, dynamic>) {
final StringBuffer buffer = StringBuffer('<String, Object>{'); final StringBuffer buffer = StringBuffer('<String, Object>{');
json.forEach((String key, dynamic value) { json.forEach((String key, dynamic value) {
buffer.writeln(_jsonToMapEntry(key, value)); buffer.writeln(_jsonToMapEntry(key, value));

View File

@ -148,15 +148,11 @@ void _copy(Directory source, Directory target) {
for (final FileSystemEntity entity in source.listSync(followLinks: false)) { for (final FileSystemEntity entity in source.listSync(followLinks: false)) {
final String name = path.basename(entity.path); final String name = path.basename(entity.path);
if (entity is Directory) { switch (entity) {
if (name == 'build' || name.startsWith('.')) { case Directory() when name != 'build' && !name.startsWith('.'):
continue;
}
_copy(entity, Directory(path.join(target.path, name))); _copy(entity, Directory(path.join(target.path, name)));
} else if (entity is File) {
if (name == '.packages' || name == 'pubspec.lock') { case File() when name != '.packages' && name != 'pubspec.lock':
continue;
}
final File dest = File(path.join(target.path, name)); final File dest = File(path.join(target.path, name));
dest.writeAsBytesSync(entity.readAsBytesSync()); dest.writeAsBytesSync(entity.readAsBytesSync());
} }

View File

@ -113,9 +113,7 @@ abstract class BoxBorder extends ShapeBorder {
return BorderDirectional.lerp(a, b, t); return BorderDirectional.lerp(a, b, t);
} }
if (b is Border && a is BorderDirectional) { if (b is Border && a is BorderDirectional) {
final BoxBorder c = b; (a, b) = (b, a);
b = a;
a = c;
t = 1.0 - t; t = 1.0 - t;
// fall through to next case // fall through to next case
} }

View File

@ -1452,25 +1452,21 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin,
..sortKey = OrdinalSortKey(ordinal++) ..sortKey = OrdinalSortKey(ordinal++)
..textDirection = initialDirection ..textDirection = initialDirection
..attributedLabel = AttributedString(info.semanticsLabel ?? info.text, attributes: info.stringAttributes); ..attributedLabel = AttributedString(info.semanticsLabel ?? info.text, attributes: info.stringAttributes);
final GestureRecognizer? recognizer = info.recognizer; switch (info.recognizer) {
if (recognizer != null) { case TapGestureRecognizer(onTap: final VoidCallback? onTap):
if (recognizer is TapGestureRecognizer) { case DoubleTapGestureRecognizer(onDoubleTap: final VoidCallback? onTap):
if (recognizer.onTap != null) { if (onTap != null) {
configuration.onTap = recognizer.onTap; configuration.onTap = onTap;
configuration.isLink = true; configuration.isLink = true;
} }
} else if (recognizer is DoubleTapGestureRecognizer) { case LongPressGestureRecognizer(onLongPress: final GestureLongPressCallback? onLongPress):
if (recognizer.onDoubleTap != null) { if (onLongPress != null) {
configuration.onTap = recognizer.onDoubleTap; configuration.onLongPress = onLongPress;
configuration.isLink = true;
}
} else if (recognizer is LongPressGestureRecognizer) {
if (recognizer.onLongPress != null) {
configuration.onLongPress = recognizer.onLongPress;
}
} else {
assert(false, '${recognizer.runtimeType} is not supported.');
} }
case null:
break;
default:
assert(false, '${info.recognizer.runtimeType} is not supported.');
} }
if (node.parentPaintClipRect != null) { if (node.parentPaintClipRect != null) {
final Rect paintRect = node.parentPaintClipRect!.intersect(currentRect); final Rect paintRect = node.parentPaintClipRect!.intersect(currentRect);

View File

@ -1214,25 +1214,21 @@ class RenderParagraph extends RenderBox with ContainerRenderObjectMixin<RenderBo
..sortKey = OrdinalSortKey(ordinal++) ..sortKey = OrdinalSortKey(ordinal++)
..textDirection = initialDirection ..textDirection = initialDirection
..attributedLabel = AttributedString(info.semanticsLabel ?? info.text, attributes: info.stringAttributes); ..attributedLabel = AttributedString(info.semanticsLabel ?? info.text, attributes: info.stringAttributes);
final GestureRecognizer? recognizer = info.recognizer; switch (info.recognizer) {
if (recognizer != null) { case TapGestureRecognizer(onTap: final VoidCallback? onTap):
if (recognizer is TapGestureRecognizer) { case DoubleTapGestureRecognizer(onDoubleTap: final VoidCallback? onTap):
if (recognizer.onTap != null) { if (onTap != null) {
configuration.onTap = recognizer.onTap; configuration.onTap = onTap;
configuration.isLink = true; configuration.isLink = true;
} }
} else if (recognizer is DoubleTapGestureRecognizer) { case LongPressGestureRecognizer(onLongPress: final GestureLongPressCallback? onLongPress):
if (recognizer.onDoubleTap != null) { if (onLongPress != null) {
configuration.onTap = recognizer.onDoubleTap; configuration.onLongPress = onLongPress;
configuration.isLink = true;
}
} else if (recognizer is LongPressGestureRecognizer) {
if (recognizer.onLongPress != null) {
configuration.onLongPress = recognizer.onLongPress;
}
} else {
assert(false, '${recognizer.runtimeType} is not supported.');
} }
case null:
break;
default:
assert(false, '${info.recognizer.runtimeType} is not supported.');
} }
if (node.parentPaintClipRect != null) { if (node.parentPaintClipRect != null) {
final Rect paintRect = node.parentPaintClipRect!.intersect(currentRect); final Rect paintRect = node.parentPaintClipRect!.intersect(currentRect);

View File

@ -3799,28 +3799,18 @@ class EditableTextState extends State<EditableText> with AutomaticKeepAliveClien
&& notification is! ScrollEndNotification) { && notification is! ScrollEndNotification) {
return; return;
} }
if (notification is ScrollStartNotification switch (notification) {
&& _dataWhenToolbarShowScheduled != null) { case ScrollStartNotification() when _dataWhenToolbarShowScheduled != null:
return; case ScrollEndNotification() when _dataWhenToolbarShowScheduled == null:
} break;
if (notification is ScrollEndNotification case ScrollEndNotification() when _dataWhenToolbarShowScheduled!.value != _value:
&& _dataWhenToolbarShowScheduled == null) {
return;
}
if (notification is ScrollEndNotification
&& _dataWhenToolbarShowScheduled!.value != _value) {
_dataWhenToolbarShowScheduled = null; _dataWhenToolbarShowScheduled = null;
_disposeScrollNotificationObserver(); _disposeScrollNotificationObserver();
return; case ScrollNotification(:final BuildContext? context)
} when !_isInternalScrollableNotification(context) && _scrollableNotificationIsFromSameSubtree(context):
if (_isInternalScrollableNotification(notification.context)) {
return;
}
if (!_scrollableNotificationIsFromSameSubtree(notification.context)) {
return;
}
_handleContextMenuOnScroll(notification); _handleContextMenuOnScroll(notification);
} }
}
Rect _calculateDeviceRect() { Rect _calculateDeviceRect() {
final Size screenSize = MediaQuery.sizeOf(context); final Size screenSize = MediaQuery.sizeOf(context);

View File

@ -1591,21 +1591,14 @@ mixin WidgetInspectorService {
/// API surface of methods called from the Flutter IntelliJ Plugin. /// API surface of methods called from the Flutter IntelliJ Plugin.
@protected @protected
bool setSelection(Object? object, [ String? groupName ]) { bool setSelection(Object? object, [ String? groupName ]) {
if (object is Element || object is RenderObject) { switch (object) {
if (object is Element) { case Element() when object != selection.currentElement:
if (object == selection.currentElement) {
return false;
}
selection.currentElement = object; selection.currentElement = object;
_sendInspectEvent(selection.currentElement); _sendInspectEvent(selection.currentElement);
} else { return true;
if (object == selection.current) { case RenderObject() when object != selection.current:
return false; selection.current = object;
}
selection.current = object! as RenderObject;
_sendInspectEvent(selection.current); _sendInspectEvent(selection.current);
}
return true; return true;
} }
return false; return false;

View File

@ -64,14 +64,11 @@ void main() {
return widget is PhysicalShape || widget is PhysicalModel; return widget is PhysicalShape || widget is PhysicalModel;
}), }),
); );
final Widget widget = tester.widgetList(finder).single; switch (tester.widgetList(finder).single) {
if (widget is PhysicalShape) { case PhysicalShape(:final Color color) || PhysicalModel(:final Color color):
expect(widget.color, bottomAppBarColor); expect(color, bottomAppBarColor);
} else if (widget is PhysicalModel) { default:
expect(widget.color, bottomAppBarColor); assert(false); // Should be unreachable: compare with the finder.
} else {
// Should be unreachable: compare with the finder.
assert(false);
} }
}); });

View File

@ -264,12 +264,10 @@ BorderSide? getBorderSide(WidgetTester tester) {
} }
BorderRadius? getBorderRadius(WidgetTester tester) { BorderRadius? getBorderRadius(WidgetTester tester) {
final InputBorder border = getBorder(tester)!; switch (getBorder(tester)!) {
if (border is UnderlineInputBorder) { case UnderlineInputBorder(:final BorderRadius borderRadius):
return border.borderRadius; case OutlineInputBorder(:final BorderRadius borderRadius):
} return borderRadius;
if (border is OutlineInputBorder) {
return border.borderRadius;
} }
return null; return null;
} }

View File

@ -1015,14 +1015,11 @@ void main() {
await tester.pump(const Duration(milliseconds: 750)); await tester.pump(const Duration(milliseconds: 750));
final Element actionTextBox = tester.element(find.text('ACTION')); final Element actionTextBox = tester.element(find.text('ACTION'));
final Widget textWidget = actionTextBox.widget; expect(actionTextBox.widget, isA<Text>());
final DefaultTextStyle defaultTextStyle = DefaultTextStyle.of(actionTextBox); final Text(:TextStyle? style) = actionTextBox.widget as Text;
if (textWidget is Text) {
final TextStyle effectiveStyle = defaultTextStyle.style.merge(textWidget.style); final TextStyle defaultStyle = DefaultTextStyle.of(actionTextBox).style;
expect(effectiveStyle.color, Colors.lightBlue); expect(defaultStyle.merge(style).color, Colors.lightBlue);
} else {
expect(false, true);
}
}); });
testWidgets('Material3 - Snackbar labels can be colored as MaterialColor', (WidgetTester tester) async { testWidgets('Material3 - Snackbar labels can be colored as MaterialColor', (WidgetTester tester) async {