Arrow syntax for getters (#156483)

This egotistical PR aims to draw attention to a [style guideline](https://github.com/flutter/flutter/blob/master/docs/contributing/Style-guide-for-Flutter-repo.md#use--for-getters-and-callbacks-that-just-return-literals-or-switch-expressions) that I changed:

> #### Use `=>` for getters and callbacks that just return literals or switch expressions

<br>

There was an opportunity for valuable discussion in #154753 about how this structure affects readability, but I shut it down pretty quick since there was a lot of other stuff going on there.

Interested to hear thoughts from @Piinks and others.
This commit is contained in:
Nate Wilson 2024-10-17 13:25:14 -06:00 committed by GitHub
parent fdbd855fdc
commit 6b1bc456f4
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
36 changed files with 239 additions and 345 deletions

View File

@ -67,18 +67,16 @@ class ResampleFlagVariant extends TestVariant<TestScenario> {
final Set<TestScenario> values = Set<TestScenario>.from(TestScenario.values); final Set<TestScenario> values = Set<TestScenario>.from(TestScenario.values);
late TestScenario currentValue; late TestScenario currentValue;
bool get resample {
return switch (currentValue) { bool get resample => switch (currentValue) {
TestScenario.resampleOn90Hz || TestScenario.resampleOn59Hz => true, TestScenario.resampleOn90Hz || TestScenario.resampleOn59Hz => true,
TestScenario.resampleOff90Hz || TestScenario.resampleOff59Hz => false, TestScenario.resampleOff90Hz || TestScenario.resampleOff59Hz => false,
}; };
}
double get frequency { double get frequency => switch (currentValue) {
return switch (currentValue) { TestScenario.resampleOn90Hz || TestScenario.resampleOff90Hz => 90.0,
TestScenario.resampleOn90Hz || TestScenario.resampleOff90Hz => 90.0, TestScenario.resampleOn59Hz || TestScenario.resampleOff59Hz => 59.0,
TestScenario.resampleOn59Hz || TestScenario.resampleOff59Hz => 59.0, };
};
}
Map<String, dynamic>? result; Map<String, dynamic>? result;

View File

@ -59,14 +59,12 @@ class _FilteredChildAnimationPageState extends State<FilteredChildAnimationPage>
setState(() => _filterType = selected ? type : null); setState(() => _filterType = selected ? type : null);
} }
String get _title { String get _title => switch (_filterType) {
return switch (_filterType) { FilterType.opacity => 'Fading Child Animation',
FilterType.opacity => 'Fading Child Animation', FilterType.rotateTransform => 'Transformed Child Animation',
FilterType.rotateTransform => 'Transformed Child Animation', FilterType.rotateFilter => 'Matrix Filtered Child Animation',
FilterType.rotateFilter => 'Matrix Filtered Child Animation', null => 'Static Child',
null => 'Static Child', };
};
}
static Widget _makeChild(int rows, int cols, double fontSize, bool complex) { static Widget _makeChild(int rows, int cols, double fontSize, bool complex) {
final BoxDecoration decoration = BoxDecoration( final BoxDecoration decoration = BoxDecoration(

View File

@ -32,12 +32,10 @@ class Remote {
final RemoteName _name; final RemoteName _name;
/// The name of the remote. /// The name of the remote.
String get name { String get name => switch (_name) {
return switch (_name) { RemoteName.upstream => 'upstream',
RemoteName.upstream => 'upstream', RemoteName.mirror => 'mirror',
RemoteName.mirror => 'mirror', };
};
}
/// The URL of the remote. /// The URL of the remote.
final String url; final String url;

View File

@ -207,12 +207,10 @@ class ABTest {
return buffer.toString(); return buffer.toString();
} }
Set<String> get _allScoreKeys { Set<String> get _allScoreKeys => <String>{
return <String>{ ..._aResults.keys,
..._aResults.keys, ..._bResults.keys,
..._bResults.keys, };
};
}
/// Returns the summary as a tab-separated spreadsheet. /// Returns the summary as a tab-separated spreadsheet.
/// ///

View File

@ -53,24 +53,20 @@ class _${blockName}DefaultsM3 extends FloatingActionButtonThemeData {
@override Color? get hoverColor => ${componentColor("md.comp.fab.primary.hover.state-layer")}; @override Color? get hoverColor => ${componentColor("md.comp.fab.primary.hover.state-layer")};
@override @override
ShapeBorder? get shape { ShapeBorder? get shape => switch (type) {
return switch (type) { _FloatingActionButtonType.regular => ${shape("md.comp.fab.primary.container")},
_FloatingActionButtonType.regular => ${shape("md.comp.fab.primary.container")}, _FloatingActionButtonType.small => ${shape("md.comp.fab.primary.small.container")},
_FloatingActionButtonType.small => ${shape("md.comp.fab.primary.small.container")}, _FloatingActionButtonType.large => ${shape("md.comp.fab.primary.large.container")},
_FloatingActionButtonType.large => ${shape("md.comp.fab.primary.large.container")}, _FloatingActionButtonType.extended => ${shape("md.comp.extended-fab.primary.container")},
_FloatingActionButtonType.extended => ${shape("md.comp.extended-fab.primary.container")}, };
};
}
@override @override
double? get iconSize { double? get iconSize => switch (type) {
return switch (type) { _FloatingActionButtonType.regular => ${getToken("md.comp.fab.primary.icon.size")},
_FloatingActionButtonType.regular => ${getToken("md.comp.fab.primary.icon.size")}, _FloatingActionButtonType.small => ${getToken("md.comp.fab.primary.small.icon.size")},
_FloatingActionButtonType.small => ${getToken("md.comp.fab.primary.small.icon.size")}, _FloatingActionButtonType.large => ${getToken("md.comp.fab.primary.large.icon.size")},
_FloatingActionButtonType.large => ${getToken("md.comp.fab.primary.large.icon.size")}, _FloatingActionButtonType.extended => ${getToken("md.comp.extended-fab.primary.icon.size")},
_FloatingActionButtonType.extended => ${getToken("md.comp.extended-fab.primary.icon.size")}, };
};
}
@override EdgeInsetsGeometry? get extendedPadding => EdgeInsetsDirectional.only(start: hasChild && _isExtended ? 16.0 : 20.0, end: 20.0); @override EdgeInsetsGeometry? get extendedPadding => EdgeInsetsDirectional.only(start: hasChild && _isExtended ? 16.0 : 20.0, end: 20.0);
@override TextStyle? get extendedTextStyle => ${textStyle("md.comp.extended-fab.primary.label-text")}; @override TextStyle? get extendedTextStyle => ${textStyle("md.comp.extended-fab.primary.label-text")};

View File

@ -85,21 +85,10 @@ class _DraggableScrollableSheetExampleState extends State<DraggableScrollableShe
); );
} }
bool get _isOnDesktopAndWeb { bool get _isOnDesktopAndWeb => kIsWeb || switch (defaultTargetPlatform) {
if (kIsWeb) { TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => true,
return true; TargetPlatform.android || TargetPlatform.iOS || TargetPlatform.fuchsia => false,
} };
switch (defaultTargetPlatform) {
case TargetPlatform.macOS:
case TargetPlatform.linux:
case TargetPlatform.windows:
return true;
case TargetPlatform.android:
case TargetPlatform.iOS:
case TargetPlatform.fuchsia:
return false;
}
}
} }
/// A draggable widget that accepts vertical drag gestures /// A draggable widget that accepts vertical drag gestures

View File

@ -102,21 +102,10 @@ class _PageViewExampleState extends State<PageViewExample> with TickerProviderSt
); );
} }
bool get _isOnDesktopAndWeb { bool get _isOnDesktopAndWeb => kIsWeb || switch (defaultTargetPlatform) {
if (kIsWeb) { TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => true,
return true; TargetPlatform.android || TargetPlatform.iOS || TargetPlatform.fuchsia => false,
} };
switch (defaultTargetPlatform) {
case TargetPlatform.macOS:
case TargetPlatform.linux:
case TargetPlatform.windows:
return true;
case TargetPlatform.android:
case TargetPlatform.iOS:
case TargetPlatform.fuchsia:
return false;
}
}
} }
/// Page indicator for desktop and web platforms. /// Page indicator for desktop and web platforms.

View File

@ -97,12 +97,10 @@ class RenderDiagonal extends RenderBox
// Returns children in hit test order. // Returns children in hit test order.
@override @override
Iterable<RenderBox> get children { Iterable<RenderBox> get children => <RenderBox>[
return <RenderBox>[ if (_topLeft != null) _topLeft!,
if (_topLeft != null) _topLeft!, if (_bottomRight != null) _bottomRight!,
if (_bottomRight != null) _bottomRight!, ];
];
}
// LAYOUT // LAYOUT

View File

@ -47,16 +47,14 @@ class _MyHomePageState extends State<MyHomePage> {
}); });
} }
static Widget get _buttonText { static Widget get _buttonText => switch (defaultTargetPlatform) {
return switch (defaultTargetPlatform) { TargetPlatform.android => const Text('Continue in Android view'),
TargetPlatform.android => const Text('Continue in Android view'), TargetPlatform.iOS => const Text('Continue in iOS view'),
TargetPlatform.iOS => const Text('Continue in iOS view'), TargetPlatform.windows => const Text('Continue in Windows view'),
TargetPlatform.windows => const Text('Continue in Windows view'), TargetPlatform.macOS => const Text('Continue in macOS view'),
TargetPlatform.macOS => const Text('Continue in macOS view'), TargetPlatform.linux => const Text('Continue in Linux view'),
TargetPlatform.linux => const Text('Continue in Linux view'), TargetPlatform.fuchsia => throw UnimplementedError('Platform not yet implemented'),
TargetPlatform.fuchsia => throw UnimplementedError('Platform not yet implemented'), };
};
}
Future<void> _launchPlatformCount() async { Future<void> _launchPlatformCount() async {
final int? platformCounter = final int? platformCounter =

View File

@ -2076,12 +2076,11 @@ class CupertinoTimerPicker extends StatefulWidget {
class _CupertinoTimerPickerState extends State<CupertinoTimerPicker> { class _CupertinoTimerPickerState extends State<CupertinoTimerPicker> {
late TextDirection textDirection; late TextDirection textDirection;
late CupertinoLocalizations localizations; late CupertinoLocalizations localizations;
int get textDirectionFactor {
return switch (textDirection) { int get textDirectionFactor => switch (textDirection) {
TextDirection.ltr => 1, TextDirection.ltr => 1,
TextDirection.rtl => -1, TextDirection.rtl => -1,
}; };
}
// The currently selected values of the picker. // The currently selected values of the picker.
int? selectedHour; int? selectedHour;

View File

@ -2143,13 +2143,11 @@ class FlagProperty extends DiagnosticsProperty<bool> {
} }
@override @override
DiagnosticLevel get level { DiagnosticLevel get level => switch (value) {
return switch (value) { true when ifTrue == null => DiagnosticLevel.hidden,
true when ifTrue == null => DiagnosticLevel.hidden, false when ifFalse == null => DiagnosticLevel.hidden,
false when ifFalse == null => DiagnosticLevel.hidden, _ => super.level,
_ => super.level, };
};
}
} }
/// Property with an `Iterable<T>` [value] that can be displayed with /// Property with an `Iterable<T>` [value] that can be displayed with

View File

@ -864,12 +864,10 @@ class _BottomNavigationBarState extends State<BottomNavigationBar> with TickerPr
// //
// Unselected labels are shown by default for [BottomNavigationBarType.fixed], // Unselected labels are shown by default for [BottomNavigationBarType.fixed],
// and hidden by default for [BottomNavigationBarType.shifting]. // and hidden by default for [BottomNavigationBarType.shifting].
bool get _defaultShowUnselected { bool get _defaultShowUnselected => switch (_effectiveType) {
return switch (_effectiveType) { BottomNavigationBarType.shifting => false,
BottomNavigationBarType.shifting => false, BottomNavigationBarType.fixed => true,
BottomNavigationBarType.fixed => true, };
};
}
@override @override
void initState() { void initState() {

View File

@ -254,13 +254,11 @@ class ButtonThemeData with Diagnosticable {
/// ///
/// * [getPadding], which is used to calculate padding for the button's /// * [getPadding], which is used to calculate padding for the button's
/// child (typically the button's label). /// child (typically the button's label).
EdgeInsetsGeometry get padding { EdgeInsetsGeometry get padding => _padding ?? switch (textTheme) {
return _padding ?? switch (textTheme) { ButtonTextTheme.normal => const EdgeInsets.symmetric(horizontal: 16.0),
ButtonTextTheme.normal => const EdgeInsets.symmetric(horizontal: 16.0), ButtonTextTheme.accent => const EdgeInsets.symmetric(horizontal: 16.0),
ButtonTextTheme.accent => const EdgeInsets.symmetric(horizontal: 16.0), ButtonTextTheme.primary => const EdgeInsets.symmetric(horizontal: 24.0),
ButtonTextTheme.primary => const EdgeInsets.symmetric(horizontal: 24.0), };
};
}
final EdgeInsetsGeometry? _padding; final EdgeInsetsGeometry? _padding;
/// The shape of a button's material. /// The shape of a button's material.
@ -277,14 +275,12 @@ class ButtonThemeData with Diagnosticable {
/// ///
/// * [getShape], which is used to calculate the shape of the button's /// * [getShape], which is used to calculate the shape of the button's
/// [Material]. /// [Material].
ShapeBorder get shape { ShapeBorder get shape => _shape ?? switch (textTheme) {
return _shape ?? switch (textTheme) { ButtonTextTheme.normal || ButtonTextTheme.accent =>
ButtonTextTheme.normal || ButtonTextTheme.accent => const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2.0))),
const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2.0))), ButtonTextTheme.primary =>
ButtonTextTheme.primary => const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))),
const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))), };
};
}
final ShapeBorder? _shape; final ShapeBorder? _shape;
/// If true, then a [DropdownButton] menu's width will match the button's /// If true, then a [DropdownButton] menu's width will match the button's

View File

@ -638,19 +638,15 @@ class DrawerControllerState extends State<DrawerController> with SingleTickerPro
); );
} }
AlignmentDirectional get _drawerOuterAlignment { AlignmentDirectional get _drawerOuterAlignment => switch (widget.alignment) {
return switch (widget.alignment) { DrawerAlignment.start => AlignmentDirectional.centerStart,
DrawerAlignment.start => AlignmentDirectional.centerStart, DrawerAlignment.end => AlignmentDirectional.centerEnd,
DrawerAlignment.end => AlignmentDirectional.centerEnd, };
};
}
AlignmentDirectional get _drawerInnerAlignment { AlignmentDirectional get _drawerInnerAlignment => switch (widget.alignment) {
return switch (widget.alignment) { DrawerAlignment.start => AlignmentDirectional.centerEnd,
DrawerAlignment.start => AlignmentDirectional.centerEnd, DrawerAlignment.end => AlignmentDirectional.centerStart,
DrawerAlignment.end => AlignmentDirectional.centerStart, };
};
}
Widget _buildDrawer(BuildContext context) { Widget _buildDrawer(BuildContext context) {
final bool isDesktop = switch (Theme.of(context).platform) { final bool isDesktop = switch (Theme.of(context).platform) {

View File

@ -822,24 +822,20 @@ class _FABDefaultsM3 extends FloatingActionButtonThemeData {
@override Color? get hoverColor => _colors.onPrimaryContainer.withOpacity(0.08); @override Color? get hoverColor => _colors.onPrimaryContainer.withOpacity(0.08);
@override @override
ShapeBorder? get shape { ShapeBorder? get shape => switch (type) {
return switch (type) { _FloatingActionButtonType.regular => const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))),
_FloatingActionButtonType.regular => const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))), _FloatingActionButtonType.small => const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(12.0))),
_FloatingActionButtonType.small => const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(12.0))), _FloatingActionButtonType.large => const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(28.0))),
_FloatingActionButtonType.large => const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(28.0))), _FloatingActionButtonType.extended => const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))),
_FloatingActionButtonType.extended => const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0))), };
};
}
@override @override
double? get iconSize { double? get iconSize => switch (type) {
return switch (type) { _FloatingActionButtonType.regular => 24.0,
_FloatingActionButtonType.regular => 24.0, _FloatingActionButtonType.small => 24.0,
_FloatingActionButtonType.small => 24.0, _FloatingActionButtonType.large => 36.0,
_FloatingActionButtonType.large => 36.0, _FloatingActionButtonType.extended => 24.0,
_FloatingActionButtonType.extended => 24.0, };
};
}
@override EdgeInsetsGeometry? get extendedPadding => EdgeInsetsDirectional.only(start: hasChild && _isExtended ? 16.0 : 20.0, end: 20.0); @override EdgeInsetsGeometry? get extendedPadding => EdgeInsetsDirectional.only(start: hasChild && _isExtended ? 16.0 : 20.0, end: 20.0);
@override TextStyle? get extendedTextStyle => _textTheme.labelLarge; @override TextStyle? get extendedTextStyle => _textTheme.labelLarge;

View File

@ -1092,12 +1092,10 @@ class _InkResponseState extends State<_InkResponseStateWidget>
}); });
} }
bool get _shouldShowFocus { bool get _shouldShowFocus => switch (MediaQuery.maybeNavigationModeOf(context)) {
return switch (MediaQuery.maybeNavigationModeOf(context)) { NavigationMode.traditional || null => enabled && _hasFocus,
NavigationMode.traditional || null => enabled && _hasFocus, NavigationMode.directional => _hasFocus,
NavigationMode.directional => _hasFocus, };
};
}
void updateFocusHighlights() { void updateFocusHighlights() {
final bool showFocus = switch (FocusManager.instance.highlightMode) { final bool showFocus = switch (FocusManager.instance.highlightMode) {
@ -1275,12 +1273,10 @@ class _InkResponseState extends State<_InkResponseStateWidget>
updateHighlight(_HighlightType.hover, value: _hovering); updateHighlight(_HighlightType.hover, value: _hovering);
} }
bool get _canRequestFocus { bool get _canRequestFocus => switch (MediaQuery.maybeNavigationModeOf(context)) {
return switch (MediaQuery.maybeNavigationModeOf(context)) { NavigationMode.traditional || null => enabled && widget.canRequestFocus,
NavigationMode.traditional || null => enabled && widget.canRequestFocus, NavigationMode.directional => true,
NavigationMode.directional => true, };
};
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {

View File

@ -2097,14 +2097,12 @@ class _InputDecoratorState extends State<InputDecorator> with TickerProviderStat
.merge(decoration.errorStyle); .merge(decoration.errorStyle);
} }
Set<MaterialState> get materialState { Set<MaterialState> get materialState => <MaterialState>{
return <MaterialState>{ if (!decoration.enabled) MaterialState.disabled,
if (!decoration.enabled) MaterialState.disabled, if (isFocused) MaterialState.focused,
if (isFocused) MaterialState.focused, if (isHovering) MaterialState.hovered,
if (isHovering) MaterialState.hovered, if (_hasError) MaterialState.error,
if (_hasError) MaterialState.error, };
};
}
InputBorder _getDefaultBorder(ThemeData themeData, InputDecorationTheme defaults) { InputBorder _getDefaultBorder(ThemeData themeData, InputDecorationTheme defaults) {

View File

@ -1546,12 +1546,10 @@ class _LisTileDefaultsM2 extends ListTileThemeData {
Color? get tileColor => Colors.transparent; Color? get tileColor => Colors.transparent;
@override @override
TextStyle? get titleTextStyle { TextStyle? get titleTextStyle => switch (style!) {
return switch (style!) { ListTileStyle.drawer => _textTheme.bodyLarge,
ListTileStyle.drawer => _textTheme.bodyLarge, ListTileStyle.list => _textTheme.titleMedium,
ListTileStyle.list => _textTheme.titleMedium, };
};
}
@override @override
TextStyle? get subtitleTextStyle => _textTheme.bodyMedium! TextStyle? get subtitleTextStyle => _textTheme.bodyMedium!
@ -1564,15 +1562,13 @@ class _LisTileDefaultsM2 extends ListTileThemeData {
Color? get selectedColor => _theme.colorScheme.primary; Color? get selectedColor => _theme.colorScheme.primary;
@override @override
Color? get iconColor { Color? get iconColor => switch (_theme.brightness) {
return switch (_theme.brightness) { // For the sake of backwards compatibility, the default for unselected
// For the sake of backwards compatibility, the default for unselected // tiles is Colors.black45 rather than colorScheme.onSurface.withAlpha(0x73).
// tiles is Colors.black45 rather than colorScheme.onSurface.withAlpha(0x73). Brightness.light => Colors.black45,
Brightness.light => Colors.black45, // null -> use current icon theme color
// null -> use current icon theme color Brightness.dark => null,
Brightness.dark => null, };
};
}
} }
// BEGIN GENERATED TOKEN PROPERTIES - LisTile // BEGIN GENERATED TOKEN PROPERTIES - LisTile

View File

@ -1106,14 +1106,12 @@ class _RenderRangeSlider extends RenderBox with RelayoutWhenSystemFontsChangeMix
} }
} }
bool get showValueIndicator { bool get showValueIndicator => switch (_sliderTheme.showValueIndicator!) {
return switch (_sliderTheme.showValueIndicator!) { ShowValueIndicator.onlyForDiscrete => isDiscrete,
ShowValueIndicator.onlyForDiscrete => isDiscrete, ShowValueIndicator.onlyForContinuous => !isDiscrete,
ShowValueIndicator.onlyForContinuous => !isDiscrete, ShowValueIndicator.always => true,
ShowValueIndicator.always => true, ShowValueIndicator.never => false,
ShowValueIndicator.never => false, };
};
}
Size get _thumbSize => _sliderTheme.rangeThumbShape!.getPreferredSize(isEnabled, isDiscrete); Size get _thumbSize => _sliderTheme.rangeThumbShape!.getPreferredSize(isEnabled, isDiscrete);

View File

@ -1391,14 +1391,12 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
} }
} }
bool get showValueIndicator { bool get showValueIndicator => switch (_sliderTheme.showValueIndicator!) {
return switch (_sliderTheme.showValueIndicator!) { ShowValueIndicator.onlyForDiscrete => isDiscrete,
ShowValueIndicator.onlyForDiscrete => isDiscrete, ShowValueIndicator.onlyForContinuous => !isDiscrete,
ShowValueIndicator.onlyForContinuous => !isDiscrete, ShowValueIndicator.always => true,
ShowValueIndicator.always => true, ShowValueIndicator.never => false,
ShowValueIndicator.never => false, };
};
}
double get _adjustmentUnit { double get _adjustmentUnit {
switch (_platform) { switch (_platform) {

View File

@ -1670,12 +1670,10 @@ class RenderEditable extends RenderBox with RelayoutWhenSystemFontsChangeMixin,
Axis get _viewportAxis => _isMultiline ? Axis.vertical : Axis.horizontal; Axis get _viewportAxis => _isMultiline ? Axis.vertical : Axis.horizontal;
Offset get _paintOffset { Offset get _paintOffset => switch (_viewportAxis) {
return switch (_viewportAxis) { Axis.horizontal => Offset(-offset.pixels, 0.0),
Axis.horizontal => Offset(-offset.pixels, 0.0), Axis.vertical => Offset(0.0, -offset.pixels),
Axis.vertical => Offset(0.0, -offset.pixels), };
};
}
double get _viewportExtent { double get _viewportExtent {
assert(hasSize); assert(hasSize);

View File

@ -670,14 +670,12 @@ class RenderConstrainedOverflowBox extends RenderAligningShiftedBox {
} }
@override @override
bool get sizedByParent { bool get sizedByParent => switch (fit) {
return switch (fit) { OverflowBoxFit.max => true,
OverflowBoxFit.max => true, // If deferToChild, the size will be as small as its child when non-overflowing,
// If deferToChild, the size will be as small as its child when non-overflowing, // thus it cannot be sizedByParent.
// thus it cannot be sizedByParent. OverflowBoxFit.deferToChild => false,
OverflowBoxFit.deferToChild => false, };
};
}
@override @override
@protected @protected

View File

@ -1338,12 +1338,10 @@ class _FocusableActionDetectorState extends State<FocusableActionDetector> {
} }
} }
bool get _canRequestFocus { bool get _canRequestFocus => switch (MediaQuery.maybeNavigationModeOf(context)) {
return switch (MediaQuery.maybeNavigationModeOf(context)) { NavigationMode.traditional || null => widget.enabled,
NavigationMode.traditional || null => widget.enabled, NavigationMode.directional => true,
NavigationMode.directional => true, };
};
}
// This global key is needed to keep only the necessary widgets in the tree // This global key is needed to keep only the necessary widgets in the tree
// while maintaining the subtree's state. // while maintaining the subtree's state.

View File

@ -787,12 +787,10 @@ class BouncingScrollPhysics extends ScrollPhysics {
double get dragStartDistanceMotionThreshold => 3.5; double get dragStartDistanceMotionThreshold => 3.5;
@override @override
double get maxFlingVelocity { double get maxFlingVelocity => switch (decelerationRate) {
return switch (decelerationRate) { ScrollDecelerationRate.fast => kMaxFlingVelocity * 8.0,
ScrollDecelerationRate.fast => kMaxFlingVelocity * 8.0, ScrollDecelerationRate.normal => super.maxFlingVelocity,
ScrollDecelerationRate.normal => super.maxFlingVelocity, };
};
}
@override @override
SpringDescription get spring { SpringDescription get spring {

View File

@ -570,14 +570,12 @@ class ScrollableState extends State<Scrollable> with TickerProviderStateMixin, R
/// ///
/// Used by [EdgeDraggingAutoScroller] to progress the position forward when a /// Used by [EdgeDraggingAutoScroller] to progress the position forward when a
/// drag gesture reaches the edge of the [Viewport]. /// drag gesture reaches the edge of the [Viewport].
Offset get deltaToScrollOrigin { Offset get deltaToScrollOrigin => switch (axisDirection) {
return switch (axisDirection) { AxisDirection.up => Offset(0, -position.pixels),
AxisDirection.up => Offset(0, -position.pixels), AxisDirection.down => Offset(0, position.pixels),
AxisDirection.down => Offset(0, position.pixels), AxisDirection.left => Offset(-position.pixels, 0),
AxisDirection.left => Offset(-position.pixels, 0), AxisDirection.right => Offset(position.pixels, 0),
AxisDirection.right => Offset(position.pixels, 0), };
};
}
ScrollController get _effectiveScrollController => widget.controller ?? _fallbackScrollController!; ScrollController get _effectiveScrollController => widget.controller ?? _fallbackScrollController!;

View File

@ -395,12 +395,11 @@ class ScrollbarPainter extends ChangeNotifier implements CustomPainter {
// Track Offsets // Track Offsets
// The track is offset by only padding. // The track is offset by only padding.
double get _totalTrackMainAxisOffsets => _isVertical ? padding.vertical : padding.horizontal; double get _totalTrackMainAxisOffsets => _isVertical ? padding.vertical : padding.horizontal;
double get _leadingTrackMainAxisOffset {
return switch (_resolvedOrientation) { double get _leadingTrackMainAxisOffset => switch (_resolvedOrientation) {
ScrollbarOrientation.left || ScrollbarOrientation.right => padding.top, ScrollbarOrientation.left || ScrollbarOrientation.right => padding.top,
ScrollbarOrientation.top || ScrollbarOrientation.bottom => padding.left, ScrollbarOrientation.top || ScrollbarOrientation.bottom => padding.left,
}; };
}
Rect? _thumbRect; Rect? _thumbRect;
// The current scroll position + _leadingThumbMainAxisOffset // The current scroll position + _leadingThumbMainAxisOffset

View File

@ -545,9 +545,7 @@ class SingleActivator with Diagnosticable, MenuSerializableShortcut implements S
final bool includeRepeats; final bool includeRepeats;
@override @override
Iterable<LogicalKeyboardKey> get triggers { Iterable<LogicalKeyboardKey> get triggers => <LogicalKeyboardKey>[trigger];
return <LogicalKeyboardKey>[trigger];
}
bool _shouldAcceptModifiers(Set<LogicalKeyboardKey> pressed) { bool _shouldAcceptModifiers(Set<LogicalKeyboardKey> pressed) {
return control == pressed.intersection(_controlSynonyms).isNotEmpty return control == pressed.intersection(_controlSynonyms).isNotEmpty

View File

@ -136,13 +136,11 @@ class _RenderSliverResizingHeader extends RenderSliver with SlottedContainerRend
RenderBox? get child => childForSlot(_Slot.child); RenderBox? get child => childForSlot(_Slot.child);
@override @override
Iterable<RenderBox> get children { Iterable<RenderBox> get children => <RenderBox>[
return <RenderBox>[ if (minExtentPrototype != null) minExtentPrototype!,
if (minExtentPrototype != null) minExtentPrototype!, if (maxExtentPrototype != null) maxExtentPrototype!,
if (maxExtentPrototype != null) maxExtentPrototype!, if (child != null) child!,
if (child != null) child!, ];
];
}
double boxExtent(RenderBox box) { double boxExtent(RenderBox box) {
assert(box.hasSize); assert(box.hasSize);

View File

@ -123,14 +123,12 @@ class Java {
/// ///
/// This map should be used as the environment when invoking any Java-dependent /// This map should be used as the environment when invoking any Java-dependent
/// processes, such as Gradle or Android SDK tools (avdmanager, sdkmanager, etc.) /// processes, such as Gradle or Android SDK tools (avdmanager, sdkmanager, etc.)
Map<String, String> get environment { Map<String, String> get environment => <String, String>{
return <String, String>{ if (javaHome != null) javaHomeEnvironmentVariable: javaHome!,
if (javaHome != null) javaHomeEnvironmentVariable: javaHome!, 'PATH': _fileSystem.path.dirname(binaryPath) +
'PATH': _fileSystem.path.dirname(binaryPath) + _os.pathVarSeparator +
_os.pathVarSeparator + _platform.environment['PATH']!,
_platform.environment['PATH']!, };
};
}
/// Returns the version of java in the format \d(.\d)+(.\d)+ /// Returns the version of java in the format \d(.\d)+(.\d)+
/// Returns null if version could not be determined. /// Returns null if version could not be determined.

View File

@ -633,16 +633,14 @@ enum HostPlatform {
windows_x64, windows_x64,
windows_arm64; windows_arm64;
String get platformName { String get platformName => switch (this) {
return switch (this) { HostPlatform.darwin_x64 => 'x64',
HostPlatform.darwin_x64 => 'x64', HostPlatform.darwin_arm64 => 'arm64',
HostPlatform.darwin_arm64 => 'arm64', HostPlatform.linux_x64 => 'x64',
HostPlatform.linux_x64 => 'x64', HostPlatform.linux_arm64 => 'arm64',
HostPlatform.linux_arm64 => 'arm64', HostPlatform.windows_x64 => 'x64',
HostPlatform.windows_x64 => 'x64', HostPlatform.windows_arm64 => 'arm64',
HostPlatform.windows_arm64 => 'arm64', };
};
}
} }
String getNameForHostPlatform(HostPlatform platform) { String getNameForHostPlatform(HostPlatform platform) {

View File

@ -649,23 +649,19 @@ enum AndroidArch {
x86, x86,
x86_64; x86_64;
String get archName { String get archName => switch (this) {
return switch (this) { AndroidArch.armeabi_v7a => 'armeabi-v7a',
AndroidArch.armeabi_v7a => 'armeabi-v7a', AndroidArch.arm64_v8a => 'arm64-v8a',
AndroidArch.arm64_v8a => 'arm64-v8a', AndroidArch.x86_64 => 'x86_64',
AndroidArch.x86_64 => 'x86_64', AndroidArch.x86 => 'x86',
AndroidArch.x86 => 'x86' };
};
}
String get platformName { String get platformName => switch (this) {
return switch (this) { AndroidArch.armeabi_v7a => 'android-arm',
AndroidArch.armeabi_v7a => 'android-arm', AndroidArch.arm64_v8a => 'android-arm64',
AndroidArch.arm64_v8a => 'android-arm64', AndroidArch.x86_64 => 'android-x64',
AndroidArch.x86_64 => 'android-x64', AndroidArch.x86 => 'android-x86',
AndroidArch.x86 => 'android-x86' };
};
}
} }
/// The default set of iOS device architectures to build for. /// The default set of iOS device architectures to build for.

View File

@ -240,13 +240,11 @@ class AnalysisError implements Comparable<AnalysisError> {
String get _separator => _platform.isWindows ? '-' : ''; String get _separator => _platform.isWindows ? '-' : '';
String get colorSeverity { String get colorSeverity => switch (writtenError.severityLevel) {
return switch (writtenError.severityLevel) { AnalysisSeverity.error => _terminal.color(writtenError.severity, TerminalColor.red),
AnalysisSeverity.error => _terminal.color(writtenError.severity, TerminalColor.red), AnalysisSeverity.warning => _terminal.color(writtenError.severity, TerminalColor.yellow),
AnalysisSeverity.warning => _terminal.color(writtenError.severity, TerminalColor.yellow), AnalysisSeverity.info || AnalysisSeverity.none => writtenError.severity,
AnalysisSeverity.info || AnalysisSeverity.none => writtenError.severity, };
};
}
String get type => writtenError.type; String get type => writtenError.type;
String get code => writtenError.code; String get code => writtenError.code;

View File

@ -161,14 +161,12 @@ class ValidationResult {
final String? statusInfo; final String? statusInfo;
final List<ValidationMessage> messages; final List<ValidationMessage> messages;
String get leadingBox { String get leadingBox => switch (type) {
return switch (type) { ValidationType.crash => '[☠]',
ValidationType.crash => '[☠]', ValidationType.missing => '[✗]',
ValidationType.missing => '[✗]', ValidationType.success => '[✓]',
ValidationType.success => '[✓]', ValidationType.notAvailable || ValidationType.partial => '[!]',
ValidationType.notAvailable || ValidationType.partial => '[!]', };
};
}
String get coloredLeadingBox { String get coloredLeadingBox {
return globals.terminal.color(leadingBox, switch (type) { return globals.terminal.color(leadingBox, switch (type) {
@ -179,15 +177,13 @@ class ValidationResult {
} }
/// The string representation of the type. /// The string representation of the type.
String get typeStr { String get typeStr => switch (type) {
return switch (type) { ValidationType.crash => 'crash',
ValidationType.crash => 'crash', ValidationType.missing => 'missing',
ValidationType.missing => 'missing', ValidationType.success => 'installed',
ValidationType.success => 'installed', ValidationType.notAvailable => 'notAvailable',
ValidationType.notAvailable => 'notAvailable', ValidationType.partial => 'partial',
ValidationType.partial => 'partial', };
};
}
@override @override
String toString() { String toString() {
@ -237,13 +233,11 @@ class ValidationMessage {
bool get isInformation => type == ValidationMessageType.information; bool get isInformation => type == ValidationMessageType.information;
String get indicator { String get indicator => switch (type) {
return switch (type) { ValidationMessageType.error => '',
ValidationMessageType.error => '', ValidationMessageType.hint => '!',
ValidationMessageType.hint => '!', ValidationMessageType.information => '',
ValidationMessageType.information => '', };
};
}
String get coloredIndicator { String get coloredIndicator {
return globals.terminal.color(indicator, switch (type) { return globals.terminal.color(indicator, switch (type) {

View File

@ -801,11 +801,9 @@ class IosUsbArtifacts extends CachedArtifact {
}; };
@override @override
Map<String, String> get environment { Map<String, String> get environment => <String, String>{
return <String, String>{ 'DYLD_LIBRARY_PATH': cache.getArtifactDirectory(name).path,
'DYLD_LIBRARY_PATH': cache.getArtifactDirectory(name).path, };
};
}
@override @override
bool isUpToDateInner(FileSystem fileSystem) { bool isUpToDateInner(FileSystem fileSystem) {

View File

@ -91,17 +91,15 @@ class SwiftPackage {
final TemplateRenderer _templateRenderer; final TemplateRenderer _templateRenderer;
/// Context for the [_swiftPackageTemplate] template. /// Context for the [_swiftPackageTemplate] template.
Map<String, Object> get _templateContext { Map<String, Object> get _templateContext => <String, Object>{
return <String, Object>{ 'swiftToolsVersion': minimumSwiftToolchainVersion,
'swiftToolsVersion': minimumSwiftToolchainVersion, 'packageName': _name,
'packageName': _name, // Supported platforms can't be empty, so only include if not null.
// Supported platforms can't be empty, so only include if not null. 'platforms': _formatPlatforms() ?? false,
'platforms': _formatPlatforms() ?? false, 'products': _formatProducts(),
'products': _formatProducts(), 'dependencies': _formatDependencies(),
'dependencies': _formatDependencies(), 'targets': _formatTargets(),
'targets': _formatTargets(), };
};
}
/// Create a Package.swift using settings from [_templateContext]. /// Create a Package.swift using settings from [_templateContext].
void createSwiftPackage() { void createSwiftPackage() {

View File

@ -1247,13 +1247,11 @@ class FakeAsyncCrashingDoctor extends Doctor {
/// overriding the doctor. /// overriding the doctor.
class FakeDoctorValidatorsProvider implements DoctorValidatorsProvider { class FakeDoctorValidatorsProvider implements DoctorValidatorsProvider {
@override @override
List<DoctorValidator> get validators { List<DoctorValidator> get validators => <DoctorValidator>[
return <DoctorValidator>[ PassingValidator('Passing Validator'),
PassingValidator('Passing Validator'), PassingValidator('Another Passing Validator'),
PassingValidator('Another Passing Validator'), PassingValidator('Providing validators is fun'),
PassingValidator('Providing validators is fun'), ];
];
}
@override @override
List<Workflow> get workflows => <Workflow>[]; List<Workflow> get workflows => <Workflow>[];