Unverified Commit 7a4c2465 authored by Nate's avatar Nate Committed by GitHub

Implementing `switch` expressions: everything in `flutter/lib/src/` (#143634)

This PR is the 9ᵗʰ step in the journey to solve issue #136139 and make the entire Flutter repo more readable.

(previous pull requests: #139048, #139882, #141591, #142279, #142634, #142793, #143293, #143496)

I did a pass through all of `packages/flutter/lib/src/` and found an abundance of `switch` statements to improve. Whereas #143496 focused on in-depth refactoring, this PR is full of simple, straightforward changes. (I ended up making some more complicated changes in `rendering/` and will file those separately after this PR is done.)
parent 3538e4c7
...@@ -598,20 +598,15 @@ class AnimationController extends Animation<double> ...@@ -598,20 +598,15 @@ class AnimationController extends Animation<double>
} }
TickerFuture _animateToInternal(double target, { Duration? duration, Curve curve = Curves.linear }) { TickerFuture _animateToInternal(double target, { Duration? duration, Curve curve = Curves.linear }) {
double scale = 1.0; final double scale = switch (animationBehavior) {
if (SemanticsBinding.instance.disableAnimations) { // Since the framework cannot handle zero duration animations, we run it at 5% of the normal
switch (animationBehavior) { // duration to limit most animations to a single frame.
case AnimationBehavior.normal: // Ideally, the framework would be able to handle zero duration animations, however, the common
// Since the framework cannot handle zero duration animations, we run it at 5% of the normal // pattern of an eternally repeating animation might cause an endless loop if it weren't delayed
// duration to limit most animations to a single frame. // for at least one frame.
// Ideally, the framework would be able to handle zero duration animations, however, the common AnimationBehavior.normal when SemanticsBinding.instance.disableAnimations => 0.05,
// pattern of an eternally repeating animation might cause an endless loop if it weren't delayed AnimationBehavior.normal || AnimationBehavior.preserve => 1.0,
// for at least one frame. };
scale = 0.05;
case AnimationBehavior.preserve:
break;
}
}
Duration? simulationDuration = duration; Duration? simulationDuration = duration;
if (simulationDuration == null) { if (simulationDuration == null) {
assert(!(this.duration == null && _direction == _AnimationDirection.forward)); assert(!(this.duration == null && _direction == _AnimationDirection.forward));
...@@ -721,16 +716,12 @@ class AnimationController extends Animation<double> ...@@ -721,16 +716,12 @@ class AnimationController extends Animation<double>
_direction = velocity < 0.0 ? _AnimationDirection.reverse : _AnimationDirection.forward; _direction = velocity < 0.0 ? _AnimationDirection.reverse : _AnimationDirection.forward;
final double target = velocity < 0.0 ? lowerBound - _kFlingTolerance.distance final double target = velocity < 0.0 ? lowerBound - _kFlingTolerance.distance
: upperBound + _kFlingTolerance.distance; : upperBound + _kFlingTolerance.distance;
double scale = 1.0;
final AnimationBehavior behavior = animationBehavior ?? this.animationBehavior; final AnimationBehavior behavior = animationBehavior ?? this.animationBehavior;
if (SemanticsBinding.instance.disableAnimations) { final double scale = switch (behavior) {
switch (behavior) { // This is arbitrary (it was chosen because it worked for the drawer widget).
case AnimationBehavior.normal: AnimationBehavior.normal when SemanticsBinding.instance.disableAnimations => 200.0,
scale = 200.0; // This is arbitrary (it was chosen because it worked for the drawer widget). AnimationBehavior.normal || AnimationBehavior.preserve => 1.0,
case AnimationBehavior.preserve: };
break;
}
}
final SpringSimulation simulation = SpringSimulation(springDescription, value, target, velocity * scale) final SpringSimulation simulation = SpringSimulation(springDescription, value, target, velocity * scale)
..tolerance = _kFlingTolerance; ..tolerance = _kFlingTolerance;
assert( assert(
......
...@@ -425,15 +425,10 @@ class CurvedAnimation extends Animation<double> with AnimationWithParentMixin<do ...@@ -425,15 +425,10 @@ class CurvedAnimation extends Animation<double> with AnimationWithParentMixin<do
bool isDisposed = false; bool isDisposed = false;
void _updateCurveDirection(AnimationStatus status) { void _updateCurveDirection(AnimationStatus status) {
switch (status) { _curveDirection = switch (status) {
case AnimationStatus.dismissed: AnimationStatus.dismissed || AnimationStatus.completed => null,
case AnimationStatus.completed: AnimationStatus.forward || AnimationStatus.reverse => _curveDirection ?? status,
_curveDirection = null; };
case AnimationStatus.forward:
_curveDirection ??= AnimationStatus.forward;
case AnimationStatus.reverse:
_curveDirection ??= AnimationStatus.reverse;
}
} }
bool get _useForwardCurve { bool get _useForwardCurve {
...@@ -584,12 +579,10 @@ class TrainHoppingAnimation extends Animation<double> ...@@ -584,12 +579,10 @@ class TrainHoppingAnimation extends Animation<double>
bool hop = false; bool hop = false;
if (_nextTrain != null) { if (_nextTrain != null) {
assert(_mode != null); assert(_mode != null);
switch (_mode!) { hop = switch (_mode!) {
case _TrainHoppingMode.minimize: _TrainHoppingMode.minimize => _nextTrain!.value <= _currentTrain!.value,
hop = _nextTrain!.value <= _currentTrain!.value; _TrainHoppingMode.maximize => _nextTrain!.value >= _currentTrain!.value,
case _TrainHoppingMode.maximize: };
hop = _nextTrain!.value >= _currentTrain!.value;
}
if (hop) { if (hop) {
_currentTrain! _currentTrain!
..removeStatusListener(_statusChangeHandler) ..removeStatusListener(_statusChangeHandler)
......
...@@ -414,20 +414,18 @@ class CupertinoDatePicker extends StatefulWidget { ...@@ -414,20 +414,18 @@ class CupertinoDatePicker extends StatefulWidget {
final double itemExtent; final double itemExtent;
@override @override
State<StatefulWidget> createState() { // ignore: no_logic_in_create_state, https://github.com/flutter/flutter/issues/70499 State<StatefulWidget> createState() {
// The `time` mode and `dateAndTime` mode of the picker share the time // ignore: no_logic_in_create_state, https://github.com/flutter/flutter/issues/70499
// columns, so they are placed together to one state. return switch (mode) {
// The `date` mode has different children and is implemented in a different // The `time` mode and `dateAndTime` mode of the picker share the time
// state. // columns, so they are placed together to one state.
switch (mode) { // The `date` mode has different children and is implemented in a different
case CupertinoDatePickerMode.time: // state.
case CupertinoDatePickerMode.dateAndTime: CupertinoDatePickerMode.time => _CupertinoDatePickerDateTimeState(),
return _CupertinoDatePickerDateTimeState(); CupertinoDatePickerMode.dateAndTime => _CupertinoDatePickerDateTimeState(),
case CupertinoDatePickerMode.date: CupertinoDatePickerMode.date => _CupertinoDatePickerDateState(dateOrder: dateOrder),
return _CupertinoDatePickerDateState(dateOrder: dateOrder); CupertinoDatePickerMode.monthYear => _CupertinoDatePickerMonthYearState(dateOrder: dateOrder),
case CupertinoDatePickerMode.monthYear: };
return _CupertinoDatePickerMonthYearState(dateOrder: dateOrder);
}
} }
// Estimate the minimum width that each column needs to layout its content. // Estimate the minimum width that each column needs to layout its content.
......
...@@ -287,15 +287,12 @@ class _CupertinoListTileState extends State<CupertinoListTile> { ...@@ -287,15 +287,12 @@ class _CupertinoListTileState extends State<CupertinoListTile> {
child: widget.title, child: widget.title,
); );
EdgeInsetsGeometry? padding = widget.padding; final EdgeInsetsGeometry padding = widget.padding ?? switch (widget._type) {
if (padding == null) { _CupertinoListTileType.base when widget.subtitle != null => _kPaddingWithSubtitle,
switch (widget._type) { _CupertinoListTileType.notched when widget.leading != null => _kNotchedPadding,
case _CupertinoListTileType.base: _CupertinoListTileType.base => _kPadding,
padding = widget.subtitle == null ? _kPadding : _kPaddingWithSubtitle; _CupertinoListTileType.notched => _kNotchedPaddingWithoutLeading,
case _CupertinoListTileType.notched: };
padding = widget.leading == null ? _kNotchedPaddingWithoutLeading : _kNotchedPadding;
}
}
Widget? subtitle; Widget? subtitle;
if (widget.subtitle != null) { if (widget.subtitle != null) {
...@@ -325,13 +322,12 @@ class _CupertinoListTileState extends State<CupertinoListTile> { ...@@ -325,13 +322,12 @@ class _CupertinoListTileState extends State<CupertinoListTile> {
backgroundColor = widget.backgroundColorActivated ?? CupertinoColors.systemGrey4.resolveFrom(context); backgroundColor = widget.backgroundColorActivated ?? CupertinoColors.systemGrey4.resolveFrom(context);
} }
double minHeight; final double minHeight = switch (widget._type) {
switch (widget._type) { _CupertinoListTileType.base when subtitle != null => _kMinHeightWithSubtitle,
case _CupertinoListTileType.base: _CupertinoListTileType.notched when widget.leading != null => _kNotchedMinHeight,
minHeight = subtitle == null ? _kMinHeight : _kMinHeightWithSubtitle; _CupertinoListTileType.base => _kMinHeight,
case _CupertinoListTileType.notched: _CupertinoListTileType.notched => _kNotchedMinHeightWithoutLeading,
minHeight = widget.leading == null ? _kNotchedMinHeightWithoutLeading : _kNotchedMinHeight; };
}
final Widget child = Container( final Widget child = Container(
constraints: BoxConstraints(minWidth: double.infinity, minHeight: minHeight), constraints: BoxConstraints(minWidth: double.infinity, minHeight: minHeight),
......
...@@ -975,16 +975,10 @@ class _CupertinoEdgeShadowPainter extends BoxPainter { ...@@ -975,16 +975,10 @@ class _CupertinoEdgeShadowPainter extends BoxPainter {
final TextDirection? textDirection = configuration.textDirection; final TextDirection? textDirection = configuration.textDirection;
assert(textDirection != null); assert(textDirection != null);
final double start; final (double shadowDirection, double start) = switch (textDirection!) {
final double shadowDirection; // -1 for ltr, 1 for rtl. TextDirection.rtl => (1, offset.dx + configuration.size!.width),
switch (textDirection!) { TextDirection.ltr => (-1, offset.dx),
case TextDirection.rtl: };
start = offset.dx + configuration.size!.width;
shadowDirection = 1;
case TextDirection.ltr:
start = offset.dx;
shadowDirection = -1;
}
int bandColorIndex = 0; int bandColorIndex = 0;
for (int dx = 0; dx < shadowWidth; dx += 1) { for (int dx = 0; dx < shadowWidth; dx += 1) {
......
...@@ -174,12 +174,10 @@ class _CupertinoScrollbarState extends RawScrollbarState<CupertinoScrollbar> { ...@@ -174,12 +174,10 @@ class _CupertinoScrollbarState extends RawScrollbarState<CupertinoScrollbar> {
if (direction == null) { if (direction == null) {
return; return;
} }
switch (direction) { _pressStartAxisPosition = switch (direction) {
case Axis.vertical: Axis.vertical => localPosition.dy,
_pressStartAxisPosition = localPosition.dy; Axis.horizontal => localPosition.dx,
case Axis.horizontal: };
_pressStartAxisPosition = localPosition.dx;
}
} }
@override @override
......
...@@ -503,19 +503,10 @@ class _RenderCupertinoSlider extends RenderConstrainedBox implements MouseTracke ...@@ -503,19 +503,10 @@ class _RenderCupertinoSlider extends RenderConstrainedBox implements MouseTracke
@override @override
void paint(PaintingContext context, Offset offset) { void paint(PaintingContext context, Offset offset) {
final double visualPosition; final (double visualPosition, Color leftColor, Color rightColor) = switch (textDirection) {
final Color leftColor; TextDirection.rtl => (1.0 - _position.value, _activeColor, trackColor),
final Color rightColor; TextDirection.ltr => (_position.value, trackColor, _activeColor),
switch (textDirection) { };
case TextDirection.rtl:
visualPosition = 1.0 - _position.value;
leftColor = _activeColor;
rightColor = trackColor;
case TextDirection.ltr:
visualPosition = _position.value;
leftColor = trackColor;
rightColor = _activeColor;
}
final double trackCenter = offset.dy + size.height / 2.0; final double trackCenter = offset.dy + size.height / 2.0;
final double trackLeft = offset.dx + _trackLeft; final double trackLeft = offset.dx + _trackLeft;
......
...@@ -429,12 +429,10 @@ class _RenderButtonBarRow extends RenderFlex { ...@@ -429,12 +429,10 @@ class _RenderButtonBarRow extends RenderFlex {
} }
} }
currentHeight += child.size.height; currentHeight += child.size.height;
switch (verticalDirection) { child = switch (verticalDirection) {
case VerticalDirection.down: VerticalDirection.down => childParentData.nextSibling,
child = childParentData.nextSibling; VerticalDirection.up => childParentData.previousSibling,
case VerticalDirection.up: };
child = childParentData.previousSibling;
}
if (overflowButtonSpacing != null && child != null) { if (overflowButtonSpacing != null && child != null) {
currentHeight += overflowButtonSpacing!; currentHeight += overflowButtonSpacing!;
......
...@@ -617,21 +617,11 @@ class ButtonThemeData with Diagnosticable { ...@@ -617,21 +617,11 @@ class ButtonThemeData with Diagnosticable {
/// [getTextTheme] is [ButtonTextTheme.primary], 16.0 on the left and right /// [getTextTheme] is [ButtonTextTheme.primary], 16.0 on the left and right
/// otherwise. /// otherwise.
EdgeInsetsGeometry getPadding(MaterialButton button) { EdgeInsetsGeometry getPadding(MaterialButton button) {
if (button.padding != null) { return button.padding ?? _padding ?? switch (getTextTheme(button)) {
return button.padding!; ButtonTextTheme.normal => const EdgeInsets.symmetric(horizontal: 16.0),
} ButtonTextTheme.accent => const EdgeInsets.symmetric(horizontal: 16.0),
ButtonTextTheme.primary => const EdgeInsets.symmetric(horizontal: 24.0),
if (_padding != null) { };
return _padding;
}
switch (getTextTheme(button)) {
case ButtonTextTheme.normal:
case ButtonTextTheme.accent:
return const EdgeInsets.symmetric(horizontal: 16.0);
case ButtonTextTheme.primary:
return const EdgeInsets.symmetric(horizontal: 24.0);
}
} }
/// The shape of the [button]'s [Material]. /// The shape of the [button]'s [Material].
......
...@@ -213,14 +213,11 @@ class Card extends StatelessWidget { ...@@ -213,14 +213,11 @@ class Card extends StatelessWidget {
final CardTheme cardTheme = CardTheme.of(context); final CardTheme cardTheme = CardTheme.of(context);
final CardTheme defaults; final CardTheme defaults;
if (Theme.of(context).useMaterial3) { if (Theme.of(context).useMaterial3) {
switch (_variant) { defaults = switch (_variant) {
case _CardVariant.elevated: _CardVariant.elevated => _CardDefaultsM3(context),
defaults = _CardDefaultsM3(context); _CardVariant.filled => _FilledCardDefaultsM3(context),
case _CardVariant.filled: _CardVariant.outlined => _OutlinedCardDefaultsM3(context),
defaults = _FilledCardDefaultsM3(context); };
case _CardVariant.outlined:
defaults = _OutlinedCardDefaultsM3(context);
}
} else { } else {
defaults = _CardDefaultsM2(context); defaults = _CardDefaultsM2(context);
} }
......
...@@ -518,16 +518,10 @@ class CheckboxListTile extends StatelessWidget { ...@@ -518,16 +518,10 @@ class CheckboxListTile extends StatelessWidget {
); );
} }
Widget? leading, trailing; final (Widget? leading, Widget? trailing) = switch (controlAffinity) {
switch (controlAffinity) { ListTileControlAffinity.leading => (control, secondary),
case ListTileControlAffinity.leading: ListTileControlAffinity.trailing || ListTileControlAffinity.platform => (secondary, control),
leading = control; };
trailing = secondary;
case ListTileControlAffinity.trailing:
case ListTileControlAffinity.platform:
leading = secondary;
trailing = control;
}
final ThemeData theme = Theme.of(context); final ThemeData theme = Theme.of(context);
final CheckboxThemeData checkboxTheme = CheckboxTheme.of(context); final CheckboxThemeData checkboxTheme = CheckboxTheme.of(context);
final Set<MaterialState> states = <MaterialState>{ final Set<MaterialState> states = <MaterialState>{
......
...@@ -646,35 +646,24 @@ class DrawerControllerState extends State<DrawerController> with SingleTickerPro ...@@ -646,35 +646,24 @@ class DrawerControllerState extends State<DrawerController> with SingleTickerPro
} }
AlignmentDirectional get _drawerOuterAlignment { AlignmentDirectional get _drawerOuterAlignment {
switch (widget.alignment) { return switch (widget.alignment) {
case DrawerAlignment.start: DrawerAlignment.start => AlignmentDirectional.centerStart,
return AlignmentDirectional.centerStart; DrawerAlignment.end => AlignmentDirectional.centerEnd,
case DrawerAlignment.end: };
return AlignmentDirectional.centerEnd;
}
} }
AlignmentDirectional get _drawerInnerAlignment { AlignmentDirectional get _drawerInnerAlignment {
switch (widget.alignment) { return switch (widget.alignment) {
case DrawerAlignment.start: DrawerAlignment.start => AlignmentDirectional.centerEnd,
return AlignmentDirectional.centerEnd; DrawerAlignment.end => AlignmentDirectional.centerStart,
case DrawerAlignment.end: };
return AlignmentDirectional.centerStart;
}
} }
Widget _buildDrawer(BuildContext context) { Widget _buildDrawer(BuildContext context) {
final bool isDesktop; final bool isDesktop = switch (Theme.of(context).platform) {
switch (Theme.of(context).platform) { TargetPlatform.android || TargetPlatform.iOS || TargetPlatform.fuchsia => false,
case TargetPlatform.android: TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => true,
case TargetPlatform.iOS: };
case TargetPlatform.fuchsia:
isDesktop = false;
case TargetPlatform.macOS:
case TargetPlatform.linux:
case TargetPlatform.windows:
isDesktop = true;
}
final double dragAreaWidth = widget.edgeDragWidth final double dragAreaWidth = widget.edgeDragWidth
?? _kEdgeDragWidth + switch ((widget.alignment, Directionality.of(context))) { ?? _kEdgeDragWidth + switch ((widget.alignment, Directionality.of(context))) {
......
...@@ -484,22 +484,11 @@ class _DropdownMenuState<T> extends State<DropdownMenu<T>> { ...@@ -484,22 +484,11 @@ class _DropdownMenuState<T> extends State<DropdownMenu<T>> {
} }
bool canRequestFocus() { bool canRequestFocus() {
if (widget.focusNode != null) { return widget.focusNode?.canRequestFocus ?? widget.requestFocusOnTap
return widget.focusNode!.canRequestFocus; ?? switch (Theme.of(context).platform) {
} TargetPlatform.iOS || TargetPlatform.android || TargetPlatform.fuchsia => false,
if (widget.requestFocusOnTap != null) { TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => true,
return widget.requestFocusOnTap!; };
}
switch (Theme.of(context).platform) {
case TargetPlatform.iOS:
case TargetPlatform.android:
case TargetPlatform.fuchsia:
return false;
case TargetPlatform.macOS:
case TargetPlatform.linux:
case TargetPlatform.windows:
return true;
}
} }
void refreshLeadingPadding() { void refreshLeadingPadding() {
......
...@@ -982,19 +982,13 @@ class _InkResponseState extends State<_InkResponseStateWidget> ...@@ -982,19 +982,13 @@ class _InkResponseState extends State<_InkResponseStateWidget>
if (value) { if (value) {
if (highlight == null) { if (highlight == null) {
Color? resolvedOverlayColor = widget.overlayColor?.resolve(statesController.value); final Color resolvedOverlayColor = widget.overlayColor?.resolve(statesController.value)
if (resolvedOverlayColor == null) { ?? switch (type) {
// Use the backwards compatible defaults // Use the backwards compatible defaults
final ThemeData theme = Theme.of(context); _HighlightType.pressed => widget.highlightColor ?? Theme.of(context).highlightColor,
switch (type) { _HighlightType.focus => widget.focusColor ?? Theme.of(context).focusColor,
case _HighlightType.pressed: _HighlightType.hover => widget.hoverColor ?? Theme.of(context).hoverColor,
resolvedOverlayColor = widget.highlightColor ?? theme.highlightColor; };
case _HighlightType.focus:
resolvedOverlayColor = widget.focusColor ?? theme.focusColor;
case _HighlightType.hover:
resolvedOverlayColor = widget.hoverColor ?? theme.hoverColor;
}
}
final RenderBox referenceBox = context.findRenderObject()! as RenderBox; final RenderBox referenceBox = context.findRenderObject()! as RenderBox;
_highlights[type] = InkHighlight( _highlights[type] = InkHighlight(
controller: Material.of(context), controller: Material.of(context),
...@@ -1094,23 +1088,17 @@ class _InkResponseState extends State<_InkResponseStateWidget> ...@@ -1094,23 +1088,17 @@ class _InkResponseState extends State<_InkResponseStateWidget>
} }
bool get _shouldShowFocus { bool get _shouldShowFocus {
final NavigationMode mode = MediaQuery.maybeNavigationModeOf(context) ?? NavigationMode.traditional; return switch (MediaQuery.maybeNavigationModeOf(context)) {
switch (mode) { NavigationMode.traditional || null => enabled && _hasFocus,
case NavigationMode.traditional: NavigationMode.directional => _hasFocus,
return enabled && _hasFocus; };
case NavigationMode.directional:
return _hasFocus;
}
} }
void updateFocusHighlights() { void updateFocusHighlights() {
final bool showFocus; final bool showFocus = switch (FocusManager.instance.highlightMode) {
switch (FocusManager.instance.highlightMode) { FocusHighlightMode.touch => false,
case FocusHighlightMode.touch: FocusHighlightMode.traditional => _shouldShowFocus,
showFocus = false; };
case FocusHighlightMode.traditional:
showFocus = _shouldShowFocus;
}
updateHighlight(_HighlightType.focus, value: showFocus); updateHighlight(_HighlightType.focus, value: showFocus);
} }
...@@ -1283,13 +1271,10 @@ class _InkResponseState extends State<_InkResponseStateWidget> ...@@ -1283,13 +1271,10 @@ class _InkResponseState extends State<_InkResponseStateWidget>
} }
bool get _canRequestFocus { bool get _canRequestFocus {
final NavigationMode mode = MediaQuery.maybeNavigationModeOf(context) ?? NavigationMode.traditional; return switch (MediaQuery.maybeNavigationModeOf(context)) {
switch (mode) { NavigationMode.traditional || null => enabled && widget.canRequestFocus,
case NavigationMode.traditional: NavigationMode.directional => true,
return enabled && widget.canRequestFocus; };
case NavigationMode.directional:
return true;
}
} }
@override @override
...@@ -1303,17 +1288,14 @@ class _InkResponseState extends State<_InkResponseStateWidget> ...@@ -1303,17 +1288,14 @@ class _InkResponseState extends State<_InkResponseStateWidget>
const Set<MaterialState> hovered = <MaterialState>{MaterialState.hovered}; const Set<MaterialState> hovered = <MaterialState>{MaterialState.hovered};
final ThemeData theme = Theme.of(context); final ThemeData theme = Theme.of(context);
switch (type) { return switch (type) {
// The pressed state triggers a ripple (ink splash), per the current // The pressed state triggers a ripple (ink splash), per the current
// Material Design spec. A separate highlight is no longer used. // Material Design spec. A separate highlight is no longer used.
// See https://material.io/design/interaction/states.html#pressed // See https://material.io/design/interaction/states.html#pressed
case _HighlightType.pressed: _HighlightType.pressed => widget.overlayColor?.resolve(pressed) ?? widget.highlightColor ?? theme.highlightColor,
return widget.overlayColor?.resolve(pressed) ?? widget.highlightColor ?? theme.highlightColor; _HighlightType.focus => widget.overlayColor?.resolve(focused) ?? widget.focusColor ?? theme.focusColor,
case _HighlightType.focus: _HighlightType.hover => widget.overlayColor?.resolve(hovered) ?? widget.hoverColor ?? theme.hoverColor,
return widget.overlayColor?.resolve(focused) ?? widget.focusColor ?? theme.focusColor; };
case _HighlightType.hover:
return widget.overlayColor?.resolve(hovered) ?? widget.hoverColor ?? theme.hoverColor;
}
} }
for (final _HighlightType type in _highlights.keys) { for (final _HighlightType type in _highlights.keys) {
_highlights[type]?.color = getHighlightColorForType(type); _highlights[type]?.color = getHighlightColorForType(type);
......
...@@ -1507,14 +1507,13 @@ class _LisTileDefaultsM2 extends ListTileThemeData { ...@@ -1507,14 +1507,13 @@ class _LisTileDefaultsM2 extends ListTileThemeData {
@override @override
Color? get iconColor { Color? get iconColor {
switch (_theme.brightness) { return switch (_theme.brightness) {
case Brightness.light: // 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,
return Colors.black45; // null -> use current icon theme color
case Brightness.dark: Brightness.dark => null,
return null; // null, Use current icon theme color };
}
} }
} }
......
...@@ -3360,16 +3360,10 @@ class _MenuPanelState extends State<_MenuPanel> { ...@@ -3360,16 +3360,10 @@ class _MenuPanelState extends State<_MenuPanel> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final MenuStyle? themeStyle; final (MenuStyle? themeStyle, MenuStyle defaultStyle) = switch (widget.orientation) {
final MenuStyle defaultStyle; Axis.horizontal => (MenuBarTheme.of(context).style, _MenuBarDefaultsM3(context)),
switch (widget.orientation) { Axis.vertical => (MenuTheme.of(context).style, _MenuDefaultsM3(context)),
case Axis.horizontal: };
themeStyle = MenuBarTheme.of(context).style;
defaultStyle = _MenuBarDefaultsM3(context);
case Axis.vertical:
themeStyle = MenuTheme.of(context).style;
defaultStyle = _MenuDefaultsM3(context);
}
final MenuStyle? widgetStyle = widget.menuStyle; final MenuStyle? widgetStyle = widget.menuStyle;
T? effectiveValue<T>(T? Function(MenuStyle? style) getProperty) { T? effectiveValue<T>(T? Function(MenuStyle? style) getProperty) {
...@@ -3518,16 +3512,10 @@ class _Submenu extends StatelessWidget { ...@@ -3518,16 +3512,10 @@ class _Submenu extends StatelessWidget {
Widget build(BuildContext context) { Widget build(BuildContext context) {
// Use the text direction of the context where the button is. // Use the text direction of the context where the button is.
final TextDirection textDirection = Directionality.of(context); final TextDirection textDirection = Directionality.of(context);
final MenuStyle? themeStyle; final (MenuStyle? themeStyle, MenuStyle defaultStyle) = switch (anchor._parent?._orientation) {
final MenuStyle defaultStyle; Axis.horizontal || null => (MenuBarTheme.of(context).style, _MenuBarDefaultsM3(context)),
switch (anchor._parent?._orientation ?? Axis.horizontal) { Axis.vertical => (MenuTheme.of(context).style, _MenuDefaultsM3(context)),
case Axis.horizontal: };
themeStyle = MenuBarTheme.of(context).style;
defaultStyle = _MenuBarDefaultsM3(context);
case Axis.vertical:
themeStyle = MenuTheme.of(context).style;
defaultStyle = _MenuDefaultsM3(context);
}
T? effectiveValue<T>(T? Function(MenuStyle? style) getProperty) { T? effectiveValue<T>(T? Function(MenuStyle? style) getProperty) {
return getProperty(menuStyle) ?? getProperty(themeStyle) ?? getProperty(defaultStyle); return getProperty(menuStyle) ?? getProperty(themeStyle) ?? getProperty(defaultStyle);
} }
......
...@@ -442,20 +442,10 @@ class _SearchAnchorState extends State<SearchAnchor> { ...@@ -442,20 +442,10 @@ class _SearchAnchorState extends State<SearchAnchor> {
} }
bool getShowFullScreenView() { bool getShowFullScreenView() {
if (widget.isFullScreen != null) { return widget.isFullScreen ?? switch (Theme.of(context).platform) {
return widget.isFullScreen!; TargetPlatform.iOS || TargetPlatform.android || TargetPlatform.fuchsia => true,
} TargetPlatform.macOS || TargetPlatform.linux || TargetPlatform.windows => false,
};
switch (Theme.of(context).platform) {
case TargetPlatform.iOS:
case TargetPlatform.android:
case TargetPlatform.fuchsia:
return true;
case TargetPlatform.macOS:
case TargetPlatform.linux:
case TargetPlatform.windows:
return false;
}
} }
@override @override
......
...@@ -1629,22 +1629,16 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin { ...@@ -1629,22 +1629,16 @@ class _RenderSlider extends RenderBox with RelayoutWhenSystemFontsChangeMixin {
@override @override
void paint(PaintingContext context, Offset offset) { void paint(PaintingContext context, Offset offset) {
final double value = _state.positionController.value; final double controllerValue = _state.positionController.value;
final double? secondaryValue = _secondaryTrackValue;
// The visual position is the position of the thumb from 0 to 1 from left // The visual position is the position of the thumb from 0 to 1 from left
// to right. In left to right, this is the same as the value, but it is // to right. In left to right, this is the same as the value, but it is
// reversed for right to left text. // reversed for right to left text.
final double visualPosition; final (double visualPosition, double? secondaryVisualPosition) = switch (textDirection) {
final double? secondaryVisualPosition; TextDirection.rtl when _secondaryTrackValue == null => (1.0 - controllerValue, null),
switch (textDirection) { TextDirection.rtl => (1.0 - controllerValue, 1.0 - _secondaryTrackValue!),
case TextDirection.rtl: TextDirection.ltr => (controllerValue, _secondaryTrackValue),
visualPosition = 1.0 - value; };
secondaryVisualPosition = (secondaryValue != null) ? (1.0 - secondaryValue) : null;
case TextDirection.ltr:
visualPosition = value;
secondaryVisualPosition = (secondaryValue != null) ? secondaryValue : null;
}
final Rect trackRect = _sliderTheme.trackShape!.getPreferredRect( final Rect trackRect = _sliderTheme.trackShape!.getPreferredRect(
parentBox: this, parentBox: this,
......
...@@ -2096,18 +2096,12 @@ class RoundSliderTickMarkShape extends SliderTickMarkShape { ...@@ -2096,18 +2096,12 @@ class RoundSliderTickMarkShape extends SliderTickMarkShape {
assert(sliderTheme.inactiveTickMarkColor != null); assert(sliderTheme.inactiveTickMarkColor != null);
// The paint color of the tick mark depends on its position relative // The paint color of the tick mark depends on its position relative
// to the thumb and the text direction. // to the thumb and the text direction.
Color? begin; final double xOffset = center.dx - thumbCenter.dx;
Color? end; final (Color? begin, Color? end) = switch (textDirection) {
switch (textDirection) { TextDirection.ltr when xOffset > 0 => (sliderTheme.disabledInactiveTickMarkColor, sliderTheme.inactiveTickMarkColor),
case TextDirection.ltr: TextDirection.rtl when xOffset < 0 => (sliderTheme.disabledInactiveTickMarkColor, sliderTheme.inactiveTickMarkColor),
final bool isTickMarkRightOfThumb = center.dx > thumbCenter.dx; TextDirection.ltr || TextDirection.rtl => (sliderTheme.disabledActiveTickMarkColor, sliderTheme.activeTickMarkColor),
begin = isTickMarkRightOfThumb ? sliderTheme.disabledInactiveTickMarkColor : sliderTheme.disabledActiveTickMarkColor; };
end = isTickMarkRightOfThumb ? sliderTheme.inactiveTickMarkColor : sliderTheme.activeTickMarkColor;
case TextDirection.rtl:
final bool isTickMarkLeftOfThumb = center.dx < thumbCenter.dx;
begin = isTickMarkLeftOfThumb ? sliderTheme.disabledInactiveTickMarkColor : sliderTheme.disabledActiveTickMarkColor;
end = isTickMarkLeftOfThumb ? sliderTheme.inactiveTickMarkColor : sliderTheme.activeTickMarkColor;
}
final Paint paint = Paint()..color = ColorTween(begin: begin, end: end).evaluate(enableAnimation)!; final Paint paint = Paint()..color = ColorTween(begin: begin, end: end).evaluate(enableAnimation)!;
// The tick marks are tiny circles that are the same height as the track. // The tick marks are tiny circles that are the same height as the track.
......
...@@ -588,13 +588,10 @@ class _StepperState extends State<Stepper> with TickerProviderStateMixin { ...@@ -588,13 +588,10 @@ class _StepperState extends State<Stepper> with TickerProviderStateMixin {
); );
} }
final Color cancelColor; final Color cancelColor = switch (Theme.of(context).brightness) {
switch (Theme.of(context).brightness) { Brightness.light => Colors.black54,
case Brightness.light: Brightness.dark => Colors.white70,
cancelColor = Colors.black54; };
case Brightness.dark:
cancelColor = Colors.white70;
}
final ThemeData themeData = Theme.of(context); final ThemeData themeData = Theme.of(context);
final ColorScheme colorScheme = themeData.colorScheme; final ColorScheme colorScheme = themeData.colorScheme;
...@@ -960,12 +957,10 @@ class _StepperState extends State<Stepper> with TickerProviderStateMixin { ...@@ -960,12 +957,10 @@ class _StepperState extends State<Stepper> with TickerProviderStateMixin {
} }
return true; return true;
}()); }());
switch (widget.type) { return switch (widget.type) {
case StepperType.vertical: StepperType.vertical => _buildVertical(),
return _buildVertical(); StepperType.horizontal => _buildHorizontal(),
case StepperType.horizontal: };
return _buildHorizontal();
}
} }
} }
......
...@@ -92,20 +92,11 @@ class MaterialTextSelectionControls extends TextSelectionControls { ...@@ -92,20 +92,11 @@ class MaterialTextSelectionControls extends TextSelectionControls {
// [handle] is a circle, with a rectangle in the top left quadrant of that // [handle] is a circle, with a rectangle in the top left quadrant of that
// circle (an onion pointing to 10:30). We rotate [handle] to point // circle (an onion pointing to 10:30). We rotate [handle] to point
// straight up or up-right depending on the handle type. // straight up or up-right depending on the handle type.
switch (type) { return switch (type) {
case TextSelectionHandleType.left: // points up-right TextSelectionHandleType.left => Transform.rotate(angle: math.pi / 2.0, child: handle), // points up-right
return Transform.rotate( TextSelectionHandleType.right => handle, // points up-left
angle: math.pi / 2.0, TextSelectionHandleType.collapsed => Transform.rotate(angle: math.pi / 4.0, child: handle), // points up
child: handle, };
);
case TextSelectionHandleType.right: // points up-left
return handle;
case TextSelectionHandleType.collapsed: // points up
return Transform.rotate(
angle: math.pi / 4.0,
child: handle,
);
}
} }
/// Gets anchor for material-style text selection handles. /// Gets anchor for material-style text selection handles.
......
...@@ -2525,17 +2525,10 @@ class VisualDensity with Diagnosticable { ...@@ -2525,17 +2525,10 @@ class VisualDensity with Diagnosticable {
/// * [adaptivePlatformDensity] which returns a [VisualDensity] that is /// * [adaptivePlatformDensity] which returns a [VisualDensity] that is
/// adaptive based on [defaultTargetPlatform]. /// adaptive based on [defaultTargetPlatform].
static VisualDensity defaultDensityForPlatform(TargetPlatform platform) { static VisualDensity defaultDensityForPlatform(TargetPlatform platform) {
switch (platform) { return switch (platform) {
case TargetPlatform.android: TargetPlatform.android || TargetPlatform.iOS || TargetPlatform.fuchsia => standard,
case TargetPlatform.iOS: TargetPlatform.linux || TargetPlatform.macOS || TargetPlatform.windows => compact,
case TargetPlatform.fuchsia: };
break;
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
return compact;
}
return VisualDensity.standard;
} }
/// Copy the current [VisualDensity] with the given values replacing the /// Copy the current [VisualDensity] with the given values replacing the
......
...@@ -1136,13 +1136,10 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin { ...@@ -1136,13 +1136,10 @@ class _DialState extends State<_Dial> with SingleTickerProviderStateMixin {
double _getRadiusForTime(TimeOfDay time) { double _getRadiusForTime(TimeOfDay time) {
switch (widget.hourMinuteMode) { switch (widget.hourMinuteMode) {
case _HourMinuteMode.hour: case _HourMinuteMode.hour:
switch (widget.hourDialType) { return switch (widget.hourDialType) {
case _HourDialType.twentyFourHourDoubleRing: _HourDialType.twentyFourHourDoubleRing => time.hour >= 12 ? 0 : 1,
return time.hour >= 12 ? 0 : 1; _HourDialType.twentyFourHour || _HourDialType.twelveHour => 1,
case _HourDialType.twentyFourHour: };
case _HourDialType.twelveHour:
return 1;
}
case _HourMinuteMode.minute: case _HourMinuteMode.minute:
return 1; return 1;
} }
...@@ -2752,14 +2749,11 @@ class _TimePickerState extends State<_TimePicker> with RestorationMixin { ...@@ -2752,14 +2749,11 @@ class _TimePickerState extends State<_TimePicker> with RestorationMixin {
final _TimePickerDefaults defaultTheme = theme.useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context); final _TimePickerDefaults defaultTheme = theme.useMaterial3 ? _TimePickerDefaultsM3(context) : _TimePickerDefaultsM2(context);
final Orientation orientation = _orientation.value ?? MediaQuery.orientationOf(context); final Orientation orientation = _orientation.value ?? MediaQuery.orientationOf(context);
final HourFormat timeOfDayHour = hourFormat(of: timeOfDayFormat); final HourFormat timeOfDayHour = hourFormat(of: timeOfDayFormat);
final _HourDialType hourMode; final _HourDialType hourMode = switch (timeOfDayHour) {
switch (timeOfDayHour) { HourFormat.HH || HourFormat.H when theme.useMaterial3 => _HourDialType.twentyFourHourDoubleRing,
case HourFormat.HH: HourFormat.HH || HourFormat.H => _HourDialType.twentyFourHour,
case HourFormat.H: HourFormat.h => _HourDialType.twelveHour,
hourMode = theme.useMaterial3 ? _HourDialType.twentyFourHourDoubleRing : _HourDialType.twentyFourHour; };
case HourFormat.h:
hourMode = _HourDialType.twelveHour;
}
final String helpText; final String helpText;
final Widget picker; final Widget picker;
......
...@@ -539,12 +539,10 @@ class AlignmentDirectional extends AlignmentGeometry { ...@@ -539,12 +539,10 @@ class AlignmentDirectional extends AlignmentGeometry {
@override @override
Alignment resolve(TextDirection? direction) { Alignment resolve(TextDirection? direction) {
assert(direction != null, 'Cannot resolve $runtimeType without a TextDirection.'); assert(direction != null, 'Cannot resolve $runtimeType without a TextDirection.');
switch (direction!) { return switch (direction!) {
case TextDirection.rtl: TextDirection.rtl => Alignment(-start, y),
return Alignment(-start, y); TextDirection.ltr => Alignment(start, y),
case TextDirection.ltr: };
return Alignment(start, y);
}
} }
static String _stringify(double start, double y) { static String _stringify(double start, double y) {
...@@ -643,12 +641,10 @@ class _MixedAlignment extends AlignmentGeometry { ...@@ -643,12 +641,10 @@ class _MixedAlignment extends AlignmentGeometry {
@override @override
Alignment resolve(TextDirection? direction) { Alignment resolve(TextDirection? direction) {
assert(direction != null, 'Cannot resolve $runtimeType without a TextDirection.'); assert(direction != null, 'Cannot resolve $runtimeType without a TextDirection.');
switch (direction!) { return switch (direction!) {
case TextDirection.rtl: TextDirection.rtl => Alignment(_x - _start, _y),
return Alignment(_x - _start, _y); TextDirection.ltr => Alignment(_x + _start, _y),
case TextDirection.ltr: };
return Alignment(_x + _start, _y);
}
} }
} }
......
...@@ -140,12 +140,10 @@ enum Axis { ...@@ -140,12 +140,10 @@ enum Axis {
/// ///
/// * [flipAxisDirection], which does the same thing for [AxisDirection] values. /// * [flipAxisDirection], which does the same thing for [AxisDirection] values.
Axis flipAxis(Axis direction) { Axis flipAxis(Axis direction) {
switch (direction) { return switch (direction) {
case Axis.horizontal: Axis.horizontal => Axis.vertical,
return Axis.vertical; Axis.vertical => Axis.horizontal,
case Axis.vertical: };
return Axis.horizontal;
}
} }
/// A direction in which boxes flow vertically. /// A direction in which boxes flow vertically.
...@@ -276,14 +274,10 @@ enum AxisDirection { ...@@ -276,14 +274,10 @@ enum AxisDirection {
/// [AxisDirection.down] and returns [Axis.horizontal] for [AxisDirection.left] /// [AxisDirection.down] and returns [Axis.horizontal] for [AxisDirection.left]
/// and [AxisDirection.right]. /// and [AxisDirection.right].
Axis axisDirectionToAxis(AxisDirection axisDirection) { Axis axisDirectionToAxis(AxisDirection axisDirection) {
switch (axisDirection) { return switch (axisDirection) {
case AxisDirection.up: AxisDirection.up || AxisDirection.down => Axis.vertical,
case AxisDirection.down: AxisDirection.left || AxisDirection.right => Axis.horizontal,
return Axis.vertical; };
case AxisDirection.left:
case AxisDirection.right:
return Axis.horizontal;
}
} }
/// Returns the [AxisDirection] in which reading occurs in the given [TextDirection]. /// Returns the [AxisDirection] in which reading occurs in the given [TextDirection].
...@@ -291,12 +285,10 @@ Axis axisDirectionToAxis(AxisDirection axisDirection) { ...@@ -291,12 +285,10 @@ Axis axisDirectionToAxis(AxisDirection axisDirection) {
/// Specifically, returns [AxisDirection.left] for [TextDirection.rtl] and /// Specifically, returns [AxisDirection.left] for [TextDirection.rtl] and
/// [AxisDirection.right] for [TextDirection.ltr]. /// [AxisDirection.right] for [TextDirection.ltr].
AxisDirection textDirectionToAxisDirection(TextDirection textDirection) { AxisDirection textDirectionToAxisDirection(TextDirection textDirection) {
switch (textDirection) { return switch (textDirection) {
case TextDirection.rtl: TextDirection.rtl => AxisDirection.left,
return AxisDirection.left; TextDirection.ltr => AxisDirection.right,
case TextDirection.ltr: };
return AxisDirection.right;
}
} }
/// Returns the opposite of the given [AxisDirection]. /// Returns the opposite of the given [AxisDirection].
...@@ -309,16 +301,12 @@ AxisDirection textDirectionToAxisDirection(TextDirection textDirection) { ...@@ -309,16 +301,12 @@ AxisDirection textDirectionToAxisDirection(TextDirection textDirection) {
/// ///
/// * [flipAxis], which does the same thing for [Axis] values. /// * [flipAxis], which does the same thing for [Axis] values.
AxisDirection flipAxisDirection(AxisDirection axisDirection) { AxisDirection flipAxisDirection(AxisDirection axisDirection) {
switch (axisDirection) { return switch (axisDirection) {
case AxisDirection.up: AxisDirection.up => AxisDirection.down,
return AxisDirection.down; AxisDirection.right => AxisDirection.left,
case AxisDirection.right: AxisDirection.down => AxisDirection.up,
return AxisDirection.left; AxisDirection.left => AxisDirection.right,
case AxisDirection.down: };
return AxisDirection.up;
case AxisDirection.left:
return AxisDirection.right;
}
} }
/// Returns whether traveling along the given axis direction visits coordinates /// Returns whether traveling along the given axis direction visits coordinates
...@@ -327,12 +315,8 @@ AxisDirection flipAxisDirection(AxisDirection axisDirection) { ...@@ -327,12 +315,8 @@ AxisDirection flipAxisDirection(AxisDirection axisDirection) {
/// Specifically, returns true for [AxisDirection.up] and [AxisDirection.left] /// Specifically, returns true for [AxisDirection.up] and [AxisDirection.left]
/// and false for [AxisDirection.down] and [AxisDirection.right]. /// and false for [AxisDirection.down] and [AxisDirection.right].
bool axisDirectionIsReversed(AxisDirection axisDirection) { bool axisDirectionIsReversed(AxisDirection axisDirection) {
switch (axisDirection) { return switch (axisDirection) {
case AxisDirection.up: AxisDirection.up || AxisDirection.left => true,
case AxisDirection.left: AxisDirection.down || AxisDirection.right => false,
return true; };
case AxisDirection.down:
case AxisDirection.right:
return false;
}
} }
...@@ -275,19 +275,14 @@ class BorderSide with Diagnosticable { ...@@ -275,19 +275,14 @@ class BorderSide with Diagnosticable {
strokeAlign: a.strokeAlign, // == b.strokeAlign strokeAlign: a.strokeAlign, // == b.strokeAlign
); );
} }
final Color colorA, colorB; final Color colorA = switch (a.style) {
switch (a.style) { BorderStyle.solid => a.color,
case BorderStyle.solid: BorderStyle.none => a.color.withAlpha(0x00),
colorA = a.color; };
case BorderStyle.none: final Color colorB = switch (b.style) {
colorA = a.color.withAlpha(0x00); BorderStyle.solid => b.color,
} BorderStyle.none => b.color.withAlpha(0x00),
switch (b.style) { };
case BorderStyle.solid:
colorB = b.color;
case BorderStyle.none:
colorB = b.color.withAlpha(0x00);
}
if (a.strokeAlign != b.strokeAlign) { if (a.strokeAlign != b.strokeAlign) {
return BorderSide( return BorderSide(
color: Color.lerp(colorA, colorB, t)!, color: Color.lerp(colorA, colorB, t)!,
......
...@@ -1013,16 +1013,11 @@ class BorderDirectional extends BoxBorder { ...@@ -1013,16 +1013,11 @@ class BorderDirectional extends BoxBorder {
return; return;
} }
final BorderSide left, right;
assert(textDirection != null, 'Non-uniform BorderDirectional objects require a TextDirection when painting.'); assert(textDirection != null, 'Non-uniform BorderDirectional objects require a TextDirection when painting.');
switch (textDirection!) { final (BorderSide left, BorderSide right) = switch (textDirection!) {
case TextDirection.rtl: TextDirection.rtl => (end, start),
left = end; TextDirection.ltr => (start, end),
right = start; };
case TextDirection.ltr:
left = start;
right = end;
}
// Allow painting non-uniform borders if the visible colors are uniform. // Allow painting non-uniform borders if the visible colors are uniform.
final Set<Color> visibleColors = _distinctVisibleColors(); final Set<Color> visibleColors = _distinctVisibleColors();
......
...@@ -64,12 +64,10 @@ abstract class EdgeInsetsGeometry { ...@@ -64,12 +64,10 @@ abstract class EdgeInsetsGeometry {
/// The total offset in the given direction. /// The total offset in the given direction.
double along(Axis axis) { double along(Axis axis) {
switch (axis) { return switch (axis) {
case Axis.horizontal: Axis.horizontal => horizontal,
return horizontal; Axis.vertical => vertical,
case Axis.vertical: };
return vertical;
}
} }
/// The size that this [EdgeInsets] would occupy with an empty interior. /// The size that this [EdgeInsets] would occupy with an empty interior.
...@@ -897,12 +895,10 @@ class EdgeInsetsDirectional extends EdgeInsetsGeometry { ...@@ -897,12 +895,10 @@ class EdgeInsetsDirectional extends EdgeInsetsGeometry {
@override @override
EdgeInsets resolve(TextDirection? direction) { EdgeInsets resolve(TextDirection? direction) {
assert(direction != null); assert(direction != null);
switch (direction!) { return switch (direction!) {
case TextDirection.rtl: TextDirection.rtl => EdgeInsets.fromLTRB(end, top, start, bottom),
return EdgeInsets.fromLTRB(end, top, start, bottom); TextDirection.ltr => EdgeInsets.fromLTRB(start, top, end, bottom),
case TextDirection.ltr: };
return EdgeInsets.fromLTRB(start, top, end, bottom);
}
} }
/// Creates a copy of this EdgeInsetsDirectional but with the given /// Creates a copy of this EdgeInsetsDirectional but with the given
...@@ -1016,11 +1012,9 @@ class _MixedEdgeInsets extends EdgeInsetsGeometry { ...@@ -1016,11 +1012,9 @@ class _MixedEdgeInsets extends EdgeInsetsGeometry {
@override @override
EdgeInsets resolve(TextDirection? direction) { EdgeInsets resolve(TextDirection? direction) {
assert(direction != null); assert(direction != null);
switch (direction!) { return switch (direction!) {
case TextDirection.rtl: TextDirection.rtl => EdgeInsets.fromLTRB(_end + _left, _top, _start + _right, _bottom),
return EdgeInsets.fromLTRB(_end + _left, _top, _start + _right, _bottom); TextDirection.ltr => EdgeInsets.fromLTRB(_start + _left, _top, _end + _right, _bottom),
case TextDirection.ltr: };
return EdgeInsets.fromLTRB(_start + _left, _top, _end + _right, _bottom);
}
} }
} }
...@@ -3005,12 +3005,10 @@ class SemanticsNode with DiagnosticableTreeMixin { ...@@ -3005,12 +3005,10 @@ class SemanticsNode with DiagnosticableTreeMixin {
return const <SemanticsNode>[]; return const <SemanticsNode>[];
} }
switch (childOrder) { return switch (childOrder) {
case DebugSemanticsDumpOrder.inverseHitTest: DebugSemanticsDumpOrder.inverseHitTest => _children!,
return _children!; DebugSemanticsDumpOrder.traversalOrder => _childrenInTraversalOrder(),
case DebugSemanticsDumpOrder.traversalOrder: };
return _childrenInTraversalOrder();
}
} }
} }
...@@ -5042,12 +5040,11 @@ AttributedString _concatAttributedString({ ...@@ -5042,12 +5040,11 @@ AttributedString _concatAttributedString({
return thisAttributedString; return thisAttributedString;
} }
if (thisTextDirection != otherTextDirection && otherTextDirection != null) { if (thisTextDirection != otherTextDirection && otherTextDirection != null) {
switch (otherTextDirection) { final AttributedString directionEmbedding = switch (otherTextDirection) {
case TextDirection.rtl: TextDirection.rtl => AttributedString(Unicode.RLE),
otherAttributedString = AttributedString(Unicode.RLE) + otherAttributedString + AttributedString(Unicode.PDF); TextDirection.ltr => AttributedString(Unicode.LRE),
case TextDirection.ltr: };
otherAttributedString = AttributedString(Unicode.LRE) + otherAttributedString + AttributedString(Unicode.PDF); otherAttributedString = directionEmbedding + otherAttributedString + AttributedString(Unicode.PDF);
}
} }
if (thisAttributedString.string.isEmpty) { if (thisAttributedString.string.isEmpty) {
return otherAttributedString; return otherAttributedString;
......
...@@ -335,30 +335,14 @@ mixin ServicesBinding on BindingBase, SchedulerBinding { ...@@ -335,30 +335,14 @@ mixin ServicesBinding on BindingBase, SchedulerBinding {
// Any transition to itself shouldn't happen. // Any transition to itself shouldn't happen.
return false; return false;
} }
switch (starting) { return switch (starting) {
case AppLifecycleState.detached: // Can't go from resumed to detached directly (must go through paused).
if (ending == AppLifecycleState.resumed || ending == AppLifecycleState.paused) { AppLifecycleState.resumed => ending == AppLifecycleState.inactive,
return true; AppLifecycleState.detached => ending == AppLifecycleState.resumed || ending == AppLifecycleState.paused,
} AppLifecycleState.inactive => ending == AppLifecycleState.resumed || ending == AppLifecycleState.hidden,
case AppLifecycleState.resumed: AppLifecycleState.hidden => ending == AppLifecycleState.paused || ending == AppLifecycleState.inactive,
// Can't go from resumed to detached directly (must go through paused). AppLifecycleState.paused => ending == AppLifecycleState.hidden || ending == AppLifecycleState.detached,
if (ending == AppLifecycleState.inactive) { };
return true;
}
case AppLifecycleState.inactive:
if (ending == AppLifecycleState.resumed || ending == AppLifecycleState.hidden) {
return true;
}
case AppLifecycleState.hidden:
if (ending == AppLifecycleState.inactive || ending == AppLifecycleState.paused) {
return true;
}
case AppLifecycleState.paused:
if (ending == AppLifecycleState.hidden || ending == AppLifecycleState.detached) {
return true;
}
}
return false;
} }
...@@ -391,19 +375,14 @@ mixin ServicesBinding on BindingBase, SchedulerBinding { ...@@ -391,19 +375,14 @@ mixin ServicesBinding on BindingBase, SchedulerBinding {
} }
static AppLifecycleState? _parseAppLifecycleMessage(String message) { static AppLifecycleState? _parseAppLifecycleMessage(String message) {
switch (message) { return switch (message) {
case 'AppLifecycleState.resumed': 'AppLifecycleState.resumed' => AppLifecycleState.resumed,
return AppLifecycleState.resumed; 'AppLifecycleState.inactive' => AppLifecycleState.inactive,
case 'AppLifecycleState.inactive': 'AppLifecycleState.hidden' => AppLifecycleState.hidden,
return AppLifecycleState.inactive; 'AppLifecycleState.paused' => AppLifecycleState.paused,
case 'AppLifecycleState.hidden': 'AppLifecycleState.detached' => AppLifecycleState.detached,
return AppLifecycleState.hidden; _ => null,
case 'AppLifecycleState.paused': };
return AppLifecycleState.paused;
case 'AppLifecycleState.detached':
return AppLifecycleState.detached;
}
return null;
} }
/// Handles any requests for application exit that may be received on the /// Handles any requests for application exit that may be received on the
......
...@@ -557,14 +557,11 @@ class StandardMessageCodec implements MessageCodec<Object?> { ...@@ -557,14 +557,11 @@ class StandardMessageCodec implements MessageCodec<Object?> {
/// [readValueOfType]. /// [readValueOfType].
int readSize(ReadBuffer buffer) { int readSize(ReadBuffer buffer) {
final int value = buffer.getUint8(); final int value = buffer.getUint8();
switch (value) { return switch (value) {
case 254: 254 => buffer.getUint16(),
return buffer.getUint16(); 255 => buffer.getUint32(),
case 255: _ => value,
return buffer.getUint32(); };
default:
return value;
}
} }
} }
......
...@@ -660,40 +660,26 @@ class _AndroidMotionEventConverter { ...@@ -660,40 +660,26 @@ class _AndroidMotionEventConverter {
} }
static int sourceFor(PointerEvent event) { static int sourceFor(PointerEvent event) {
int source = AndroidViewController.kInputDeviceSourceUnknown; return switch (event.kind) {
switch (event.kind) { PointerDeviceKind.touch => AndroidViewController.kInputDeviceSourceTouchScreen,
case PointerDeviceKind.touch: PointerDeviceKind.trackpad => AndroidViewController.kInputDeviceSourceTouchPad,
source = AndroidViewController.kInputDeviceSourceTouchScreen; PointerDeviceKind.mouse => AndroidViewController.kInputDeviceSourceMouse,
case PointerDeviceKind.trackpad: PointerDeviceKind.stylus => AndroidViewController.kInputDeviceSourceStylus,
source = AndroidViewController.kInputDeviceSourceTouchPad; PointerDeviceKind.invertedStylus => AndroidViewController.kInputDeviceSourceStylus,
case PointerDeviceKind.mouse: PointerDeviceKind.unknown => AndroidViewController.kInputDeviceSourceUnknown,
source = AndroidViewController.kInputDeviceSourceMouse; };
case PointerDeviceKind.stylus:
case PointerDeviceKind.invertedStylus:
source = AndroidViewController.kInputDeviceSourceStylus;
case PointerDeviceKind.unknown:
source = AndroidViewController.kInputDeviceSourceUnknown;
}
return source;
} }
AndroidPointerProperties propertiesFor(PointerEvent event, int pointerId) { AndroidPointerProperties propertiesFor(PointerEvent event, int pointerId) {
int toolType = AndroidPointerProperties.kToolTypeUnknown; return AndroidPointerProperties(id: pointerId, toolType: switch (event.kind) {
switch (event.kind) { PointerDeviceKind.touch => AndroidPointerProperties.kToolTypeFinger,
case PointerDeviceKind.touch: PointerDeviceKind.trackpad => AndroidPointerProperties.kToolTypeFinger,
case PointerDeviceKind.trackpad: PointerDeviceKind.mouse => AndroidPointerProperties.kToolTypeMouse,
toolType = AndroidPointerProperties.kToolTypeFinger; PointerDeviceKind.stylus => AndroidPointerProperties.kToolTypeStylus,
case PointerDeviceKind.mouse: PointerDeviceKind.invertedStylus => AndroidPointerProperties.kToolTypeEraser,
toolType = AndroidPointerProperties.kToolTypeMouse; PointerDeviceKind.unknown => AndroidPointerProperties.kToolTypeUnknown,
case PointerDeviceKind.stylus: });
toolType = AndroidPointerProperties.kToolTypeStylus;
case PointerDeviceKind.invertedStylus:
toolType = AndroidPointerProperties.kToolTypeEraser;
case PointerDeviceKind.unknown:
toolType = AndroidPointerProperties.kToolTypeUnknown;
}
return AndroidPointerProperties(id: pointerId, toolType: toolType);
} }
bool isSinglePointerAction(PointerEvent event) => bool isSinglePointerAction(PointerEvent event) =>
...@@ -793,12 +779,10 @@ abstract class AndroidViewController extends PlatformViewController { ...@@ -793,12 +779,10 @@ abstract class AndroidViewController extends PlatformViewController {
<PlatformViewCreatedCallback>[]; <PlatformViewCreatedCallback>[];
static int _getAndroidDirection(TextDirection direction) { static int _getAndroidDirection(TextDirection direction) {
switch (direction) { return switch (direction) {
case TextDirection.ltr: TextDirection.ltr => kAndroidLayoutDirectionLtr,
return kAndroidLayoutDirectionLtr; TextDirection.rtl => kAndroidLayoutDirectionRtl,
case TextDirection.rtl: };
return kAndroidLayoutDirectionRtl;
}
} }
/// Creates a masked Android MotionEvent action value for an indexed pointer. /// Creates a masked Android MotionEvent action value for an indexed pointer.
......
...@@ -488,14 +488,11 @@ abstract class RawKeyEvent with Diagnosticable { ...@@ -488,14 +488,11 @@ abstract class RawKeyEvent with Diagnosticable {
} }
final bool repeat = RawKeyboard.instance.physicalKeysPressed.contains(data.physicalKey); final bool repeat = RawKeyboard.instance.physicalKeysPressed.contains(data.physicalKey);
final String type = message['type']! as String; final String type = message['type']! as String;
switch (type) { return switch (type) {
case 'keydown': 'keydown' => RawKeyDownEvent(data: data, character: character, repeat: repeat),
return RawKeyDownEvent(data: data, character: character, repeat: repeat); 'keyup' => RawKeyUpEvent(data: data),
case 'keyup': _ => throw FlutterError('Unknown key event type: $type'),
return RawKeyUpEvent(data: data); };
default:
throw FlutterError('Unknown key event type: $type');
}
} }
/// Returns true if the given [LogicalKeyboardKey] is pressed. /// Returns true if the given [LogicalKeyboardKey] is pressed.
......
...@@ -216,40 +216,27 @@ class RawKeyEventDataAndroid extends RawKeyEventData { ...@@ -216,40 +216,27 @@ class RawKeyEventDataAndroid extends RawKeyEventData {
if (metaState & anyMask == 0) { if (metaState & anyMask == 0) {
return false; return false;
} }
switch (side) { return switch (side) {
case KeyboardSide.any: KeyboardSide.any => true,
return true; KeyboardSide.all => (metaState & leftMask != 0) && (metaState & rightMask != 0),
case KeyboardSide.all: KeyboardSide.left => metaState & leftMask != 0,
return metaState & leftMask != 0 && metaState & rightMask != 0; KeyboardSide.right => metaState & rightMask != 0,
case KeyboardSide.left: };
return metaState & leftMask != 0;
case KeyboardSide.right:
return metaState & rightMask != 0;
}
} }
@override @override
bool isModifierPressed(ModifierKey key, { KeyboardSide side = KeyboardSide.any }) { bool isModifierPressed(ModifierKey key, { KeyboardSide side = KeyboardSide.any }) {
switch (key) { return switch (key) {
case ModifierKey.controlModifier: ModifierKey.controlModifier => _isLeftRightModifierPressed(side, modifierControl, modifierLeftControl, modifierRightControl),
return _isLeftRightModifierPressed(side, modifierControl, modifierLeftControl, modifierRightControl); ModifierKey.shiftModifier => _isLeftRightModifierPressed(side, modifierShift, modifierLeftShift, modifierRightShift),
case ModifierKey.shiftModifier: ModifierKey.altModifier => _isLeftRightModifierPressed(side, modifierAlt, modifierLeftAlt, modifierRightAlt),
return _isLeftRightModifierPressed(side, modifierShift, modifierLeftShift, modifierRightShift); ModifierKey.metaModifier => _isLeftRightModifierPressed(side, modifierMeta, modifierLeftMeta, modifierRightMeta),
case ModifierKey.altModifier: ModifierKey.capsLockModifier => metaState & modifierCapsLock != 0,
return _isLeftRightModifierPressed(side, modifierAlt, modifierLeftAlt, modifierRightAlt); ModifierKey.numLockModifier => metaState & modifierNumLock != 0,
case ModifierKey.metaModifier: ModifierKey.scrollLockModifier => metaState & modifierScrollLock != 0,
return _isLeftRightModifierPressed(side, modifierMeta, modifierLeftMeta, modifierRightMeta); ModifierKey.functionModifier => metaState & modifierFunction != 0,
case ModifierKey.capsLockModifier: ModifierKey.symbolModifier => metaState & modifierSym != 0,
return metaState & modifierCapsLock != 0; };
case ModifierKey.numLockModifier:
return metaState & modifierNumLock != 0;
case ModifierKey.scrollLockModifier:
return metaState & modifierScrollLock != 0;
case ModifierKey.functionModifier:
return metaState & modifierFunction != 0;
case ModifierKey.symbolModifier:
return metaState & modifierSym != 0;
}
} }
@override @override
......
...@@ -99,16 +99,12 @@ class RawKeyEventDataFuchsia extends RawKeyEventData { ...@@ -99,16 +99,12 @@ class RawKeyEventDataFuchsia extends RawKeyEventData {
if (modifiers & anyMask == 0) { if (modifiers & anyMask == 0) {
return false; return false;
} }
switch (side) { return switch (side) {
case KeyboardSide.any: KeyboardSide.any => true,
return true; KeyboardSide.all => (modifiers & leftMask != 0) && (modifiers & rightMask != 0),
case KeyboardSide.all: KeyboardSide.left => modifiers & leftMask != 0,
return modifiers & leftMask != 0 && modifiers & rightMask != 0; KeyboardSide.right => modifiers & rightMask != 0,
case KeyboardSide.left: };
return modifiers & leftMask != 0;
case KeyboardSide.right:
return modifiers & rightMask != 0;
}
} }
@override @override
......
...@@ -307,27 +307,15 @@ class GLFWKeyHelper implements KeyHelper { ...@@ -307,27 +307,15 @@ class GLFWKeyHelper implements KeyHelper {
// a key down, then we need to add the correct modifier bits, and if it's a // a key down, then we need to add the correct modifier bits, and if it's a
// key up, we need to remove them. // key up, we need to remove them.
int modifierChange = 0; final int modifierChange = switch (keyCode) {
switch (keyCode) { shiftLeftKeyCode || shiftRightKeyCode => modifierShift,
case shiftLeftKeyCode: controlLeftKeyCode || controlRightKeyCode => modifierControl,
case shiftRightKeyCode: altLeftKeyCode || altRightKeyCode => modifierAlt,
modifierChange = modifierShift; metaLeftKeyCode || metaRightKeyCode => modifierMeta,
case controlLeftKeyCode: capsLockKeyCode => modifierCapsLock,
case controlRightKeyCode: numLockKeyCode => modifierNumericPad,
modifierChange = modifierControl; _ => 0,
case altLeftKeyCode: };
case altRightKeyCode:
modifierChange = modifierAlt;
case metaLeftKeyCode:
case metaRightKeyCode:
modifierChange = modifierMeta;
case capsLockKeyCode:
modifierChange = modifierCapsLock;
case numLockKeyCode:
modifierChange = modifierNumericPad;
default:
break;
}
return isDown ? modifiers | modifierChange : modifiers & ~modifierChange; return isDown ? modifiers | modifierChange : modifiers & ~modifierChange;
} }
...@@ -335,25 +323,18 @@ class GLFWKeyHelper implements KeyHelper { ...@@ -335,25 +323,18 @@ class GLFWKeyHelper implements KeyHelper {
@override @override
bool isModifierPressed(ModifierKey key, int modifiers, {KeyboardSide side = KeyboardSide.any, required int keyCode, required bool isDown}) { bool isModifierPressed(ModifierKey key, int modifiers, {KeyboardSide side = KeyboardSide.any, required int keyCode, required bool isDown}) {
modifiers = _mergeModifiers(modifiers: modifiers, keyCode: keyCode, isDown: isDown); modifiers = _mergeModifiers(modifiers: modifiers, keyCode: keyCode, isDown: isDown);
switch (key) { return switch (key) {
case ModifierKey.controlModifier: ModifierKey.controlModifier => modifiers & modifierControl != 0,
return modifiers & modifierControl != 0; ModifierKey.shiftModifier => modifiers & modifierShift != 0,
case ModifierKey.shiftModifier: ModifierKey.altModifier => modifiers & modifierAlt != 0,
return modifiers & modifierShift != 0; ModifierKey.metaModifier => modifiers & modifierMeta != 0,
case ModifierKey.altModifier: ModifierKey.capsLockModifier => modifiers & modifierCapsLock != 0,
return modifiers & modifierAlt != 0; ModifierKey.numLockModifier => modifiers & modifierNumericPad != 0,
case ModifierKey.metaModifier: // These are not used in GLFW keyboards.
return modifiers & modifierMeta != 0; ModifierKey.functionModifier => false,
case ModifierKey.capsLockModifier: ModifierKey.symbolModifier => false,
return modifiers & modifierCapsLock != 0; ModifierKey.scrollLockModifier => false,
case ModifierKey.numLockModifier: };
return modifiers & modifierNumericPad != 0;
case ModifierKey.functionModifier:
case ModifierKey.symbolModifier:
case ModifierKey.scrollLockModifier:
// These are not used in GLFW keyboards.
return false;
}
} }
@override @override
...@@ -451,28 +432,15 @@ class GtkKeyHelper implements KeyHelper { ...@@ -451,28 +432,15 @@ class GtkKeyHelper implements KeyHelper {
// a key down, then we need to add the correct modifier bits, and if it's a // a key down, then we need to add the correct modifier bits, and if it's a
// key up, we need to remove them. // key up, we need to remove them.
int modifierChange = 0; final int modifierChange = switch (keyCode) {
switch (keyCode) { shiftLeftKeyCode || shiftRightKeyCode => modifierShift,
case shiftLeftKeyCode: controlLeftKeyCode || controlRightKeyCode => modifierControl,
case shiftRightKeyCode: altLeftKeyCode || altRightKeyCode => modifierMod1,
modifierChange = modifierShift; metaLeftKeyCode || metaRightKeyCode => modifierMeta,
case controlLeftKeyCode: capsLockKeyCode || shiftLockKeyCode => modifierCapsLock,
case controlRightKeyCode: numLockKeyCode => modifierMod2,
modifierChange = modifierControl; _ => 0,
case altLeftKeyCode: };
case altRightKeyCode:
modifierChange = modifierMod1;
case metaLeftKeyCode:
case metaRightKeyCode:
modifierChange = modifierMeta;
case capsLockKeyCode:
case shiftLockKeyCode:
modifierChange = modifierCapsLock;
case numLockKeyCode:
modifierChange = modifierMod2;
default:
break;
}
return isDown ? modifiers | modifierChange : modifiers & ~modifierChange; return isDown ? modifiers | modifierChange : modifiers & ~modifierChange;
} }
...@@ -480,25 +448,18 @@ class GtkKeyHelper implements KeyHelper { ...@@ -480,25 +448,18 @@ class GtkKeyHelper implements KeyHelper {
@override @override
bool isModifierPressed(ModifierKey key, int modifiers, {KeyboardSide side = KeyboardSide.any, required int keyCode, required bool isDown}) { bool isModifierPressed(ModifierKey key, int modifiers, {KeyboardSide side = KeyboardSide.any, required int keyCode, required bool isDown}) {
modifiers = _mergeModifiers(modifiers: modifiers, keyCode: keyCode, isDown: isDown); modifiers = _mergeModifiers(modifiers: modifiers, keyCode: keyCode, isDown: isDown);
switch (key) { return switch (key) {
case ModifierKey.controlModifier: ModifierKey.controlModifier => modifiers & modifierControl != 0,
return modifiers & modifierControl != 0; ModifierKey.shiftModifier => modifiers & modifierShift != 0,
case ModifierKey.shiftModifier: ModifierKey.altModifier => modifiers & modifierMod1 != 0,
return modifiers & modifierShift != 0; ModifierKey.metaModifier => modifiers & modifierMeta != 0,
case ModifierKey.altModifier: ModifierKey.capsLockModifier => modifiers & modifierCapsLock != 0,
return modifiers & modifierMod1 != 0; ModifierKey.numLockModifier => modifiers & modifierMod2 != 0,
case ModifierKey.metaModifier: // These are not used in GTK keyboards.
return modifiers & modifierMeta != 0; ModifierKey.functionModifier => false,
case ModifierKey.capsLockModifier: ModifierKey.symbolModifier => false,
return modifiers & modifierCapsLock != 0; ModifierKey.scrollLockModifier => false,
case ModifierKey.numLockModifier: };
return modifiers & modifierMod2 != 0;
case ModifierKey.functionModifier:
case ModifierKey.symbolModifier:
case ModifierKey.scrollLockModifier:
// These are not used in GTK keyboards.
return false;
}
} }
@override @override
......
...@@ -131,30 +131,18 @@ class RawKeyEventDataWeb extends RawKeyEventData { ...@@ -131,30 +131,18 @@ class RawKeyEventDataWeb extends RawKeyEventData {
} }
@override @override
bool isModifierPressed( bool isModifierPressed(ModifierKey key, {KeyboardSide side = KeyboardSide.any}) {
ModifierKey key, { return switch (key) {
KeyboardSide side = KeyboardSide.any, ModifierKey.controlModifier => metaState & modifierControl != 0,
}) { ModifierKey.shiftModifier => metaState & modifierShift != 0,
switch (key) { ModifierKey.altModifier => metaState & modifierAlt != 0,
case ModifierKey.controlModifier: ModifierKey.metaModifier => metaState & modifierMeta != 0,
return metaState & modifierControl != 0; ModifierKey.numLockModifier => metaState & modifierNumLock != 0,
case ModifierKey.shiftModifier: ModifierKey.capsLockModifier => metaState & modifierCapsLock != 0,
return metaState & modifierShift != 0; ModifierKey.scrollLockModifier => metaState & modifierScrollLock != 0,
case ModifierKey.altModifier: // On Web, the browser doesn't report the state of the FN and SYM modifiers.
return metaState & modifierAlt != 0; ModifierKey.functionModifier || ModifierKey.symbolModifier => false,
case ModifierKey.metaModifier: };
return metaState & modifierMeta != 0;
case ModifierKey.numLockModifier:
return metaState & modifierNumLock != 0;
case ModifierKey.capsLockModifier:
return metaState & modifierCapsLock != 0;
case ModifierKey.scrollLockModifier:
return metaState & modifierScrollLock != 0;
case ModifierKey.functionModifier:
case ModifierKey.symbolModifier:
// On Web, the browser doesn't report the state of the FN and SYM modifiers.
return false;
}
} }
@override @override
......
...@@ -15,13 +15,11 @@ export 'text_editing.dart' show TextSelection; ...@@ -15,13 +15,11 @@ export 'text_editing.dart' show TextSelection;
export 'text_input.dart' show TextEditingValue; export 'text_input.dart' show TextEditingValue;
TextAffinity? _toTextAffinity(String? affinity) { TextAffinity? _toTextAffinity(String? affinity) {
switch (affinity) { return switch (affinity) {
case 'TextAffinity.downstream': 'TextAffinity.downstream' => TextAffinity.downstream,
return TextAffinity.downstream; 'TextAffinity.upstream' => TextAffinity.upstream,
case 'TextAffinity.upstream': _ => null,
return TextAffinity.upstream; };
}
return null;
} }
// Replaces a range of text in the original string with the text given in the // Replaces a range of text in the original string with the text given in the
......
...@@ -712,13 +712,11 @@ class TextInputConfiguration { ...@@ -712,13 +712,11 @@ class TextInputConfiguration {
} }
TextAffinity? _toTextAffinity(String? affinity) { TextAffinity? _toTextAffinity(String? affinity) {
switch (affinity) { return switch (affinity) {
case 'TextAffinity.downstream': 'TextAffinity.downstream' => TextAffinity.downstream,
return TextAffinity.downstream; 'TextAffinity.upstream' => TextAffinity.upstream,
case 'TextAffinity.upstream': _ => null,
return TextAffinity.upstream; };
}
return null;
} }
/// The state of a "floating cursor" drag on an iOS soft keyboard. /// The state of a "floating cursor" drag on an iOS soft keyboard.
...@@ -1515,47 +1513,31 @@ class TextInputConnection { ...@@ -1515,47 +1513,31 @@ class TextInputConnection {
} }
TextInputAction _toTextInputAction(String action) { TextInputAction _toTextInputAction(String action) {
switch (action) { return switch (action) {
case 'TextInputAction.none': 'TextInputAction.none' => TextInputAction.none,
return TextInputAction.none; 'TextInputAction.unspecified' => TextInputAction.unspecified,
case 'TextInputAction.unspecified': 'TextInputAction.go' => TextInputAction.go,
return TextInputAction.unspecified; 'TextInputAction.search' => TextInputAction.search,
case 'TextInputAction.go': 'TextInputAction.send' => TextInputAction.send,
return TextInputAction.go; 'TextInputAction.next' => TextInputAction.next,
case 'TextInputAction.search': 'TextInputAction.previous' => TextInputAction.previous,
return TextInputAction.search; 'TextInputAction.continueAction' => TextInputAction.continueAction,
case 'TextInputAction.send': 'TextInputAction.join' => TextInputAction.join,
return TextInputAction.send; 'TextInputAction.route' => TextInputAction.route,
case 'TextInputAction.next': 'TextInputAction.emergencyCall' => TextInputAction.emergencyCall,
return TextInputAction.next; 'TextInputAction.done' => TextInputAction.done,
case 'TextInputAction.previous': 'TextInputAction.newline' => TextInputAction.newline,
return TextInputAction.previous; _ => throw FlutterError.fromParts(<DiagnosticsNode>[ErrorSummary('Unknown text input action: $action')]),
case 'TextInputAction.continueAction': };
return TextInputAction.continueAction;
case 'TextInputAction.join':
return TextInputAction.join;
case 'TextInputAction.route':
return TextInputAction.route;
case 'TextInputAction.emergencyCall':
return TextInputAction.emergencyCall;
case 'TextInputAction.done':
return TextInputAction.done;
case 'TextInputAction.newline':
return TextInputAction.newline;
}
throw FlutterError.fromParts(<DiagnosticsNode>[ErrorSummary('Unknown text input action: $action')]);
} }
FloatingCursorDragState _toTextCursorAction(String state) { FloatingCursorDragState _toTextCursorAction(String state) {
switch (state) { return switch (state) {
case 'FloatingCursorDragState.start': 'FloatingCursorDragState.start' => FloatingCursorDragState.Start,
return FloatingCursorDragState.Start; 'FloatingCursorDragState.update' => FloatingCursorDragState.Update,
case 'FloatingCursorDragState.update': 'FloatingCursorDragState.end' => FloatingCursorDragState.End,
return FloatingCursorDragState.Update; _ => throw FlutterError.fromParts(<DiagnosticsNode>[ErrorSummary('Unknown text cursor action: $state')]),
case 'FloatingCursorDragState.end': };
return FloatingCursorDragState.End;
}
throw FlutterError.fromParts(<DiagnosticsNode>[ErrorSummary('Unknown text cursor action: $state')]);
} }
RawFloatingCursorPoint _toTextPoint(FloatingCursorDragState state, Map<String, dynamic> encoded) { RawFloatingCursorPoint _toTextPoint(FloatingCursorDragState state, Map<String, dynamic> encoded) {
......
...@@ -98,13 +98,11 @@ class UndoManager { ...@@ -98,13 +98,11 @@ class UndoManager {
} }
UndoDirection _toUndoDirection(String direction) { UndoDirection _toUndoDirection(String direction) {
switch (direction) { return switch (direction) {
case 'undo': 'undo' => UndoDirection.undo,
return UndoDirection.undo; 'redo' => UndoDirection.redo,
case 'redo': _ => throw FlutterError.fromParts(<DiagnosticsNode>[ErrorSummary('Unknown undo direction: $direction')]),
return UndoDirection.redo; };
}
throw FlutterError.fromParts(<DiagnosticsNode>[ErrorSummary('Unknown undo direction: $direction')]);
} }
} }
......
...@@ -1167,14 +1167,13 @@ class _ReadingOrderSortData with Diagnosticable { ...@@ -1167,14 +1167,13 @@ class _ReadingOrderSortData with Diagnosticable {
} }
static void sortWithDirectionality(List<_ReadingOrderSortData> list, TextDirection directionality) { static void sortWithDirectionality(List<_ReadingOrderSortData> list, TextDirection directionality) {
mergeSort<_ReadingOrderSortData>(list, compare: (_ReadingOrderSortData a, _ReadingOrderSortData b) { mergeSort<_ReadingOrderSortData>(
switch (directionality) { list,
case TextDirection.ltr: compare: (_ReadingOrderSortData a, _ReadingOrderSortData b) => switch (directionality) {
return a.rect.left.compareTo(b.rect.left); TextDirection.ltr => a.rect.left.compareTo(b.rect.left),
case TextDirection.rtl: TextDirection.rtl => b.rect.right.compareTo(a.rect.right),
return b.rect.right.compareTo(a.rect.right); },
} );
});
} }
/// Returns the list of Directionality ancestors, in order from nearest to /// Returns the list of Directionality ancestors, in order from nearest to
...@@ -1238,14 +1237,13 @@ class _ReadingOrderDirectionalGroupData with Diagnosticable { ...@@ -1238,14 +1237,13 @@ class _ReadingOrderDirectionalGroupData with Diagnosticable {
List<Directionality>? _memberAncestors; List<Directionality>? _memberAncestors;
static void sortWithDirectionality(List<_ReadingOrderDirectionalGroupData> list, TextDirection directionality) { static void sortWithDirectionality(List<_ReadingOrderDirectionalGroupData> list, TextDirection directionality) {
mergeSort<_ReadingOrderDirectionalGroupData>(list, compare: (_ReadingOrderDirectionalGroupData a, _ReadingOrderDirectionalGroupData b) { mergeSort<_ReadingOrderDirectionalGroupData>(
switch (directionality) { list,
case TextDirection.ltr: compare: (_ReadingOrderDirectionalGroupData a, _ReadingOrderDirectionalGroupData b) => switch (directionality) {
return a.rect.left.compareTo(b.rect.left); TextDirection.ltr => a.rect.left.compareTo(b.rect.left),
case TextDirection.rtl: TextDirection.rtl => b.rect.right.compareTo(a.rect.right),
return b.rect.right.compareTo(a.rect.right); },
} );
});
} }
@override @override
......
...@@ -600,19 +600,15 @@ class _InteractiveViewerState extends State<InteractiveViewer> with TickerProvid ...@@ -600,19 +600,15 @@ class _InteractiveViewerState extends State<InteractiveViewer> with TickerProvid
return matrix.clone(); return matrix.clone();
} }
late final Offset alignedTranslation; final Offset alignedTranslation;
if (_currentAxis != null) { if (_currentAxis != null) {
switch (widget.panAxis){ alignedTranslation = switch (widget.panAxis){
case PanAxis.horizontal: PanAxis.horizontal => _alignAxis(translation, Axis.horizontal),
alignedTranslation = _alignAxis(translation, Axis.horizontal); PanAxis.vertical => _alignAxis(translation, Axis.vertical),
case PanAxis.vertical: PanAxis.aligned => _alignAxis(translation, _currentAxis!),
alignedTranslation = _alignAxis(translation, Axis.vertical); PanAxis.free => translation,
case PanAxis.aligned: };
alignedTranslation = _alignAxis(translation, _currentAxis!);
case PanAxis.free:
alignedTranslation = translation;
}
} else { } else {
alignedTranslation = translation; alignedTranslation = translation;
} }
...@@ -739,17 +735,11 @@ class _InteractiveViewerState extends State<InteractiveViewer> with TickerProvid ...@@ -739,17 +735,11 @@ class _InteractiveViewerState extends State<InteractiveViewer> with TickerProvid
// Returns true iff the given _GestureType is enabled. // Returns true iff the given _GestureType is enabled.
bool _gestureIsSupported(_GestureType? gestureType) { bool _gestureIsSupported(_GestureType? gestureType) {
switch (gestureType) { return switch (gestureType) {
case _GestureType.rotate: _GestureType.rotate => _rotateEnabled,
return _rotateEnabled; _GestureType.scale => widget.scaleEnabled,
_GestureType.pan || null => widget.panEnabled,
case _GestureType.scale: };
return widget.scaleEnabled;
case _GestureType.pan:
case null:
return widget.panEnabled;
}
} }
// Decide which type of gesture this is by comparing the amount of scale // Decide which type of gesture this is by comparing the amount of scale
...@@ -1448,12 +1438,10 @@ Offset _round(Offset offset) { ...@@ -1448,12 +1438,10 @@ Offset _round(Offset offset) {
// Align the given offset to the given axis by allowing movement only in the // Align the given offset to the given axis by allowing movement only in the
// axis direction. // axis direction.
Offset _alignAxis(Offset offset, Axis axis) { Offset _alignAxis(Offset offset, Axis axis) {
switch (axis) { return switch (axis) {
case Axis.horizontal: Axis.horizontal => Offset(offset.dx, 0.0),
return Offset(offset.dx, 0.0); Axis.vertical => Offset(0.0, offset.dy),
case Axis.vertical: };
return Offset(0.0, offset.dy);
}
} }
// Given two points, return the axis where the distance between the points is // Given two points, return the axis where the distance between the points is
......
...@@ -743,13 +743,6 @@ class BouncingScrollPhysics extends ScrollPhysics { ...@@ -743,13 +743,6 @@ class BouncingScrollPhysics extends ScrollPhysics {
Simulation? createBallisticSimulation(ScrollMetrics position, double velocity) { Simulation? createBallisticSimulation(ScrollMetrics position, double velocity) {
final Tolerance tolerance = toleranceFor(position); final Tolerance tolerance = toleranceFor(position);
if (velocity.abs() >= tolerance.velocity || position.outOfRange) { if (velocity.abs() >= tolerance.velocity || position.outOfRange) {
double constantDeceleration;
switch (decelerationRate) {
case ScrollDecelerationRate.fast:
constantDeceleration = 1400;
case ScrollDecelerationRate.normal:
constantDeceleration = 0;
}
return BouncingScrollSimulation( return BouncingScrollSimulation(
spring: spring, spring: spring,
position: position.pixels, position: position.pixels,
...@@ -757,7 +750,10 @@ class BouncingScrollPhysics extends ScrollPhysics { ...@@ -757,7 +750,10 @@ class BouncingScrollPhysics extends ScrollPhysics {
leadingExtent: position.minScrollExtent, leadingExtent: position.minScrollExtent,
trailingExtent: position.maxScrollExtent, trailingExtent: position.maxScrollExtent,
tolerance: tolerance, tolerance: tolerance,
constantDeceleration: constantDeceleration constantDeceleration: switch (decelerationRate) {
ScrollDecelerationRate.fast => 1400,
ScrollDecelerationRate.normal => 0,
},
); );
} }
return null; return null;
...@@ -795,12 +791,10 @@ class BouncingScrollPhysics extends ScrollPhysics { ...@@ -795,12 +791,10 @@ class BouncingScrollPhysics extends ScrollPhysics {
@override @override
double get maxFlingVelocity { double get maxFlingVelocity {
switch (decelerationRate) { return switch (decelerationRate) {
case ScrollDecelerationRate.fast: ScrollDecelerationRate.fast => kMaxFlingVelocity * 8.0,
return kMaxFlingVelocity * 8.0; ScrollDecelerationRate.normal => super.maxFlingVelocity,
case ScrollDecelerationRate.normal: };
return super.maxFlingVelocity;
}
} }
@override @override
......
...@@ -722,22 +722,12 @@ abstract class ScrollPosition extends ViewportOffset with ScrollMetrics { ...@@ -722,22 +722,12 @@ abstract class ScrollPosition extends ViewportOffset with ScrollMetrics {
/// scroll view dimensions both change) and therefore shouldn't do anything /// scroll view dimensions both change) and therefore shouldn't do anything
/// expensive. /// expensive.
void _updateSemanticActions() { void _updateSemanticActions() {
final SemanticsAction forward; final (SemanticsAction forward, SemanticsAction backward) = switch (axisDirection) {
final SemanticsAction backward; AxisDirection.up => (SemanticsAction.scrollDown, SemanticsAction.scrollUp),
switch (axisDirection) { AxisDirection.down => (SemanticsAction.scrollUp, SemanticsAction.scrollDown),
case AxisDirection.up: AxisDirection.left => (SemanticsAction.scrollRight, SemanticsAction.scrollLeft),
forward = SemanticsAction.scrollDown; AxisDirection.right => (SemanticsAction.scrollLeft, SemanticsAction.scrollRight),
backward = SemanticsAction.scrollUp; };
case AxisDirection.right:
forward = SemanticsAction.scrollLeft;
backward = SemanticsAction.scrollRight;
case AxisDirection.down:
forward = SemanticsAction.scrollUp;
backward = SemanticsAction.scrollDown;
case AxisDirection.left:
forward = SemanticsAction.scrollRight;
backward = SemanticsAction.scrollLeft;
}
final Set<SemanticsAction> actions = <SemanticsAction>{}; final Set<SemanticsAction> actions = <SemanticsAction>{};
if (pixels > minScrollExtent) { if (pixels > minScrollExtent) {
......
...@@ -548,16 +548,12 @@ class ScrollableState extends State<Scrollable> with TickerProviderStateMixin, R ...@@ -548,16 +548,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) {
case AxisDirection.down: AxisDirection.up => Offset(0, -position.pixels),
return Offset(0, position.pixels); AxisDirection.down => Offset(0, position.pixels),
case AxisDirection.up: AxisDirection.left => Offset(-position.pixels, 0),
return Offset(0, -position.pixels); AxisDirection.right => Offset(position.pixels, 0),
case AxisDirection.left: };
return Offset(-position.pixels, 0);
case AxisDirection.right:
return Offset(position.pixels, 0);
}
} }
ScrollController get _effectiveScrollController => widget.controller ?? _fallbackScrollController!; ScrollController get _effectiveScrollController => widget.controller ?? _fallbackScrollController!;
...@@ -1491,16 +1487,12 @@ class _ScrollableSelectionContainerDelegate extends MultiSelectableSelectionCont ...@@ -1491,16 +1487,12 @@ class _ScrollableSelectionContainerDelegate extends MultiSelectableSelectionCont
} }
Offset _getDeltaToScrollOrigin(ScrollableState scrollableState) { Offset _getDeltaToScrollOrigin(ScrollableState scrollableState) {
switch (scrollableState.axisDirection) { return switch (scrollableState.axisDirection) {
case AxisDirection.down: AxisDirection.up => Offset(0, -scrollableState.position.pixels),
return Offset(0, scrollableState.position.pixels); AxisDirection.down => Offset(0, scrollableState.position.pixels),
case AxisDirection.up: AxisDirection.left => Offset(-scrollableState.position.pixels, 0),
return Offset(0, -scrollableState.position.pixels); AxisDirection.right => Offset(scrollableState.position.pixels, 0),
case AxisDirection.left: };
return Offset(-scrollableState.position.pixels, 0);
case AxisDirection.right:
return Offset(scrollableState.position.pixels, 0);
}
} }
/// With [_ScrollSemantics] certain child [SemanticsNode]s can be /// With [_ScrollSemantics] certain child [SemanticsNode]s can be
......
...@@ -184,21 +184,17 @@ class EdgeDraggingAutoScroller { ...@@ -184,21 +184,17 @@ class EdgeDraggingAutoScroller {
bool _scrolling = false; bool _scrolling = false;
double _offsetExtent(Offset offset, Axis scrollDirection) { double _offsetExtent(Offset offset, Axis scrollDirection) {
switch (scrollDirection) { return switch (scrollDirection) {
case Axis.horizontal: Axis.horizontal => offset.dx,
return offset.dx; Axis.vertical => offset.dy,
case Axis.vertical: };
return offset.dy;
}
} }
double _sizeExtent(Size size, Axis scrollDirection) { double _sizeExtent(Size size, Axis scrollDirection) {
switch (scrollDirection) { return switch (scrollDirection) {
case Axis.horizontal: Axis.horizontal => size.width,
return size.width; Axis.vertical => size.height,
case Axis.vertical: };
return size.height;
}
} }
AxisDirection get _axisDirection => scrollable.axisDirection; AxisDirection get _axisDirection => scrollable.axisDirection;
...@@ -415,12 +411,10 @@ class ScrollAction extends ContextAction<ScrollIntent> { ...@@ -415,12 +411,10 @@ class ScrollAction extends ContextAction<ScrollIntent> {
), ),
); );
} }
switch (type) { return switch (type) {
case ScrollIncrementType.line: ScrollIncrementType.line => 50.0,
return 50.0; ScrollIncrementType.page => 0.8 * state.position.viewportDimension,
case ScrollIncrementType.page: };
return 0.8 * state.position.viewportDimension;
}
} }
/// Find out how much of an increment to move by, taking the different /// Find out how much of an increment to move by, taking the different
......
...@@ -384,14 +384,10 @@ class ScrollbarPainter extends ChangeNotifier implements CustomPainter { ...@@ -384,14 +384,10 @@ class ScrollbarPainter extends ChangeNotifier implements CustomPainter {
// 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 { double get _leadingTrackMainAxisOffset {
switch (_resolvedOrientation) { return switch (_resolvedOrientation) {
case ScrollbarOrientation.left: ScrollbarOrientation.left || ScrollbarOrientation.right => padding.top,
case ScrollbarOrientation.right: ScrollbarOrientation.top || ScrollbarOrientation.bottom => padding.left,
return padding.top; };
case ScrollbarOrientation.top:
case ScrollbarOrientation.bottom:
return padding.left;
}
} }
Rect? _thumbRect; Rect? _thumbRect;
...@@ -401,16 +397,8 @@ class ScrollbarPainter extends ChangeNotifier implements CustomPainter { ...@@ -401,16 +397,8 @@ class ScrollbarPainter extends ChangeNotifier implements CustomPainter {
late double _thumbExtent; late double _thumbExtent;
// Thumb Offsets // Thumb Offsets
// The thumb is offset by padding and margins. // The thumb is offset by padding and margins.
double get _leadingThumbMainAxisOffset { double get _leadingThumbMainAxisOffset => _leadingTrackMainAxisOffset + mainAxisMargin;
switch (_resolvedOrientation) {
case ScrollbarOrientation.left:
case ScrollbarOrientation.right:
return padding.top + mainAxisMargin;
case ScrollbarOrientation.top:
case ScrollbarOrientation.bottom:
return padding.left + mainAxisMargin;
}
}
void _setThumbExtent() { void _setThumbExtent() {
// Thumb extent reflects fraction of content visible, as long as this // Thumb extent reflects fraction of content visible, as long as this
// isn't less than the absolute minimum size. // isn't less than the absolute minimum size.
......
...@@ -2321,14 +2321,10 @@ abstract class MultiSelectableSelectionContainerDelegate extends SelectionContai ...@@ -2321,14 +2321,10 @@ abstract class MultiSelectableSelectionContainerDelegate extends SelectionContai
SelectionResult handleDirectionallyExtendSelection(DirectionallyExtendSelectionEvent event) { SelectionResult handleDirectionallyExtendSelection(DirectionallyExtendSelectionEvent event) {
assert((currentSelectionStartIndex == -1) == (currentSelectionEndIndex == -1)); assert((currentSelectionStartIndex == -1) == (currentSelectionEndIndex == -1));
if (currentSelectionStartIndex == -1) { if (currentSelectionStartIndex == -1) {
switch (event.direction) { currentSelectionStartIndex = currentSelectionEndIndex = switch (event.direction) {
case SelectionExtendDirection.previousLine: SelectionExtendDirection.previousLine || SelectionExtendDirection.backward => selectables.length,
case SelectionExtendDirection.backward: SelectionExtendDirection.nextLine || SelectionExtendDirection.forward => 0,
currentSelectionStartIndex = currentSelectionEndIndex = selectables.length; };
case SelectionExtendDirection.nextLine:
case SelectionExtendDirection.forward:
currentSelectionStartIndex = currentSelectionEndIndex = 0;
}
} }
int targetIndex = event.isEnd ? currentSelectionEndIndex : currentSelectionStartIndex; int targetIndex = event.isEnd ? currentSelectionEndIndex : currentSelectionStartIndex;
SelectionResult result = dispatchSelectionEventToChild(selectables[targetIndex], event); SelectionResult result = dispatchSelectionEventToChild(selectables[targetIndex], event);
......
...@@ -404,12 +404,10 @@ class _RenderSingleChildViewport extends RenderBox with RenderObjectWithChildMix ...@@ -404,12 +404,10 @@ class _RenderSingleChildViewport extends RenderBox with RenderObjectWithChildMix
double get _viewportExtent { double get _viewportExtent {
assert(hasSize); assert(hasSize);
switch (axis) { return switch (axis) {
case Axis.horizontal: Axis.horizontal => size.width,
return size.width; Axis.vertical => size.height,
case Axis.vertical: };
return size.height;
}
} }
double get _minScrollExtent { double get _minScrollExtent {
...@@ -422,21 +420,17 @@ class _RenderSingleChildViewport extends RenderBox with RenderObjectWithChildMix ...@@ -422,21 +420,17 @@ class _RenderSingleChildViewport extends RenderBox with RenderObjectWithChildMix
if (child == null) { if (child == null) {
return 0.0; return 0.0;
} }
switch (axis) { return math.max(0.0, switch (axis) {
case Axis.horizontal: Axis.horizontal => child!.size.width - size.width,
return math.max(0.0, child!.size.width - size.width); Axis.vertical => child!.size.height - size.height,
case Axis.vertical: });
return math.max(0.0, child!.size.height - size.height);
}
} }
BoxConstraints _getInnerConstraints(BoxConstraints constraints) { BoxConstraints _getInnerConstraints(BoxConstraints constraints) {
switch (axis) { return switch (axis) {
case Axis.horizontal: Axis.horizontal => constraints.heightConstraints(),
return constraints.heightConstraints(); Axis.vertical => constraints.widthConstraints(),
case Axis.vertical: };
return constraints.widthConstraints();
}
} }
@override @override
...@@ -510,16 +504,12 @@ class _RenderSingleChildViewport extends RenderBox with RenderObjectWithChildMix ...@@ -510,16 +504,12 @@ class _RenderSingleChildViewport extends RenderBox with RenderObjectWithChildMix
Offset get _paintOffset => _paintOffsetForPosition(offset.pixels); Offset get _paintOffset => _paintOffsetForPosition(offset.pixels);
Offset _paintOffsetForPosition(double position) { Offset _paintOffsetForPosition(double position) {
switch (axisDirection) { return switch (axisDirection) {
case AxisDirection.up: AxisDirection.up => Offset(0.0, position - child!.size.height + size.height),
return Offset(0.0, position - child!.size.height + size.height); AxisDirection.left => Offset(position - child!.size.width + size.width, 0.0),
case AxisDirection.down: AxisDirection.right => Offset(-position, 0.0),
return Offset(0.0, -position); AxisDirection.down => Offset(0.0, -position),
case AxisDirection.left: };
return Offset(position - child!.size.width + size.width, 0.0);
case AxisDirection.right:
return Offset(-position, 0.0);
}
} }
bool _shouldClipAtPaintOffset(Offset paintOffset) { bool _shouldClipAtPaintOffset(Offset paintOffset) {
...@@ -620,28 +610,12 @@ class _RenderSingleChildViewport extends RenderBox with RenderObjectWithChildMix ...@@ -620,28 +610,12 @@ class _RenderSingleChildViewport extends RenderBox with RenderObjectWithChildMix
final Rect bounds = MatrixUtils.transformRect(transform, rect); final Rect bounds = MatrixUtils.transformRect(transform, rect);
final Size contentSize = child!.size; final Size contentSize = child!.size;
final double leadingScrollOffset; final (double mainAxisExtent, double leadingScrollOffset, double targetMainAxisExtent) = switch (axisDirection) {
final double targetMainAxisExtent; AxisDirection.up => (size.height, contentSize.height - bounds.bottom, bounds.height),
final double mainAxisExtent; AxisDirection.left => (size.width, contentSize.width - bounds.right, bounds.width),
AxisDirection.right => (size.width, bounds.left, bounds.width),
switch (axisDirection) { AxisDirection.down => (size.height, bounds.top, bounds.height),
case AxisDirection.up: };
mainAxisExtent = size.height;
leadingScrollOffset = contentSize.height - bounds.bottom;
targetMainAxisExtent = bounds.height;
case AxisDirection.right:
mainAxisExtent = size.width;
leadingScrollOffset = bounds.left;
targetMainAxisExtent = bounds.width;
case AxisDirection.down:
mainAxisExtent = size.height;
leadingScrollOffset = bounds.top;
targetMainAxisExtent = bounds.height;
case AxisDirection.left:
mainAxisExtent = size.width;
leadingScrollOffset = contentSize.width - bounds.right;
targetMainAxisExtent = bounds.width;
}
final double targetOffset = leadingScrollOffset - (mainAxisExtent - targetMainAxisExtent) * alignment; final double targetOffset = leadingScrollOffset - (mainAxisExtent - targetMainAxisExtent) * alignment;
final Rect targetRect = bounds.shift(_paintOffsetForPosition(targetOffset)); final Rect targetRect = bounds.shift(_paintOffsetForPosition(targetOffset));
......
...@@ -144,12 +144,10 @@ class _RenderSliverFractionalPadding extends RenderSliverEdgeInsetsPadding { ...@@ -144,12 +144,10 @@ class _RenderSliverFractionalPadding extends RenderSliverEdgeInsetsPadding {
final double paddingValue = constraints.viewportMainAxisExtent * viewportFraction; final double paddingValue = constraints.viewportMainAxisExtent * viewportFraction;
_lastResolvedConstraints = constraints; _lastResolvedConstraints = constraints;
switch (constraints.axis) { _resolvedPadding = switch (constraints.axis) {
case Axis.horizontal: Axis.horizontal => EdgeInsets.symmetric(horizontal: paddingValue),
_resolvedPadding = EdgeInsets.symmetric(horizontal: paddingValue); Axis.vertical => EdgeInsets.symmetric(vertical: paddingValue),
case Axis.vertical: };
_resolvedPadding = EdgeInsets.symmetric(vertical: paddingValue);
}
return; return;
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment