text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/rendering.dart';
import 'package:flutter/semantics.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'theme.dart';
/// Provides platform-specific acoustic and/or haptic feedback for certain
/// actions.
///
/// For example, to play the Android-typically click sound when a button is
/// tapped, call [forTap]. For the Android-specific vibration when long pressing
/// an element, call [forLongPress]. Alternatively, you can also wrap your
/// [GestureDetector.onTap] or [GestureDetector.onLongPress] callback in
/// [wrapForTap] or [wrapForLongPress] to achieve the same (see example code
/// below).
///
/// Calling any of these methods is a no-op on iOS as actions on that platform
/// typically don't provide haptic or acoustic feedback.
///
/// All methods in this class are usually called from within a
/// [StatelessWidget.build] method or from a [State]'s methods as you have to
/// provide a [BuildContext].
///
/// {@tool snippet}
///
/// To trigger platform-specific feedback before executing the actual callback:
///
/// ```dart
/// class WidgetWithWrappedHandler extends StatelessWidget {
/// const WidgetWithWrappedHandler({super.key});
///
/// @override
/// Widget build(BuildContext context) {
/// return GestureDetector(
/// onTap: Feedback.wrapForTap(_onTapHandler, context),
/// onLongPress: Feedback.wrapForLongPress(_onLongPressHandler, context),
/// child: const Text('X'),
/// );
/// }
///
/// void _onTapHandler() {
/// // Respond to tap.
/// }
///
/// void _onLongPressHandler() {
/// // Respond to long press.
/// }
/// }
/// ```
/// {@end-tool}
/// {@tool snippet}
///
/// Alternatively, you can also call [forTap] or [forLongPress] directly within
/// your tap or long press handler:
///
/// ```dart
/// class WidgetWithExplicitCall extends StatelessWidget {
/// const WidgetWithExplicitCall({super.key});
///
/// @override
/// Widget build(BuildContext context) {
/// return GestureDetector(
/// onTap: () {
/// // Do some work (e.g. check if the tap is valid)
/// Feedback.forTap(context);
/// // Do more work (e.g. respond to the tap)
/// },
/// onLongPress: () {
/// // Do some work (e.g. check if the long press is valid)
/// Feedback.forLongPress(context);
/// // Do more work (e.g. respond to the long press)
/// },
/// child: const Text('X'),
/// );
/// }
/// }
/// ```
/// {@end-tool}
abstract final class Feedback {
/// Provides platform-specific feedback for a tap.
///
/// On Android the click system sound is played. On iOS this is a no-op.
///
/// See also:
///
/// * [wrapForTap] to trigger platform-specific feedback before executing a
/// [GestureTapCallback].
static Future<void> forTap(BuildContext context) async {
context.findRenderObject()!.sendSemanticsEvent(const TapSemanticEvent());
switch (_platform(context)) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
return SystemSound.play(SystemSoundType.click);
case TargetPlatform.iOS:
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
return Future<void>.value();
}
}
/// Wraps a [GestureTapCallback] to provide platform specific feedback for a
/// tap before the provided callback is executed.
///
/// On Android the platform-typical click system sound is played. On iOS this
/// is a no-op as that platform usually doesn't provide feedback for a tap.
///
/// See also:
///
/// * [forTap] to just trigger the platform-specific feedback without wrapping
/// a [GestureTapCallback].
static GestureTapCallback? wrapForTap(GestureTapCallback? callback, BuildContext context) {
if (callback == null) {
return null;
}
return () {
Feedback.forTap(context);
callback();
};
}
/// Provides platform-specific feedback for a long press.
///
/// On Android the platform-typical vibration is triggered. On iOS this is a
/// no-op as that platform usually doesn't provide feedback for long presses.
///
/// See also:
///
/// * [wrapForLongPress] to trigger platform-specific feedback before
/// executing a [GestureLongPressCallback].
static Future<void> forLongPress(BuildContext context) {
context.findRenderObject()!.sendSemanticsEvent(const LongPressSemanticsEvent());
switch (_platform(context)) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
return HapticFeedback.vibrate();
case TargetPlatform.iOS:
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
return Future<void>.value();
}
}
/// Wraps a [GestureLongPressCallback] to provide platform specific feedback
/// for a long press before the provided callback is executed.
///
/// On Android the platform-typical vibration is triggered. On iOS this
/// is a no-op as that platform usually doesn't provide feedback for a long
/// press.
///
/// See also:
///
/// * [forLongPress] to just trigger the platform-specific feedback without
/// wrapping a [GestureLongPressCallback].
static GestureLongPressCallback? wrapForLongPress(GestureLongPressCallback? callback, BuildContext context) {
if (callback == null) {
return null;
}
return () {
Feedback.forLongPress(context);
callback();
};
}
static TargetPlatform _platform(BuildContext context) => Theme.of(context).platform;
}
| flutter/packages/flutter/lib/src/material/feedback.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/feedback.dart",
"repo_id": "flutter",
"token_count": 1853
} | 800 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/widgets.dart';
import 'ink_well.dart';
import 'material.dart';
const Duration _kUnconfirmedRippleDuration = Duration(seconds: 1);
const Duration _kFadeInDuration = Duration(milliseconds: 75);
const Duration _kRadiusDuration = Duration(milliseconds: 225);
const Duration _kFadeOutDuration = Duration(milliseconds: 375);
const Duration _kCancelDuration = Duration(milliseconds: 75);
// The fade out begins 225ms after the _fadeOutController starts. See confirm().
const double _kFadeOutIntervalStart = 225.0 / 375.0;
RectCallback? _getClipCallback(RenderBox referenceBox, bool containedInkWell, RectCallback? rectCallback) {
if (rectCallback != null) {
assert(containedInkWell);
return rectCallback;
}
if (containedInkWell) {
return () => Offset.zero & referenceBox.size;
}
return null;
}
double _getTargetRadius(RenderBox referenceBox, bool containedInkWell, RectCallback? rectCallback, Offset position) {
final Size size = rectCallback != null ? rectCallback().size : referenceBox.size;
final double d1 = size.bottomRight(Offset.zero).distance;
final double d2 = (size.topRight(Offset.zero) - size.bottomLeft(Offset.zero)).distance;
return math.max(d1, d2) / 2.0;
}
class _InkRippleFactory extends InteractiveInkFeatureFactory {
const _InkRippleFactory();
@override
InteractiveInkFeature create({
required MaterialInkController controller,
required RenderBox referenceBox,
required Offset position,
required Color color,
required TextDirection textDirection,
bool containedInkWell = false,
RectCallback? rectCallback,
BorderRadius? borderRadius,
ShapeBorder? customBorder,
double? radius,
VoidCallback? onRemoved,
}) {
return InkRipple(
controller: controller,
referenceBox: referenceBox,
position: position,
color: color,
containedInkWell: containedInkWell,
rectCallback: rectCallback,
borderRadius: borderRadius,
customBorder: customBorder,
radius: radius,
onRemoved: onRemoved,
textDirection: textDirection,
);
}
}
/// A visual reaction on a piece of [Material] to user input.
///
/// A circular ink feature whose origin starts at the input touch point and
/// whose radius expands from 60% of the final radius. The splash origin
/// animates to the center of its [referenceBox].
///
/// This object is rarely created directly. Instead of creating an ink ripple,
/// consider using an [InkResponse] or [InkWell] widget, which uses
/// gestures (such as tap and long-press) to trigger ink splashes. This class
/// is used when the [Theme]'s [ThemeData.splashFactory] is [InkRipple.splashFactory].
///
/// See also:
///
/// * [InkSplash], which is an ink splash feature that expands less
/// aggressively than the ripple.
/// * [InkResponse], which uses gestures to trigger ink highlights and ink
/// splashes in the parent [Material].
/// * [InkWell], which is a rectangular [InkResponse] (the most common type of
/// ink response).
/// * [Material], which is the widget on which the ink splash is painted.
/// * [InkHighlight], which is an ink feature that emphasizes a part of a
/// [Material].
class InkRipple extends InteractiveInkFeature {
/// Begin a ripple, centered at [position] relative to [referenceBox].
///
/// The [controller] argument is typically obtained via
/// `Material.of(context)`.
///
/// If [containedInkWell] is true, then the ripple will be sized to fit
/// the well rectangle, then clipped to it when drawn. The well
/// rectangle is the box returned by [rectCallback], if provided, or
/// otherwise is the bounds of the [referenceBox].
///
/// If [containedInkWell] is false, then [rectCallback] should be null.
/// The ink ripple is clipped only to the edges of the [Material].
/// This is the default.
///
/// When the ripple is removed, [onRemoved] will be called.
InkRipple({
required MaterialInkController controller,
required super.referenceBox,
required Offset position,
required Color color,
required TextDirection textDirection,
bool containedInkWell = false,
RectCallback? rectCallback,
BorderRadius? borderRadius,
super.customBorder,
double? radius,
super.onRemoved,
}) : _position = position,
_borderRadius = borderRadius ?? BorderRadius.zero,
_textDirection = textDirection,
_targetRadius = radius ?? _getTargetRadius(referenceBox, containedInkWell, rectCallback, position),
_clipCallback = _getClipCallback(referenceBox, containedInkWell, rectCallback),
super(controller: controller, color: color) {
// Immediately begin fading-in the initial splash.
_fadeInController = AnimationController(duration: _kFadeInDuration, vsync: controller.vsync)
..addListener(controller.markNeedsPaint)
..forward();
_fadeIn = _fadeInController.drive(IntTween(
begin: 0,
end: color.alpha,
));
// Controls the splash radius and its center. Starts upon confirm.
_radiusController = AnimationController(duration: _kUnconfirmedRippleDuration, vsync: controller.vsync)
..addListener(controller.markNeedsPaint)
..forward();
// Initial splash diameter is 60% of the target diameter, final
// diameter is 10dps larger than the target diameter.
_radius = _radiusController.drive(
Tween<double>(
begin: _targetRadius * 0.30,
end: _targetRadius + 5.0,
).chain(_easeCurveTween),
);
// Controls the splash radius and its center. Starts upon confirm however its
// Interval delays changes until the radius expansion has completed.
_fadeOutController = AnimationController(duration: _kFadeOutDuration, vsync: controller.vsync)
..addListener(controller.markNeedsPaint)
..addStatusListener(_handleAlphaStatusChanged);
_fadeOut = _fadeOutController.drive(
IntTween(
begin: color.alpha,
end: 0,
).chain(_fadeOutIntervalTween),
);
controller.addInkFeature(this);
}
final Offset _position;
final BorderRadius _borderRadius;
final double _targetRadius;
final RectCallback? _clipCallback;
final TextDirection _textDirection;
late Animation<double> _radius;
late AnimationController _radiusController;
late Animation<int> _fadeIn;
late AnimationController _fadeInController;
late Animation<int> _fadeOut;
late AnimationController _fadeOutController;
/// Used to specify this type of ink splash for an [InkWell], [InkResponse],
/// material [Theme], or [ButtonStyle].
static const InteractiveInkFeatureFactory splashFactory = _InkRippleFactory();
static final Animatable<double> _easeCurveTween = CurveTween(curve: Curves.ease);
static final Animatable<double> _fadeOutIntervalTween = CurveTween(curve: const Interval(_kFadeOutIntervalStart, 1.0));
@override
void confirm() {
_radiusController
..duration = _kRadiusDuration
..forward();
// This confirm may have been preceded by a cancel.
_fadeInController.forward();
_fadeOutController.animateTo(1.0, duration: _kFadeOutDuration);
}
@override
void cancel() {
_fadeInController.stop();
// Watch out: setting _fadeOutController's value to 1.0 will
// trigger a call to _handleAlphaStatusChanged() which will
// dispose _fadeOutController.
final double fadeOutValue = 1.0 - _fadeInController.value;
_fadeOutController.value = fadeOutValue;
if (fadeOutValue < 1.0) {
_fadeOutController.animateTo(1.0, duration: _kCancelDuration);
}
}
void _handleAlphaStatusChanged(AnimationStatus status) {
if (status == AnimationStatus.completed) {
dispose();
}
}
@override
void dispose() {
_radiusController.dispose();
_fadeInController.dispose();
_fadeOutController.dispose();
super.dispose();
}
@override
void paintFeature(Canvas canvas, Matrix4 transform) {
final int alpha = _fadeInController.isAnimating ? _fadeIn.value : _fadeOut.value;
final Paint paint = Paint()..color = color.withAlpha(alpha);
Rect? rect;
if (_clipCallback != null) {
rect = _clipCallback();
}
// Splash moves to the center of the reference box.
final Offset center = Offset.lerp(
_position,
rect != null ? rect.center : referenceBox.size.center(Offset.zero),
Curves.ease.transform(_radiusController.value),
)!;
paintInkCircle(
canvas: canvas,
transform: transform,
paint: paint,
center: center,
textDirection: _textDirection,
radius: _radius.value,
customBorder: customBorder,
borderRadius: _borderRadius,
clipCallback: _clipCallback,
);
}
}
| flutter/packages/flutter/lib/src/material/ink_ripple.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/ink_ripple.dart",
"repo_id": "flutter",
"token_count": 2905
} | 801 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'button_style.dart';
import 'button_style_button.dart';
import 'checkbox.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'constants.dart';
import 'icons.dart';
import 'ink_well.dart';
import 'material.dart';
import 'material_localizations.dart';
import 'material_state.dart';
import 'menu_bar_theme.dart';
import 'menu_button_theme.dart';
import 'menu_style.dart';
import 'menu_theme.dart';
import 'radio.dart';
import 'scrollbar.dart';
import 'text_button.dart';
import 'text_theme.dart';
import 'theme.dart';
import 'theme_data.dart';
// Examples can assume:
// bool _throwShotAway = false;
// late BuildContext context;
// enum SingingCharacter { lafayette }
// late SingingCharacter? _character;
// late StateSetter setState;
// Enable if you want verbose logging about menu changes.
const bool _kDebugMenus = false;
// The default size of the arrow in _MenuItemLabel that indicates that a menu
// has a submenu.
const double _kDefaultSubmenuIconSize = 24;
// The default spacing between the leading icon, label, trailing icon, and
// shortcut label in a _MenuItemLabel.
const double _kLabelItemDefaultSpacing = 12;
// The minimum spacing between the leading icon, label, trailing icon, and
// shortcut label in a _MenuItemLabel.
const double _kLabelItemMinSpacing = 4;
// Navigation shortcuts that we need to make sure are active when menus are
// open.
const Map<ShortcutActivator, Intent> _kMenuTraversalShortcuts = <ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.gameButtonA): ActivateIntent(),
SingleActivator(LogicalKeyboardKey.escape): DismissIntent(),
SingleActivator(LogicalKeyboardKey.tab): NextFocusIntent(),
SingleActivator(LogicalKeyboardKey.tab, shift: true): PreviousFocusIntent(),
SingleActivator(LogicalKeyboardKey.arrowDown): DirectionalFocusIntent(TraversalDirection.down),
SingleActivator(LogicalKeyboardKey.arrowUp): DirectionalFocusIntent(TraversalDirection.up),
SingleActivator(LogicalKeyboardKey.arrowLeft): DirectionalFocusIntent(TraversalDirection.left),
SingleActivator(LogicalKeyboardKey.arrowRight): DirectionalFocusIntent(TraversalDirection.right),
};
// The minimum vertical spacing on the outside of menus.
const double _kMenuVerticalMinPadding = 8;
// How close to the edge of the safe area the menu will be placed.
const double _kMenuViewPadding = 8;
// The minimum horizontal spacing on the outside of the top level menu.
const double _kTopLevelMenuHorizontalMinPadding = 4;
/// The type of builder function used by [MenuAnchor.builder] to build the
/// widget that the [MenuAnchor] surrounds.
///
/// The `context` is the context that the widget is being built in.
///
/// The `controller` is the [MenuController] that can be used to open and close
/// the menu with.
///
/// The `child` is an optional child supplied as the [MenuAnchor.child]
/// attribute. The child is intended to be incorporated in the result of the
/// function.
typedef MenuAnchorChildBuilder = Widget Function(
BuildContext context,
MenuController controller,
Widget? child,
);
/// A widget used to mark the "anchor" for a set of submenus, defining the
/// rectangle used to position the menu, which can be done either with an
/// explicit location, or with an alignment.
///
/// When creating a menu with [MenuBar] or a [SubmenuButton], a [MenuAnchor] is
/// not needed, since they provide their own internally.
///
/// The [MenuAnchor] is meant to be a slightly lower level interface than
/// [MenuBar], used in situations where a [MenuBar] isn't appropriate, or to
/// construct widgets or screen regions that have submenus.
///
/// {@tool dartpad}
/// This example shows how to use a [MenuAnchor] to wrap a button and open a
/// cascading menu from the button.
///
/// ** See code in examples/api/lib/material/menu_anchor/menu_anchor.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This example shows how to use a [MenuAnchor] to create a cascading context
/// menu in a region of the view, positioned where the user clicks the mouse
/// with Ctrl pressed. The [anchorTapClosesMenu] attribute is set to true so
/// that clicks on the [MenuAnchor] area will cause the menus to be closed.
///
/// ** See code in examples/api/lib/material/menu_anchor/menu_anchor.1.dart **
/// {@end-tool}
class MenuAnchor extends StatefulWidget {
/// Creates a const [MenuAnchor].
///
/// The [menuChildren] argument is required.
const MenuAnchor({
super.key,
this.controller,
this.childFocusNode,
this.style,
this.alignmentOffset = Offset.zero,
this.clipBehavior = Clip.hardEdge,
@Deprecated(
'Use consumeOutsideTap instead. '
'This feature was deprecated after v3.16.0-8.0.pre.',
)
this.anchorTapClosesMenu = false,
this.consumeOutsideTap = false,
this.onOpen,
this.onClose,
this.crossAxisUnconstrained = true,
required this.menuChildren,
this.builder,
this.child,
});
/// An optional controller that allows opening and closing of the menu from
/// other widgets.
final MenuController? controller;
/// The [childFocusNode] attribute is the optional [FocusNode] also associated
/// the [child] or [builder] widget that opens the menu.
///
/// The focus node should be attached to the widget that should receive focus
/// if keyboard focus traversal moves the focus off of the submenu with the
/// arrow keys.
///
/// If not supplied, then keyboard traversal from the menu back to the
/// controlling button when the menu is open is disabled.
final FocusNode? childFocusNode;
/// The [MenuStyle] that defines the visual attributes of the menu bar.
///
/// Colors and sizing of the menus is controllable via the [MenuStyle].
///
/// Defaults to the ambient [MenuThemeData.style].
final MenuStyle? style;
/// The offset of the menu relative to the alignment origin determined by
/// [MenuStyle.alignment] on the [style] attribute and the ambient
/// [Directionality].
///
/// Use this for adjustments of the menu placement.
///
/// Increasing [Offset.dy] values of [alignmentOffset] move the menu position
/// down.
///
/// If the [MenuStyle.alignment] from [style] is not an [AlignmentDirectional]
/// (e.g. [Alignment]), then increasing [Offset.dx] values of
/// [alignmentOffset] move the menu position to the right.
///
/// If the [MenuStyle.alignment] from [style] is an [AlignmentDirectional],
/// then in a [TextDirection.ltr] [Directionality], increasing [Offset.dx]
/// values of [alignmentOffset] move the menu position to the right. In a
/// [TextDirection.rtl] directionality, increasing [Offset.dx] values of
/// [alignmentOffset] move the menu position to the left.
///
/// Defaults to [Offset.zero].
final Offset? alignmentOffset;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.hardEdge].
final Clip clipBehavior;
/// Whether the menus will be closed if the anchor area is tapped.
///
/// For menus opened by buttons that toggle the menu, if the button is tapped
/// when the menu is open, the button should close the menu. But if
/// [anchorTapClosesMenu] is true, then the menu will close, and
/// (surprisingly) immediately re-open. This is because tapping on the button
/// closes the menu before the `onPressed` or `onTap` handler is called
/// because of it being considered to be "outside" the menu system, and then
/// the button (seeing that the menu is closed) immediately reopens the menu.
/// The result is that the user thinks that tapping on the button does
/// nothing. So, for button-initiated menus, this value is typically false so
/// that the menu anchor area is considered "inside" of the menu system and
/// doesn't cause it to close unless [MenuController.close] is called.
///
/// For menus that are positioned using [MenuController.open]'s `position`
/// parameter, it is often desirable that clicking on the anchor always closes
/// the menu since the anchor area isn't usually considered part of the menu
/// system by the user. In this case [anchorTapClosesMenu] should be true.
///
/// Defaults to false.
@Deprecated(
'Use consumeOutsideTap instead. '
'This feature was deprecated after v3.16.0-8.0.pre.',
)
final bool anchorTapClosesMenu;
/// Whether or not a tap event that closes the menu will be permitted to
/// continue on to the gesture arena.
///
/// If false, then tapping outside of a menu when the menu is open will both
/// close the menu, and allow the tap to participate in the gesture arena. If
/// true, then it will only close the menu, and the tap event will be
/// consumed.
///
/// Defaults to false.
final bool consumeOutsideTap;
/// A callback that is invoked when the menu is opened.
final VoidCallback? onOpen;
/// A callback that is invoked when the menu is closed.
final VoidCallback? onClose;
/// Determine if the menu panel can be wrapped by a [UnconstrainedBox] which allows
/// the panel to render at its "natural" size.
///
/// Defaults to true as it allows developers to render the menu panel at the
/// size it should be. When it is set to false, it can be useful when the menu should
/// be constrained in both main axis and cross axis, such as a [DropdownMenu].
final bool crossAxisUnconstrained;
/// A list of children containing the menu items that are the contents of the
/// menu surrounded by this [MenuAnchor].
///
/// {@macro flutter.material.MenuBar.shortcuts_note}
final List<Widget> menuChildren;
/// The widget that this [MenuAnchor] surrounds.
///
/// Typically this is a button used to open the menu by calling
/// [MenuController.open] on the `controller` passed to the builder.
///
/// If not supplied, then the [MenuAnchor] will be the size that its parent
/// allocates for it.
final MenuAnchorChildBuilder? builder;
/// The optional child to be passed to the [builder].
///
/// Supply this child if there is a portion of the widget tree built in
/// [builder] that doesn't depend on the `controller` or `context` supplied to
/// the [builder]. It will be more efficient, since Flutter doesn't then need
/// to rebuild this child when those change.
final Widget? child;
@override
State<MenuAnchor> createState() => _MenuAnchorState();
@override
List<DiagnosticsNode> debugDescribeChildren() {
return menuChildren.map<DiagnosticsNode>((Widget child) => child.toDiagnosticsNode()).toList();
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(FlagProperty('anchorTapClosesMenu', value: anchorTapClosesMenu, ifTrue: 'AUTO-CLOSE'));
properties.add(DiagnosticsProperty<FocusNode?>('focusNode', childFocusNode));
properties.add(DiagnosticsProperty<MenuStyle?>('style', style));
properties.add(EnumProperty<Clip>('clipBehavior', clipBehavior));
properties.add(DiagnosticsProperty<Offset?>('alignmentOffset', alignmentOffset));
}
}
class _MenuAnchorState extends State<MenuAnchor> {
// This is the global key that is used later to determine the bounding rect
// for the anchor's region that the CustomSingleChildLayout's delegate
// uses to determine where to place the menu on the screen and to avoid the
// view's edges.
final GlobalKey<_MenuAnchorState> _anchorKey = GlobalKey<_MenuAnchorState>(debugLabel: kReleaseMode ? null : 'MenuAnchor');
_MenuAnchorState? _parent;
late final FocusScopeNode _menuScopeNode;
MenuController? _internalMenuController;
final List<_MenuAnchorState> _anchorChildren = <_MenuAnchorState>[];
ScrollPosition? _scrollPosition;
Size? _viewSize;
final OverlayPortalController _overlayController = OverlayPortalController(debugLabel: kReleaseMode ? null : 'MenuAnchor controller');
Offset? _menuPosition;
Axis get _orientation => Axis.vertical;
bool get _isOpen => _overlayController.isShowing;
bool get _isRoot => _parent == null;
bool get _isTopLevel => _parent?._isRoot ?? false;
MenuController get _menuController => widget.controller ?? _internalMenuController!;
@override
void initState() {
super.initState();
_menuScopeNode = FocusScopeNode(debugLabel: kReleaseMode ? null : '${describeIdentity(this)} Sub Menu');
if (widget.controller == null) {
_internalMenuController = MenuController();
}
_menuController._attach(this);
}
@override
void dispose() {
assert(_debugMenuInfo('Disposing of $this'));
if (_isOpen) {
_close(inDispose: true);
_parent?._removeChild(this);
}
_anchorChildren.clear();
_menuController._detach(this);
_internalMenuController = null;
_menuScopeNode.dispose();
super.dispose();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final _MenuAnchorState? newParent = _MenuAnchorState._maybeOf(context);
if (newParent != _parent) {
_parent?._removeChild(this);
_parent = newParent;
_parent?._addChild(this);
}
_scrollPosition?.isScrollingNotifier.removeListener(_handleScroll);
_scrollPosition = Scrollable.maybeOf(context)?.position;
_scrollPosition?.isScrollingNotifier.addListener(_handleScroll);
final Size newSize = MediaQuery.sizeOf(context);
if (_viewSize != null && newSize != _viewSize) {
// Close the menus if the view changes size.
_root._close();
}
_viewSize = newSize;
}
@override
void didUpdateWidget(MenuAnchor oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.controller != widget.controller) {
oldWidget.controller?._detach(this);
if (widget.controller != null) {
_internalMenuController?._detach(this);
_internalMenuController = null;
widget.controller?._attach(this);
} else {
assert(_internalMenuController == null);
_internalMenuController = MenuController().._attach(this);
}
}
assert(_menuController._anchor == this);
}
@override
Widget build(BuildContext context) {
Widget child = OverlayPortal(
controller: _overlayController,
overlayChildBuilder: (BuildContext context) {
return _Submenu(
anchor: this,
menuStyle: widget.style,
alignmentOffset: widget.alignmentOffset ?? Offset.zero,
menuPosition: _menuPosition,
clipBehavior: widget.clipBehavior,
menuChildren: widget.menuChildren,
crossAxisUnconstrained: widget.crossAxisUnconstrained,
);
},
child: _buildContents(context),
);
if (!widget.anchorTapClosesMenu) {
child = TapRegion(
groupId: _root,
consumeOutsideTaps: _root._isOpen && widget.consumeOutsideTap,
onTapOutside: (PointerDownEvent event) {
assert(_debugMenuInfo('Tapped Outside ${widget.controller}'));
_closeChildren();
},
child: child,
);
}
return _MenuAnchorScope(
anchorKey: _anchorKey,
anchor: this,
isOpen: _isOpen,
child: child,
);
}
Widget _buildContents(BuildContext context) {
return Actions(
actions: <Type, Action<Intent>>{
DirectionalFocusIntent: _MenuDirectionalFocusAction(),
PreviousFocusIntent: _MenuPreviousFocusAction(),
NextFocusIntent: _MenuNextFocusAction(),
DismissIntent: DismissMenuAction(controller: _menuController),
},
child: Builder(
key: _anchorKey,
builder: (BuildContext context) {
return widget.builder?.call(context, _menuController, widget.child)
?? widget.child ?? const SizedBox();
},
),
);
}
// Returns the first focusable item in the submenu, where "first" is
// determined by the focus traversal policy.
FocusNode? get _firstItemFocusNode {
if (_menuScopeNode.context == null) {
return null;
}
final FocusTraversalPolicy policy =
FocusTraversalGroup.maybeOf(_menuScopeNode.context!) ?? ReadingOrderTraversalPolicy();
return policy.findFirstFocus(_menuScopeNode, ignoreCurrentFocus: true);
}
void _addChild(_MenuAnchorState child) {
assert(_isRoot || _debugMenuInfo('Added root child: $child'));
assert(!_anchorChildren.contains(child));
_anchorChildren.add(child);
assert(_debugMenuInfo('Added:\n${child.widget.toStringDeep()}'));
assert(_debugMenuInfo('Tree:\n${widget.toStringDeep()}'));
}
void _removeChild(_MenuAnchorState child) {
assert(_isRoot || _debugMenuInfo('Removed root child: $child'));
assert(_anchorChildren.contains(child));
assert(_debugMenuInfo('Removing:\n${child.widget.toStringDeep()}'));
_anchorChildren.remove(child);
assert(_debugMenuInfo('Tree:\n${widget.toStringDeep()}'));
}
List<_MenuAnchorState> _getFocusableChildren() {
if (_parent == null) {
return <_MenuAnchorState>[];
}
return _parent!._anchorChildren.where((_MenuAnchorState menu) {
return menu.widget.childFocusNode?.canRequestFocus ?? false;
},).toList();
}
_MenuAnchorState? get _nextFocusableSibling {
final List<_MenuAnchorState> focusable = _getFocusableChildren();
if (focusable.isEmpty) {
return null;
}
return focusable[(focusable.indexOf(this) + 1) % focusable.length];
}
_MenuAnchorState? get _previousFocusableSibling {
final List<_MenuAnchorState> focusable = _getFocusableChildren();
if (focusable.isEmpty) {
return null;
}
return focusable[(focusable.indexOf(this) - 1 + focusable.length) % focusable.length];
}
_MenuAnchorState get _root {
_MenuAnchorState anchor = this;
while (anchor._parent != null) {
anchor = anchor._parent!;
}
return anchor;
}
_MenuAnchorState get _topLevel {
_MenuAnchorState handle = this;
while (handle._parent != null && !handle._parent!._isTopLevel) {
handle = handle._parent!;
}
return handle;
}
void _childChangedOpenState() {
_parent?._childChangedOpenState();
assert(mounted);
if (SchedulerBinding.instance.schedulerPhase != SchedulerPhase.persistentCallbacks) {
setState(() {
// Mark dirty now, but only if not in a build.
});
} else {
SchedulerBinding.instance.addPostFrameCallback((Duration _) {
setState(() {
// Mark dirty after this frame, but only if in a build.
});
});
}
}
void _focusButton() {
if (widget.childFocusNode == null) {
return;
}
assert(_debugMenuInfo('Requesting focus for ${widget.childFocusNode}'));
widget.childFocusNode!.requestFocus();
}
void _handleScroll() {
// If an ancestor scrolls, and we're a root anchor, then close the menus.
// Don't just close it on *any* scroll, since we want to be able to scroll
// menus themselves if they're too big for the view.
if (_isRoot) {
_close();
}
}
KeyEventResult _checkForEscape(KeyEvent event) {
if (event is KeyDownEvent && event.logicalKey == LogicalKeyboardKey.escape) {
_close();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
/// Open the menu, optionally at a position relative to the [MenuAnchor].
///
/// Call this when the menu should be shown to the user.
///
/// The optional `position` argument will specify the location of the menu in
/// the local coordinates of the [MenuAnchor], ignoring any
/// [MenuStyle.alignment] and/or [MenuAnchor.alignmentOffset] that were
/// specified.
void _open({Offset? position}) {
assert(_menuController._anchor == this);
if (_isOpen && position == null) {
assert(_debugMenuInfo("Not opening $this because it's already open"));
return;
}
if (_isOpen && position != null) {
// The menu is already open, but we need to move to another location, so
// close it first.
_close();
}
assert(_debugMenuInfo(
'Opening $this at ${position ?? Offset.zero} with alignment offset ${widget.alignmentOffset ?? Offset.zero}'));
_parent?._closeChildren(); // Close all siblings.
assert(!_overlayController.isShowing);
_parent?._childChangedOpenState();
_menuPosition = position;
_overlayController.show();
widget.onOpen?.call();
}
/// Close the menu.
///
/// Call this when the menu should be closed. Has no effect if the menu is
/// already closed.
void _close({bool inDispose = false}) {
assert(_debugMenuInfo('Closing $this'));
if (!_isOpen) {
return;
}
if (_isRoot) {
FocusManager.instance.removeEarlyKeyEventHandler(_checkForEscape);
}
_closeChildren(inDispose: inDispose);
// Don't hide if we're in the middle of a build.
if (SchedulerBinding.instance.schedulerPhase != SchedulerPhase.persistentCallbacks) {
_overlayController.hide();
} else if (!inDispose) {
SchedulerBinding.instance.addPostFrameCallback((_) {
_overlayController.hide();
}, debugLabel: 'MenuAnchor.hide');
}
if (!inDispose) {
// Notify that _childIsOpen changed state, but only if not
// currently disposing.
_parent?._childChangedOpenState();
widget.onClose?.call();
if (mounted && SchedulerBinding.instance.schedulerPhase != SchedulerPhase.persistentCallbacks) {
setState(() {
// Mark dirty, but only if mounted and not in a build.
});
}
}
}
void _closeChildren({bool inDispose = false}) {
assert(_debugMenuInfo('Closing children of $this${inDispose ? ' (dispose)' : ''}'));
for (final _MenuAnchorState child in List<_MenuAnchorState>.from(_anchorChildren)) {
child._close(inDispose: inDispose);
}
}
// Returns the active anchor in the given context, if any, and creates a
// dependency relationship that will rebuild the context when the node
// changes.
static _MenuAnchorState? _maybeOf(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<_MenuAnchorScope>()?.anchor;
}
@override
String toString({DiagnosticLevel minLevel = DiagnosticLevel.debug}) {
return describeIdentity(this);
}
}
/// A controller to manage a menu created by a [MenuBar] or [MenuAnchor].
///
/// A [MenuController] is used to control and interrogate a menu after it has
/// been created, with methods such as [open] and [close], and state accessors
/// like [isOpen].
///
/// See also:
///
/// * [MenuAnchor], a widget that defines a region that has submenu.
/// * [MenuBar], a widget that creates a menu bar, that can take an optional
/// [MenuController].
/// * [SubmenuButton], a widget that has a button that manages a submenu.
class MenuController {
/// The anchor that this controller controls.
///
/// This is set automatically when a [MenuController] is given to the anchor
/// it controls.
_MenuAnchorState? _anchor;
/// Whether or not the associated menu is currently open.
bool get isOpen {
assert(_anchor != null);
return _anchor!._isOpen;
}
/// Close the menu that this menu controller is associated with.
///
/// Associating with a menu is done by passing a [MenuController] to a
/// [MenuAnchor]. A [MenuController] is also be received by the
/// [MenuAnchor.builder] when invoked.
///
/// If the menu's anchor point (either a [MenuBar] or a [MenuAnchor]) is
/// scrolled by an ancestor, or the view changes size, then any open menu will
/// automatically close.
void close() {
assert(_anchor != null);
_anchor!._close();
}
/// Opens the menu that this menu controller is associated with.
///
/// If `position` is given, then the menu will open at the position given, in
/// the coordinate space of the [MenuAnchor] this controller is attached to.
///
/// If given, the `position` will override the [MenuAnchor.alignmentOffset]
/// given to the [MenuAnchor].
///
/// If the menu's anchor point (either a [MenuBar] or a [MenuAnchor]) is
/// scrolled by an ancestor, or the view changes size, then any open menu will
/// automatically close.
void open({Offset? position}) {
assert(_anchor != null);
_anchor!._open(position: position);
}
// ignore: use_setters_to_change_properties
void _attach(_MenuAnchorState anchor) {
_anchor = anchor;
}
void _detach(_MenuAnchorState anchor) {
if (_anchor == anchor) {
_anchor = null;
}
}
}
/// A menu bar that manages cascading child menus.
///
/// This is a Material Design menu bar that typically resides above the main
/// body of an application (but can go anywhere) that defines a menu system for
/// invoking callbacks in response to user selection of a menu item.
///
/// The menus can be opened with a click or tap. Once a menu is opened, it can
/// be navigated by using the arrow and tab keys or via mouse hover. Selecting a
/// menu item can be done by pressing enter, or by clicking or tapping on the
/// menu item. Clicking or tapping on any part of the user interface that isn't
/// part of the menu system controlled by the same controller will cause all of
/// the menus controlled by that controller to close, as will pressing the
/// escape key.
///
/// When a menu item with a submenu is clicked on, it toggles the visibility of
/// the submenu. When the menu item is hovered over, the submenu will open, and
/// hovering over other items will close the previous menu and open the newly
/// hovered one. When those open/close transitions occur,
/// [SubmenuButton.onOpen], and [SubmenuButton.onClose] are called on the
/// corresponding [SubmenuButton] child of the menu bar.
///
/// {@template flutter.material.MenuBar.shortcuts_note}
/// Menus using [MenuItemButton] can have a [SingleActivator] or
/// [CharacterActivator] assigned to them as their [MenuItemButton.shortcut],
/// which will display an appropriate shortcut hint. Even though the shortcut
/// labels are displayed in the menu, shortcuts are not automatically handled.
/// They must be available in whatever context they are appropriate, and handled
/// via another mechanism.
///
/// If shortcuts should be generally enabled, but are not easily defined in a
/// context surrounding the menu bar, consider registering them with a
/// [ShortcutRegistry] (one is already included in the [WidgetsApp], and thus
/// also [MaterialApp] and [CupertinoApp]), as shown in the example below. To be
/// sure that selecting a menu item and triggering the shortcut do the same
/// thing, it is recommended that they call the same callback.
///
/// {@tool dartpad} This example shows a [MenuBar] that contains a single top
/// level menu, containing three items: "About", a checkbox menu item for
/// showing a message, and "Quit". The items are identified with an enum value,
/// and the shortcuts are registered globally with the [ShortcutRegistry].
///
/// ** See code in examples/api/lib/material/menu_anchor/menu_bar.0.dart **
/// {@end-tool}
/// {@endtemplate}
///
/// {@macro flutter.material.MenuAcceleratorLabel.accelerator_sample}
///
/// See also:
///
/// * [MenuAnchor], a widget that creates a region with a submenu and shows it
/// when requested.
/// * [SubmenuButton], a menu item which manages a submenu.
/// * [MenuItemButton], a leaf menu item which displays the label, an optional
/// shortcut label, and optional leading and trailing icons.
/// * [PlatformMenuBar], which creates a menu bar that is rendered by the host
/// platform instead of by Flutter (on macOS, for example).
/// * [ShortcutRegistry], a registry of shortcuts that apply for the entire
/// application.
/// * [VoidCallbackIntent], to define intents that will call a [VoidCallback] and
/// work with the [Actions] and [Shortcuts] system.
/// * [CallbackShortcuts], to define shortcuts that call a callback without
/// involving [Actions].
class MenuBar extends StatelessWidget {
/// Creates a const [MenuBar].
///
/// The [children] argument is required.
const MenuBar({
super.key,
this.style,
this.clipBehavior = Clip.none,
this.controller,
required this.children,
});
/// The [MenuStyle] that defines the visual attributes of the menu bar.
///
/// Colors and sizing of the menus is controllable via the [MenuStyle].
///
/// Defaults to the ambient [MenuThemeData.style].
final MenuStyle? style;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.none].
final Clip clipBehavior;
/// The [MenuController] to use for this menu bar.
final MenuController? controller;
/// The list of menu items that are the top level children of the [MenuBar].
///
/// A Widget in Flutter is immutable, so directly modifying the [children]
/// with [List] APIs such as `someMenuBarWidget.menus.add(...)` will result in
/// incorrect behaviors. Whenever the menus list is modified, a new list
/// object must be provided.
///
/// {@macro flutter.material.MenuBar.shortcuts_note}
final List<Widget> children;
@override
Widget build(BuildContext context) {
assert(debugCheckHasOverlay(context));
return _MenuBarAnchor(
controller: controller,
clipBehavior: clipBehavior,
style: style,
menuChildren: children,
);
}
@override
List<DiagnosticsNode> debugDescribeChildren() {
return <DiagnosticsNode>[
...children.map<DiagnosticsNode>(
(Widget item) => item.toDiagnosticsNode(),
),
];
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<MenuStyle?>('style', style, defaultValue: null));
properties.add(DiagnosticsProperty<Clip>('clipBehavior', clipBehavior, defaultValue: null));
}
}
/// A button for use in a [MenuBar], in a menu created with [MenuAnchor], or on
/// its own, that can be activated by click or keyboard navigation.
///
/// This widget represents a leaf entry in a menu hierarchy that is typically
/// part of a [MenuBar], but may be used independently, or as part of a menu
/// created with a [MenuAnchor].
///
/// {@macro flutter.material.MenuBar.shortcuts_note}
///
/// See also:
///
/// * [MenuBar], a class that creates a top level menu bar in a Material Design
/// style.
/// * [MenuAnchor], a widget that creates a region with a submenu and shows it
/// when requested.
/// * [SubmenuButton], a menu item similar to this one which manages a submenu.
/// * [PlatformMenuBar], which creates a menu bar that is rendered by the host
/// platform instead of by Flutter (on macOS, for example).
/// * [ShortcutRegistry], a registry of shortcuts that apply for the entire
/// application.
/// * [VoidCallbackIntent], to define intents that will call a [VoidCallback] and
/// work with the [Actions] and [Shortcuts] system.
/// * [CallbackShortcuts] to define shortcuts that call a callback without
/// involving [Actions].
class MenuItemButton extends StatefulWidget {
/// Creates a const [MenuItemButton].
///
/// The [child] attribute is required.
const MenuItemButton({
super.key,
this.onPressed,
this.onHover,
this.requestFocusOnHover = true,
this.onFocusChange,
this.focusNode,
this.shortcut,
this.style,
this.statesController,
this.clipBehavior = Clip.none,
this.leadingIcon,
this.trailingIcon,
this.closeOnActivate = true,
required this.child,
});
/// Called when the button is tapped or otherwise activated.
///
/// If this callback is null, then the button will be disabled.
///
/// See also:
///
/// * [enabled], which is true if the button is enabled.
final VoidCallback? onPressed;
/// Called when a pointer enters or exits the button response area.
///
/// The value passed to the callback is true if a pointer has entered button
/// area and false if a pointer has exited.
final ValueChanged<bool>? onHover;
/// Determine if hovering can request focus.
///
/// Defaults to true.
final bool requestFocusOnHover;
/// Handler called when the focus changes.
///
/// Called with true if this widget's node gains focus, and false if it loses
/// focus.
final ValueChanged<bool>? onFocusChange;
/// {@macro flutter.widgets.Focus.focusNode}
final FocusNode? focusNode;
/// The optional shortcut that selects this [MenuItemButton].
///
/// {@macro flutter.material.MenuBar.shortcuts_note}
final MenuSerializableShortcut? shortcut;
/// Customizes this button's appearance.
///
/// Non-null properties of this style override the corresponding properties in
/// [themeStyleOf] and [defaultStyleOf]. [MaterialStateProperty]s that resolve
/// to non-null values will similarly override the corresponding
/// [MaterialStateProperty]s in [themeStyleOf] and [defaultStyleOf].
///
/// Null by default.
final ButtonStyle? style;
/// {@macro flutter.material.inkwell.statesController}
final MaterialStatesController? statesController;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.none].
final Clip clipBehavior;
/// An optional icon to display before the [child] label.
final Widget? leadingIcon;
/// An optional icon to display after the [child] label.
final Widget? trailingIcon;
/// {@template flutter.material.menu_anchor.closeOnActivate}
/// Determines if the menu will be closed when a [MenuItemButton]
/// is pressed.
///
/// Defaults to true.
/// {@endtemplate}
final bool closeOnActivate;
/// The widget displayed in the center of this button.
///
/// Typically this is the button's label, using a [Text] widget.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
/// Whether the button is enabled or disabled.
///
/// To enable a button, set its [onPressed] property to a non-null value.
bool get enabled => onPressed != null;
@override
State<MenuItemButton> createState() => _MenuItemButtonState();
/// Defines the button's default appearance.
///
/// {@macro flutter.material.text_button.default_style_of}
///
/// {@macro flutter.material.text_button.material3_defaults}
ButtonStyle defaultStyleOf(BuildContext context) {
return _MenuButtonDefaultsM3(context);
}
/// Returns the [MenuButtonThemeData.style] of the closest
/// [MenuButtonTheme] ancestor.
ButtonStyle? themeStyleOf(BuildContext context) {
return MenuButtonTheme.of(context).style;
}
/// A static convenience method that constructs a [MenuItemButton]'s
/// [ButtonStyle] given simple values.
///
/// The [foregroundColor] color is used to create a [MaterialStateProperty]
/// [ButtonStyle.foregroundColor] value. Specify a value for [foregroundColor]
/// to specify the color of the button's icons. Use [backgroundColor] for the
/// button's background fill color. Use [disabledForegroundColor] and
/// [disabledBackgroundColor] to specify the button's disabled icon and fill
/// color.
///
/// All of the other parameters are either used directly or used to create a
/// [MaterialStateProperty] with a single value for all states.
///
/// All parameters default to null, by default this method returns a
/// [ButtonStyle] that doesn't override anything.
///
/// For example, to override the default foreground color for a
/// [MenuItemButton], as well as its overlay color, with all of the standard
/// opacity adjustments for the pressed, focused, and hovered states, one
/// could write:
///
/// ```dart
/// MenuItemButton(
/// leadingIcon: const Icon(Icons.pets),
/// style: MenuItemButton.styleFrom(foregroundColor: Colors.green),
/// onPressed: () {
/// // ...
/// },
/// child: const Text('Button Label'),
/// ),
/// ```
static ButtonStyle styleFrom({
Color? foregroundColor,
Color? backgroundColor,
Color? disabledForegroundColor,
Color? disabledBackgroundColor,
Color? shadowColor,
Color? surfaceTintColor,
Color? iconColor,
TextStyle? textStyle,
double? elevation,
EdgeInsetsGeometry? padding,
Size? minimumSize,
Size? fixedSize,
Size? maximumSize,
MouseCursor? enabledMouseCursor,
MouseCursor? disabledMouseCursor,
BorderSide? side,
OutlinedBorder? shape,
VisualDensity? visualDensity,
MaterialTapTargetSize? tapTargetSize,
Duration? animationDuration,
bool? enableFeedback,
AlignmentGeometry? alignment,
InteractiveInkFeatureFactory? splashFactory,
}) {
return TextButton.styleFrom(
foregroundColor: foregroundColor,
backgroundColor: backgroundColor,
disabledBackgroundColor: disabledBackgroundColor,
disabledForegroundColor: disabledForegroundColor,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
iconColor: iconColor,
textStyle: textStyle,
elevation: elevation,
padding: padding,
minimumSize: minimumSize,
fixedSize: fixedSize,
maximumSize: maximumSize,
enabledMouseCursor: enabledMouseCursor,
disabledMouseCursor: disabledMouseCursor,
side: side,
shape: shape,
visualDensity: visualDensity,
tapTargetSize: tapTargetSize,
animationDuration: animationDuration,
enableFeedback: enableFeedback,
alignment: alignment,
splashFactory: splashFactory,
);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(FlagProperty('enabled', value: onPressed != null, ifFalse: 'DISABLED'));
properties.add(DiagnosticsProperty<ButtonStyle?>('style', style, defaultValue: null));
properties.add(DiagnosticsProperty<MenuSerializableShortcut?>('shortcut', shortcut, defaultValue: null));
properties.add(DiagnosticsProperty<FocusNode?>('focusNode', focusNode, defaultValue: null));
properties.add(EnumProperty<Clip>('clipBehavior', clipBehavior, defaultValue: Clip.none));
properties.add(DiagnosticsProperty<MaterialStatesController?>('statesController', statesController, defaultValue: null));
}
}
class _MenuItemButtonState extends State<MenuItemButton> {
// If a focus node isn't given to the widget, then we have to manage our own.
FocusNode? _internalFocusNode;
FocusNode get _focusNode => widget.focusNode ?? _internalFocusNode!;
@override
void initState() {
super.initState();
_createInternalFocusNodeIfNeeded();
_focusNode.addListener(_handleFocusChange);
}
@override
void dispose() {
_focusNode.removeListener(_handleFocusChange);
_internalFocusNode?.dispose();
_internalFocusNode = null;
super.dispose();
}
@override
void didUpdateWidget(MenuItemButton oldWidget) {
if (widget.focusNode != oldWidget.focusNode) {
(oldWidget.focusNode ?? _internalFocusNode)?.removeListener(_handleFocusChange);
if (widget.focusNode != null) {
_internalFocusNode?.dispose();
_internalFocusNode = null;
}
_createInternalFocusNodeIfNeeded();
_focusNode.addListener(_handleFocusChange);
}
super.didUpdateWidget(oldWidget);
}
@override
Widget build(BuildContext context) {
// Since we don't want to use the theme style or default style from the
// TextButton, we merge the styles, merging them in the right order when
// each type of style exists. Each "*StyleOf" function is only called once.
ButtonStyle mergedStyle = widget.themeStyleOf(context)?.merge(widget.defaultStyleOf(context))
?? widget.defaultStyleOf(context);
if (widget.style != null) {
mergedStyle = widget.style!.merge(mergedStyle);
}
Widget child = TextButton(
onPressed: widget.enabled ? _handleSelect : null,
onHover: widget.enabled ? _handleHover : null,
onFocusChange: widget.enabled ? widget.onFocusChange : null,
focusNode: _focusNode,
style: mergedStyle,
statesController: widget.statesController,
clipBehavior: widget.clipBehavior,
isSemanticButton: null,
child: _MenuItemLabel(
leadingIcon: widget.leadingIcon,
shortcut: widget.shortcut,
trailingIcon: widget.trailingIcon,
hasSubmenu: false,
child: widget.child!,
),
);
if (_platformSupportsAccelerators && widget.enabled) {
child = MenuAcceleratorCallbackBinding(
onInvoke: _handleSelect,
child: child,
);
}
return MergeSemantics(child: child);
}
void _handleFocusChange() {
if (!_focusNode.hasPrimaryFocus) {
// Close any child menus of this button's menu.
_MenuAnchorState._maybeOf(context)?._closeChildren();
}
}
void _handleHover(bool hovering) {
widget.onHover?.call(hovering);
if (hovering && widget.requestFocusOnHover) {
assert(_debugMenuInfo('Requesting focus for $_focusNode from hover'));
_focusNode.requestFocus();
}
}
void _handleSelect() {
assert(_debugMenuInfo('Selected ${widget.child} menu'));
if (widget.closeOnActivate) {
_MenuAnchorState._maybeOf(context)?._root._close();
}
// Delay the call to onPressed until post-frame so that the focus is
// restored to what it was before the menu was opened before the action is
// executed.
SchedulerBinding.instance.addPostFrameCallback((Duration _) {
FocusManager.instance.applyFocusChangesIfNeeded();
widget.onPressed?.call();
}, debugLabel: 'MenuAnchor.onPressed');
}
void _createInternalFocusNodeIfNeeded() {
if (widget.focusNode == null) {
_internalFocusNode = FocusNode();
assert(() {
if (_internalFocusNode != null) {
_internalFocusNode!.debugLabel = '$MenuItemButton(${widget.child})';
}
return true;
}());
}
}
}
/// A menu item that combines a [Checkbox] widget with a [MenuItemButton].
///
/// To style the checkbox separately from the button, add a [CheckboxTheme]
/// ancestor.
///
/// {@tool dartpad}
/// This example shows a menu with a checkbox that shows a message in the body
/// of the app if checked.
///
/// ** See code in examples/api/lib/material/menu_anchor/checkbox_menu_button.0.dart **
/// {@end-tool}
///
/// See also:
///
/// - [MenuBar], a widget that creates a menu bar of cascading menu items.
/// - [MenuAnchor], a widget that defines a region which can host a cascading
/// menu.
class CheckboxMenuButton extends StatelessWidget {
/// Creates a const [CheckboxMenuButton].
///
/// The [child], [value], and [onChanged] attributes are required.
const CheckboxMenuButton({
super.key,
required this.value,
this.tristate = false,
this.isError = false,
required this.onChanged,
this.onHover,
this.onFocusChange,
this.focusNode,
this.shortcut,
this.style,
this.statesController,
this.clipBehavior = Clip.none,
this.trailingIcon,
this.closeOnActivate = true,
required this.child,
});
/// Whether this checkbox is checked.
///
/// When [tristate] is true, a value of null corresponds to the mixed state.
/// When [tristate] is false, this value must not be null.
final bool? value;
/// If true, then the checkbox's [value] can be true, false, or null.
///
/// [CheckboxMenuButton] displays a dash when its value is null.
///
/// When a tri-state checkbox ([tristate] is true) is tapped, its [onChanged]
/// callback will be applied to true if the current value is false, to null if
/// value is true, and to false if value is null (i.e. it cycles through false
/// => true => null => false when tapped).
///
/// If tristate is false (the default), [value] must not be null.
final bool tristate;
/// True if this checkbox wants to show an error state.
///
/// The checkbox will have different default container color and check color when
/// this is true. This is only used when [ThemeData.useMaterial3] is set to true.
///
/// Defaults to false.
final bool isError;
/// Called when the value of the checkbox should change.
///
/// The checkbox passes the new value to the callback but does not actually
/// change state until the parent widget rebuilds the checkbox with the new
/// value.
///
/// If this callback is null, the menu item will be displayed as disabled
/// and will not respond to input gestures.
///
/// When the checkbox is tapped, if [tristate] is false (the default) then the
/// [onChanged] callback will be applied to `!value`. If [tristate] is true
/// this callback cycle from false to true to null and then back to false
/// again.
///
/// The callback provided to [onChanged] should update the state of the parent
/// [StatefulWidget] using the [State.setState] method, so that the parent
/// gets rebuilt; for example:
///
/// ```dart
/// CheckboxMenuButton(
/// value: _throwShotAway,
/// child: const Text('THROW'),
/// onChanged: (bool? newValue) {
/// setState(() {
/// _throwShotAway = newValue!;
/// });
/// },
/// )
/// ```
final ValueChanged<bool?>? onChanged;
/// Called when a pointer enters or exits the button response area.
///
/// The value passed to the callback is true if a pointer has entered button
/// area and false if a pointer has exited.
final ValueChanged<bool>? onHover;
/// Handler called when the focus changes.
///
/// Called with true if this widget's node gains focus, and false if it loses
/// focus.
final ValueChanged<bool>? onFocusChange;
/// {@macro flutter.widgets.Focus.focusNode}
final FocusNode? focusNode;
/// The optional shortcut that selects this [MenuItemButton].
///
/// {@macro flutter.material.MenuBar.shortcuts_note}
final MenuSerializableShortcut? shortcut;
/// Customizes this button's appearance.
///
/// Non-null properties of this style override the corresponding properties in
/// [MenuItemButton.themeStyleOf] and [MenuItemButton.defaultStyleOf].
/// [MaterialStateProperty]s that resolve to non-null values will similarly
/// override the corresponding [MaterialStateProperty]s in
/// [MenuItemButton.themeStyleOf] and [MenuItemButton.defaultStyleOf].
///
/// Null by default.
final ButtonStyle? style;
/// {@macro flutter.material.inkwell.statesController}
final MaterialStatesController? statesController;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.none].
final Clip clipBehavior;
/// An optional icon to display after the [child] label.
final Widget? trailingIcon;
/// {@macro flutter.material.menu_anchor.closeOnActivate}
final bool closeOnActivate;
/// The widget displayed in the center of this button.
///
/// Typically this is the button's label, using a [Text] widget.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
/// Whether the button is enabled or disabled.
///
/// To enable a button, set its [onChanged] property to a non-null value.
bool get enabled => onChanged != null;
@override
Widget build(BuildContext context) {
return MenuItemButton(
key: key,
onPressed: onChanged == null ? null : () {
switch (value) {
case false:
onChanged!.call(true);
case true:
onChanged!.call(tristate ? null : false);
case null:
onChanged!.call(false);
}
},
onHover: onHover,
onFocusChange: onFocusChange,
focusNode: focusNode,
style: style,
shortcut: shortcut,
statesController: statesController,
leadingIcon: ExcludeFocus(
child: IgnorePointer(
child: ConstrainedBox(
constraints: const BoxConstraints(
maxHeight: Checkbox.width,
maxWidth: Checkbox.width,
),
child: Checkbox(
tristate: tristate,
value: value,
onChanged: onChanged,
isError: isError,
),
),
),
),
clipBehavior: clipBehavior,
trailingIcon: trailingIcon,
closeOnActivate: closeOnActivate,
child: child,
);
}
}
/// A menu item that combines a [Radio] widget with a [MenuItemButton].
///
/// To style the radio button separately from the overall button, add a
/// [RadioTheme] ancestor.
///
/// {@tool dartpad}
/// This example shows a menu with three radio buttons with shortcuts that
/// changes the background color of the body when the buttons are selected.
///
/// ** See code in examples/api/lib/material/menu_anchor/radio_menu_button.0.dart **
/// {@end-tool}
///
/// See also:
///
/// - [MenuBar], a widget that creates a menu bar of cascading menu items.
/// - [MenuAnchor], a widget that defines a region which can host a cascading
/// menu.
class RadioMenuButton<T> extends StatelessWidget {
/// Creates a const [RadioMenuButton].
///
/// The [child] attribute is required.
const RadioMenuButton({
super.key,
required this.value,
required this.groupValue,
required this.onChanged,
this.toggleable = false,
this.onHover,
this.onFocusChange,
this.focusNode,
this.shortcut,
this.style,
this.statesController,
this.clipBehavior = Clip.none,
this.trailingIcon,
this.closeOnActivate = true,
required this.child,
});
/// The value represented by this radio button.
///
/// This radio button is considered selected if its [value] matches the
/// [groupValue].
final T value;
/// The currently selected value for a group of radio buttons.
///
/// This radio button is considered selected if its [value] matches the
/// [groupValue].
final T? groupValue;
/// Set to true if this radio button is allowed to be returned to an
/// indeterminate state by selecting it again when selected.
///
/// To indicate returning to an indeterminate state, [onChanged] will be
/// called with null.
///
/// If true, [onChanged] can be called with [value] when selected while
/// [groupValue] != [value], or with null when selected again while
/// [groupValue] == [value].
///
/// If false, [onChanged] will be called with [value] when it is selected
/// while [groupValue] != [value], and only by selecting another radio button
/// in the group (i.e. changing the value of [groupValue]) can this radio
/// button be unselected.
///
/// The default is false.
final bool toggleable;
/// Called when the user selects this radio button.
///
/// The radio button passes [value] as a parameter to this callback. The radio
/// button does not actually change state until the parent widget rebuilds the
/// radio button with the new [groupValue].
///
/// If null, the radio button will be displayed as disabled.
///
/// The provided callback will not be invoked if this radio button is already
/// selected.
///
/// The callback provided to [onChanged] should update the state of the parent
/// [StatefulWidget] using the [State.setState] method, so that the parent
/// gets rebuilt; for example:
///
/// ```dart
/// RadioMenuButton<SingingCharacter>(
/// value: SingingCharacter.lafayette,
/// groupValue: _character,
/// onChanged: (SingingCharacter? newValue) {
/// setState(() {
/// _character = newValue;
/// });
/// },
/// child: const Text('Lafayette'),
/// )
/// ```
final ValueChanged<T?>? onChanged;
/// Called when a pointer enters or exits the button response area.
///
/// The value passed to the callback is true if a pointer has entered button
/// area and false if a pointer has exited.
final ValueChanged<bool>? onHover;
/// Handler called when the focus changes.
///
/// Called with true if this widget's node gains focus, and false if it loses
/// focus.
final ValueChanged<bool>? onFocusChange;
/// {@macro flutter.widgets.Focus.focusNode}
final FocusNode? focusNode;
/// The optional shortcut that selects this [MenuItemButton].
///
/// {@macro flutter.material.MenuBar.shortcuts_note}
final MenuSerializableShortcut? shortcut;
/// Customizes this button's appearance.
///
/// Non-null properties of this style override the corresponding properties in
/// [MenuItemButton.themeStyleOf] and [MenuItemButton.defaultStyleOf].
/// [MaterialStateProperty]s that resolve to non-null values will similarly
/// override the corresponding [MaterialStateProperty]s in
/// [MenuItemButton.themeStyleOf] and [MenuItemButton.defaultStyleOf].
///
/// Null by default.
final ButtonStyle? style;
/// {@macro flutter.material.inkwell.statesController}
final MaterialStatesController? statesController;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.none].
final Clip clipBehavior;
/// An optional icon to display after the [child] label.
final Widget? trailingIcon;
/// {@macro flutter.material.menu_anchor.closeOnActivate}
final bool closeOnActivate;
/// The widget displayed in the center of this button.
///
/// Typically this is the button's label, using a [Text] widget.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
/// Whether the button is enabled or disabled.
///
/// To enable a button, set its [onChanged] property to a non-null value.
bool get enabled => onChanged != null;
@override
Widget build(BuildContext context) {
return MenuItemButton(
key: key,
onPressed: onChanged == null ? null : () {
if (toggleable && groupValue == value) {
onChanged!.call(null);
return;
}
onChanged!.call(value);
},
onHover: onHover,
onFocusChange: onFocusChange,
focusNode: focusNode,
style: style,
shortcut: shortcut,
statesController: statesController,
leadingIcon: ExcludeFocus(
child: IgnorePointer(
child: ConstrainedBox(
constraints: const BoxConstraints(
maxHeight: Checkbox.width,
maxWidth: Checkbox.width,
),
child: Radio<T>(
value: value,
groupValue: groupValue,
onChanged: onChanged,
toggleable: toggleable,
),
),
),
),
clipBehavior: clipBehavior,
trailingIcon: trailingIcon,
closeOnActivate: closeOnActivate,
child: child,
);
}
}
/// A menu button that displays a cascading menu.
///
/// It can be used as part of a [MenuBar], or as a standalone widget.
///
/// This widget represents a menu item that has a submenu. Like the leaf
/// [MenuItemButton], it shows a label with an optional leading or trailing
/// icon, but additionally shows an arrow icon showing that it has a submenu.
///
/// By default the submenu will appear to the side of the controlling button.
/// The alignment and offset of the submenu can be controlled by setting
/// [MenuStyle.alignment] on the [style] and the [alignmentOffset] argument,
/// respectively.
///
/// When activated (by being clicked, through keyboard navigation, or via
/// hovering with a mouse), it will open a submenu containing the
/// [menuChildren].
///
/// If [menuChildren] is empty, then this menu item will appear disabled.
///
/// See also:
///
/// * [MenuItemButton], a widget that represents a leaf menu item that does not
/// host a submenu.
/// * [MenuBar], a widget that renders menu items in a row in a Material Design
/// style.
/// * [MenuAnchor], a widget that creates a region with a submenu and shows it
/// when requested.
/// * [PlatformMenuBar], a widget that renders similar menu bar items from a
/// [PlatformMenuItem] using platform-native APIs instead of Flutter.
class SubmenuButton extends StatefulWidget {
/// Creates a const [SubmenuButton].
///
/// The [child] and [menuChildren] attributes are required.
const SubmenuButton({
super.key,
this.onHover,
this.onFocusChange,
this.onOpen,
this.onClose,
this.controller,
this.style,
this.menuStyle,
this.alignmentOffset,
this.clipBehavior = Clip.hardEdge,
this.focusNode,
this.statesController,
this.leadingIcon,
this.trailingIcon,
required this.menuChildren,
required this.child,
});
/// Called when a pointer enters or exits the button response area.
///
/// The value passed to the callback is true if a pointer has entered this
/// part of the button and false if a pointer has exited.
final ValueChanged<bool>? onHover;
/// Handler called when the focus changes.
///
/// Called with true if this widget's [focusNode] gains focus, and false if it
/// loses focus.
final ValueChanged<bool>? onFocusChange;
/// A callback that is invoked when the menu is opened.
final VoidCallback? onOpen;
/// A callback that is invoked when the menu is closed.
final VoidCallback? onClose;
/// An optional [MenuController] for this submenu.
final MenuController? controller;
/// Customizes this button's appearance.
///
/// Non-null properties of this style override the corresponding properties in
/// [themeStyleOf] and [defaultStyleOf]. [MaterialStateProperty]s that resolve
/// to non-null values will similarly override the corresponding
/// [MaterialStateProperty]s in [themeStyleOf] and [defaultStyleOf].
///
/// Null by default.
final ButtonStyle? style;
/// The [MenuStyle] of the menu specified by [menuChildren].
///
/// Defaults to the value of [MenuThemeData.style] of the ambient [MenuTheme].
final MenuStyle? menuStyle;
/// The offset of the menu relative to the alignment origin determined by
/// [MenuStyle.alignment] on the [style] attribute.
///
/// Use this for fine adjustments of the menu placement.
///
/// Defaults to an offset that takes into account the padding of the menu so
/// that the top starting corner of the first menu item is aligned with the
/// top of the [MenuAnchor] region.
final Offset? alignmentOffset;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.hardEdge].
final Clip clipBehavior;
/// {@macro flutter.widgets.Focus.focusNode}
final FocusNode? focusNode;
/// {@macro flutter.material.inkwell.statesController}
final MaterialStatesController? statesController;
/// An optional icon to display before the [child].
final Widget? leadingIcon;
/// An optional icon to display after the [child].
final Widget? trailingIcon;
/// The list of widgets that appear in the menu when it is opened.
///
/// These can be any widget, but are typically either [MenuItemButton] or
/// [SubmenuButton] widgets.
///
/// If [menuChildren] is empty, then the button for this menu item will be
/// disabled.
final List<Widget> menuChildren;
/// The widget displayed in the middle portion of this button.
///
/// Typically this is the button's label, using a [Text] widget.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
@override
State<SubmenuButton> createState() => _SubmenuButtonState();
/// Defines the button's default appearance.
///
/// {@macro flutter.material.text_button.default_style_of}
///
/// {@macro flutter.material.text_button.material3_defaults}
ButtonStyle defaultStyleOf(BuildContext context) {
return _MenuButtonDefaultsM3(context);
}
/// Returns the [MenuButtonThemeData.style] of the closest [MenuButtonTheme]
/// ancestor.
ButtonStyle? themeStyleOf(BuildContext context) {
return MenuButtonTheme.of(context).style;
}
/// A static convenience method that constructs a [SubmenuButton]'s
/// [ButtonStyle] given simple values.
///
/// The [foregroundColor] color is used to create a [MaterialStateProperty]
/// [ButtonStyle.foregroundColor] value. Specify a value for [foregroundColor]
/// to specify the color of the button's icons. Use [backgroundColor] for the
/// button's background fill color. Use [disabledForegroundColor] and
/// [disabledBackgroundColor] to specify the button's disabled icon and fill
/// color.
///
/// All of the other parameters are either used directly or used to create a
/// [MaterialStateProperty] with a single value for all states.
///
/// All parameters default to null, by default this method returns a
/// [ButtonStyle] that doesn't override anything.
///
/// For example, to override the default foreground color for a
/// [SubmenuButton], as well as its overlay color, with all of the standard
/// opacity adjustments for the pressed, focused, and hovered states, one
/// could write:
///
/// ```dart
/// SubmenuButton(
/// leadingIcon: const Icon(Icons.pets),
/// style: SubmenuButton.styleFrom(foregroundColor: Colors.green),
/// menuChildren: const <Widget>[ /* ... */ ],
/// child: const Text('Button Label'),
/// ),
/// ```
static ButtonStyle styleFrom({
Color? foregroundColor,
Color? backgroundColor,
Color? disabledForegroundColor,
Color? disabledBackgroundColor,
Color? shadowColor,
Color? surfaceTintColor,
Color? iconColor,
TextStyle? textStyle,
double? elevation,
EdgeInsetsGeometry? padding,
Size? minimumSize,
Size? fixedSize,
Size? maximumSize,
MouseCursor? enabledMouseCursor,
MouseCursor? disabledMouseCursor,
BorderSide? side,
OutlinedBorder? shape,
VisualDensity? visualDensity,
MaterialTapTargetSize? tapTargetSize,
Duration? animationDuration,
bool? enableFeedback,
AlignmentGeometry? alignment,
InteractiveInkFeatureFactory? splashFactory,
}) {
return TextButton.styleFrom(
foregroundColor: foregroundColor,
backgroundColor: backgroundColor,
disabledBackgroundColor: disabledBackgroundColor,
disabledForegroundColor: disabledForegroundColor,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
iconColor: iconColor,
textStyle: textStyle,
elevation: elevation,
padding: padding,
minimumSize: minimumSize,
fixedSize: fixedSize,
maximumSize: maximumSize,
enabledMouseCursor: enabledMouseCursor,
disabledMouseCursor: disabledMouseCursor,
side: side,
shape: shape,
visualDensity: visualDensity,
tapTargetSize: tapTargetSize,
animationDuration: animationDuration,
enableFeedback: enableFeedback,
alignment: alignment,
splashFactory: splashFactory,
);
}
@override
List<DiagnosticsNode> debugDescribeChildren() {
return <DiagnosticsNode>[
...menuChildren.map<DiagnosticsNode>((Widget child) {
return child.toDiagnosticsNode();
})
];
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<FocusNode?>('focusNode', focusNode));
properties.add(DiagnosticsProperty<MenuStyle>('menuStyle', menuStyle, defaultValue: null));
properties.add(DiagnosticsProperty<Offset>('alignmentOffset', alignmentOffset));
properties.add(EnumProperty<Clip>('clipBehavior', clipBehavior));
}
}
class _SubmenuButtonState extends State<SubmenuButton> {
FocusNode? _internalFocusNode;
bool _waitingToFocusMenu = false;
MenuController? _internalMenuController;
MenuController get _menuController => widget.controller ?? _internalMenuController!;
_MenuAnchorState? get _anchor => _MenuAnchorState._maybeOf(context);
FocusNode get _buttonFocusNode => widget.focusNode ?? _internalFocusNode!;
bool get _enabled => widget.menuChildren.isNotEmpty;
@override
void initState() {
super.initState();
if (widget.focusNode == null) {
_internalFocusNode = FocusNode();
assert(() {
if (_internalFocusNode != null) {
_internalFocusNode!.debugLabel = '$SubmenuButton(${widget.child})';
}
return true;
}());
}
if (widget.controller == null) {
_internalMenuController = MenuController();
}
_buttonFocusNode.addListener(_handleFocusChange);
}
@override
void dispose() {
_buttonFocusNode.removeListener(_handleFocusChange);
_internalFocusNode?.dispose();
_internalFocusNode = null;
super.dispose();
}
@override
void didUpdateWidget(SubmenuButton oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.focusNode != oldWidget.focusNode) {
if (oldWidget.focusNode == null) {
_internalFocusNode?.removeListener(_handleFocusChange);
_internalFocusNode?.dispose();
_internalFocusNode = null;
} else {
oldWidget.focusNode!.removeListener(_handleFocusChange);
}
if (widget.focusNode == null) {
_internalFocusNode ??= FocusNode();
assert(() {
if (_internalFocusNode != null) {
_internalFocusNode!.debugLabel = '$SubmenuButton(${widget.child})';
}
return true;
}());
}
_buttonFocusNode.addListener(_handleFocusChange);
}
if (widget.controller != oldWidget.controller) {
_internalMenuController = (oldWidget.controller == null) ? null : MenuController();
}
}
@override
Widget build(BuildContext context) {
Offset menuPaddingOffset = widget.alignmentOffset ?? Offset.zero;
final EdgeInsets menuPadding = _computeMenuPadding(context);
final Axis orientation = _anchor?._orientation ?? Axis.vertical;
// Move the submenu over by the size of the menu padding, so that
// the first menu item aligns with the submenu button that opens it.
menuPaddingOffset += switch ((orientation, Directionality.of(context))) {
(Axis.horizontal, TextDirection.rtl) => Offset(menuPadding.right, 0),
(Axis.horizontal, TextDirection.ltr) => Offset(-menuPadding.left, 0),
(Axis.vertical, TextDirection.rtl) => Offset(0, -menuPadding.top),
(Axis.vertical, TextDirection.ltr) => Offset(0, -menuPadding.top),
};
return MenuAnchor(
controller: _menuController,
childFocusNode: _buttonFocusNode,
alignmentOffset: menuPaddingOffset,
clipBehavior: widget.clipBehavior,
onClose: widget.onClose,
onOpen: () {
if (!_waitingToFocusMenu) {
SchedulerBinding.instance.addPostFrameCallback((_) {
_menuController._anchor?._focusButton();
_waitingToFocusMenu = false;
}, debugLabel: 'MenuAnchor.focus');
_waitingToFocusMenu = true;
}
setState(() { /* Rebuild with updated controller.isOpen value */ });
widget.onOpen?.call();
},
style: widget.menuStyle,
builder: (BuildContext context, MenuController controller, Widget? child) {
// Since we don't want to use the theme style or default style from the
// TextButton, we merge the styles, merging them in the right order when
// each type of style exists. Each "*StyleOf" function is only called
// once.
ButtonStyle mergedStyle = widget.themeStyleOf(context)?.merge(widget.defaultStyleOf(context))
?? widget.defaultStyleOf(context);
mergedStyle = widget.style?.merge(mergedStyle) ?? mergedStyle;
void toggleShowMenu(BuildContext context) {
if (controller._anchor == null) {
return;
}
if (controller.isOpen) {
controller.close();
} else {
controller.open();
}
}
// Called when the pointer is hovering over the menu button.
void handleHover(bool hovering, BuildContext context) {
widget.onHover?.call(hovering);
// Don't open the root menu bar menus on hover unless something else
// is already open. This means that the user has to first click to
// open a menu on the menu bar before hovering allows them to traverse
// it.
if (controller._anchor!._root._orientation == Axis.horizontal && !controller._anchor!._root._isOpen) {
return;
}
if (hovering) {
controller.open();
controller._anchor!._focusButton();
}
}
child = MergeSemantics(
child: Semantics(
expanded: _enabled && controller.isOpen,
child: TextButton(
style: mergedStyle,
focusNode: _buttonFocusNode,
onFocusChange: _enabled ? widget.onFocusChange : null,
onHover: _enabled ? (bool hovering) => handleHover(hovering, context) : null,
onPressed: _enabled ? () => toggleShowMenu(context) : null,
isSemanticButton: null,
child: _MenuItemLabel(
leadingIcon: widget.leadingIcon,
trailingIcon: widget.trailingIcon,
hasSubmenu: true,
showDecoration: (controller._anchor!._parent?._orientation ?? Axis.horizontal) == Axis.vertical,
child: child ?? const SizedBox(),
),
),
),
);
if (_enabled && _platformSupportsAccelerators) {
return MenuAcceleratorCallbackBinding(
onInvoke: () => toggleShowMenu(context),
hasSubmenu: true,
child: child,
);
}
return child;
},
menuChildren: widget.menuChildren,
child: widget.child,
);
}
EdgeInsets _computeMenuPadding(BuildContext context) {
final MaterialStateProperty<EdgeInsetsGeometry?> insets =
widget.menuStyle?.padding ??
MenuTheme.of(context).style?.padding ??
_MenuDefaultsM3(context).padding!;
return insets
.resolve(widget.statesController?.value ?? const <MaterialState>{})!
.resolve(Directionality.of(context));
}
void _handleFocusChange() {
if (_buttonFocusNode.hasPrimaryFocus) {
if (!_menuController.isOpen) {
_menuController.open();
}
} else {
if (!_menuController._anchor!._menuScopeNode.hasFocus && _menuController.isOpen) {
_menuController.close();
}
}
}
}
/// An action that closes all the menus associated with the given
/// [MenuController].
///
/// See also:
///
/// * [MenuAnchor], a widget that hosts a cascading submenu.
/// * [MenuBar], a widget that defines a menu bar with cascading submenus.
class DismissMenuAction extends DismissAction {
/// Creates a [DismissMenuAction].
DismissMenuAction({required this.controller});
/// The [MenuController] associated with the menus that should be closed.
final MenuController controller;
@override
void invoke(DismissIntent intent) {
assert(_debugMenuInfo('$runtimeType: Dismissing all open menus.'));
controller._anchor!._root._close();
}
@override
bool isEnabled(DismissIntent intent) {
return controller.isOpen;
}
}
/// A helper class used to generate shortcut labels for a
/// [MenuSerializableShortcut] (a subset of the subclasses of
/// [ShortcutActivator]).
///
/// This helper class is typically used by the [MenuItemButton] and
/// [SubmenuButton] classes to display a label for their assigned shortcuts.
///
/// Call [getShortcutLabel] with the [MenuSerializableShortcut] to get a label
/// for it.
///
/// For instance, calling [getShortcutLabel] with `SingleActivator(trigger:
/// LogicalKeyboardKey.keyA, control: true)` would return "⌃ A" on macOS, "Ctrl
/// A" in an US English locale, and "Strg A" in a German locale.
class _LocalizedShortcutLabeler {
_LocalizedShortcutLabeler._();
static _LocalizedShortcutLabeler? _instance;
static final Map<LogicalKeyboardKey, String> _shortcutGraphicEquivalents = <LogicalKeyboardKey, String>{
LogicalKeyboardKey.arrowLeft: '←',
LogicalKeyboardKey.arrowRight: '→',
LogicalKeyboardKey.arrowUp: '↑',
LogicalKeyboardKey.arrowDown: '↓',
LogicalKeyboardKey.enter: '↵',
};
static final Set<LogicalKeyboardKey> _modifiers = <LogicalKeyboardKey>{
LogicalKeyboardKey.alt,
LogicalKeyboardKey.control,
LogicalKeyboardKey.meta,
LogicalKeyboardKey.shift,
LogicalKeyboardKey.altLeft,
LogicalKeyboardKey.controlLeft,
LogicalKeyboardKey.metaLeft,
LogicalKeyboardKey.shiftLeft,
LogicalKeyboardKey.altRight,
LogicalKeyboardKey.controlRight,
LogicalKeyboardKey.metaRight,
LogicalKeyboardKey.shiftRight,
};
/// Return the instance for this singleton.
static _LocalizedShortcutLabeler get instance {
return _instance ??= _LocalizedShortcutLabeler._();
}
// Caches the created shortcut key maps so that creating one of these isn't
// expensive after the first time for each unique localizations object.
final Map<MaterialLocalizations, Map<LogicalKeyboardKey, String>> _cachedShortcutKeys =
<MaterialLocalizations, Map<LogicalKeyboardKey, String>>{};
/// Returns the label to be shown to the user in the UI when a
/// [MenuSerializableShortcut] is used as a keyboard shortcut.
///
/// When [defaultTargetPlatform] is [TargetPlatform.macOS] or
/// [TargetPlatform.iOS], this will return graphical key representations when
/// it can. For instance, the default [LogicalKeyboardKey.shift] will return
/// '⇧', and the arrow keys will return arrows. The key
/// [LogicalKeyboardKey.meta] will show as '⌘', [LogicalKeyboardKey.control]
/// will show as '˄', and [LogicalKeyboardKey.alt] will show as '⌥'.
///
/// The keys are joined by spaces on macOS and iOS, and by "+" on other
/// platforms.
String getShortcutLabel(MenuSerializableShortcut shortcut, MaterialLocalizations localizations) {
final ShortcutSerialization serialized = shortcut.serializeForMenu();
final String keySeparator;
if (_usesSymbolicModifiers) {
// Use "⌃ ⇧ A" style on macOS and iOS.
keySeparator = ' ';
} else {
// Use "Ctrl+Shift+A" style.
keySeparator = '+';
}
if (serialized.trigger != null) {
final List<String> modifiers = <String>[];
final LogicalKeyboardKey trigger = serialized.trigger!;
if (_usesSymbolicModifiers) {
// macOS/iOS platform convention uses this ordering, with ⌘ always last.
if (serialized.control!) {
modifiers.add(_getModifierLabel(LogicalKeyboardKey.control, localizations));
}
if (serialized.alt!) {
modifiers.add(_getModifierLabel(LogicalKeyboardKey.alt, localizations));
}
if (serialized.shift!) {
modifiers.add(_getModifierLabel(LogicalKeyboardKey.shift, localizations));
}
if (serialized.meta!) {
modifiers.add(_getModifierLabel(LogicalKeyboardKey.meta, localizations));
}
} else {
// These should be in this order, to match the LogicalKeySet version.
if (serialized.alt!) {
modifiers.add(_getModifierLabel(LogicalKeyboardKey.alt, localizations));
}
if (serialized.control!) {
modifiers.add(_getModifierLabel(LogicalKeyboardKey.control, localizations));
}
if (serialized.meta!) {
modifiers.add(_getModifierLabel(LogicalKeyboardKey.meta, localizations));
}
if (serialized.shift!) {
modifiers.add(_getModifierLabel(LogicalKeyboardKey.shift, localizations));
}
}
String? shortcutTrigger;
final int logicalKeyId = trigger.keyId;
if (_shortcutGraphicEquivalents.containsKey(trigger)) {
shortcutTrigger = _shortcutGraphicEquivalents[trigger];
} else {
// Otherwise, look it up, and if we don't have a translation for it,
// then fall back to the key label.
shortcutTrigger = _getLocalizedName(trigger, localizations);
if (shortcutTrigger == null && logicalKeyId & LogicalKeyboardKey.planeMask == 0x0) {
// If the trigger is a Unicode-character-producing key, then use the
// character.
shortcutTrigger = String.fromCharCode(logicalKeyId & LogicalKeyboardKey.valueMask).toUpperCase();
}
// Fall back to the key label if all else fails.
shortcutTrigger ??= trigger.keyLabel;
}
return <String>[
...modifiers,
if (shortcutTrigger != null && shortcutTrigger.isNotEmpty) shortcutTrigger,
].join(keySeparator);
} else if (serialized.character != null) {
return serialized.character!;
}
throw UnimplementedError('Shortcut labels for ShortcutActivators that do not implement '
'MenuSerializableShortcut (e.g. ShortcutActivators other than SingleActivator or '
'CharacterActivator) are not supported.');
}
// Tries to look up the key in an internal table, and if it can't find it,
// then fall back to the key's keyLabel.
String? _getLocalizedName(LogicalKeyboardKey key, MaterialLocalizations localizations) {
// Since this is an expensive table to build, we cache it based on the
// localization object. There's currently no way to clear the cache, but
// it's unlikely that more than one or two will be cached for each run, and
// they're not huge.
_cachedShortcutKeys[localizations] ??= <LogicalKeyboardKey, String>{
LogicalKeyboardKey.altGraph: localizations.keyboardKeyAltGraph,
LogicalKeyboardKey.backspace: localizations.keyboardKeyBackspace,
LogicalKeyboardKey.capsLock: localizations.keyboardKeyCapsLock,
LogicalKeyboardKey.channelDown: localizations.keyboardKeyChannelDown,
LogicalKeyboardKey.channelUp: localizations.keyboardKeyChannelUp,
LogicalKeyboardKey.delete: localizations.keyboardKeyDelete,
LogicalKeyboardKey.eject: localizations.keyboardKeyEject,
LogicalKeyboardKey.end: localizations.keyboardKeyEnd,
LogicalKeyboardKey.escape: localizations.keyboardKeyEscape,
LogicalKeyboardKey.fn: localizations.keyboardKeyFn,
LogicalKeyboardKey.home: localizations.keyboardKeyHome,
LogicalKeyboardKey.insert: localizations.keyboardKeyInsert,
LogicalKeyboardKey.numLock: localizations.keyboardKeyNumLock,
LogicalKeyboardKey.numpad1: localizations.keyboardKeyNumpad1,
LogicalKeyboardKey.numpad2: localizations.keyboardKeyNumpad2,
LogicalKeyboardKey.numpad3: localizations.keyboardKeyNumpad3,
LogicalKeyboardKey.numpad4: localizations.keyboardKeyNumpad4,
LogicalKeyboardKey.numpad5: localizations.keyboardKeyNumpad5,
LogicalKeyboardKey.numpad6: localizations.keyboardKeyNumpad6,
LogicalKeyboardKey.numpad7: localizations.keyboardKeyNumpad7,
LogicalKeyboardKey.numpad8: localizations.keyboardKeyNumpad8,
LogicalKeyboardKey.numpad9: localizations.keyboardKeyNumpad9,
LogicalKeyboardKey.numpad0: localizations.keyboardKeyNumpad0,
LogicalKeyboardKey.numpadAdd: localizations.keyboardKeyNumpadAdd,
LogicalKeyboardKey.numpadComma: localizations.keyboardKeyNumpadComma,
LogicalKeyboardKey.numpadDecimal: localizations.keyboardKeyNumpadDecimal,
LogicalKeyboardKey.numpadDivide: localizations.keyboardKeyNumpadDivide,
LogicalKeyboardKey.numpadEnter: localizations.keyboardKeyNumpadEnter,
LogicalKeyboardKey.numpadEqual: localizations.keyboardKeyNumpadEqual,
LogicalKeyboardKey.numpadMultiply: localizations.keyboardKeyNumpadMultiply,
LogicalKeyboardKey.numpadParenLeft: localizations.keyboardKeyNumpadParenLeft,
LogicalKeyboardKey.numpadParenRight: localizations.keyboardKeyNumpadParenRight,
LogicalKeyboardKey.numpadSubtract: localizations.keyboardKeyNumpadSubtract,
LogicalKeyboardKey.pageDown: localizations.keyboardKeyPageDown,
LogicalKeyboardKey.pageUp: localizations.keyboardKeyPageUp,
LogicalKeyboardKey.power: localizations.keyboardKeyPower,
LogicalKeyboardKey.powerOff: localizations.keyboardKeyPowerOff,
LogicalKeyboardKey.printScreen: localizations.keyboardKeyPrintScreen,
LogicalKeyboardKey.scrollLock: localizations.keyboardKeyScrollLock,
LogicalKeyboardKey.select: localizations.keyboardKeySelect,
LogicalKeyboardKey.space: localizations.keyboardKeySpace,
};
return _cachedShortcutKeys[localizations]![key];
}
String _getModifierLabel(LogicalKeyboardKey modifier, MaterialLocalizations localizations) {
assert(_modifiers.contains(modifier), '${modifier.keyLabel} is not a modifier key');
if (modifier == LogicalKeyboardKey.meta ||
modifier == LogicalKeyboardKey.metaLeft ||
modifier == LogicalKeyboardKey.metaRight) {
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
return localizations.keyboardKeyMeta;
case TargetPlatform.windows:
return localizations.keyboardKeyMetaWindows;
case TargetPlatform.iOS:
case TargetPlatform.macOS:
return '⌘';
}
}
if (modifier == LogicalKeyboardKey.alt ||
modifier == LogicalKeyboardKey.altLeft ||
modifier == LogicalKeyboardKey.altRight) {
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
return localizations.keyboardKeyAlt;
case TargetPlatform.iOS:
case TargetPlatform.macOS:
return '⌥';
}
}
if (modifier == LogicalKeyboardKey.control ||
modifier == LogicalKeyboardKey.controlLeft ||
modifier == LogicalKeyboardKey.controlRight) {
// '⎈' (a boat helm wheel, not an asterisk) is apparently the standard
// icon for "control", but only seems to appear on the French Canadian
// keyboard. A '✲' (an open center asterisk) appears on some Microsoft
// keyboards. For all but macOS (which has standardized on "⌃", it seems),
// we just return the local translation of "Ctrl".
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
return localizations.keyboardKeyControl;
case TargetPlatform.iOS:
case TargetPlatform.macOS:
return '⌃';
}
}
if (modifier == LogicalKeyboardKey.shift ||
modifier == LogicalKeyboardKey.shiftLeft ||
modifier == LogicalKeyboardKey.shiftRight) {
switch (defaultTargetPlatform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
return localizations.keyboardKeyShift;
case TargetPlatform.iOS:
case TargetPlatform.macOS:
return '⇧';
}
}
throw ArgumentError('Keyboard key ${modifier.keyLabel} is not a modifier.');
}
}
class _MenuAnchorScope extends InheritedWidget {
const _MenuAnchorScope({
required super.child,
required this.anchorKey,
required this.anchor,
required this.isOpen,
});
final GlobalKey anchorKey;
final _MenuAnchorState anchor;
final bool isOpen;
@override
bool updateShouldNotify(_MenuAnchorScope oldWidget) {
return anchorKey != oldWidget.anchorKey
|| anchor != oldWidget.anchor
|| isOpen != oldWidget.isOpen;
}
}
/// MenuBar-specific private specialization of [MenuAnchor] so that it can act
/// differently in regards to orientation, how open works, and what gets built.
class _MenuBarAnchor extends MenuAnchor {
const _MenuBarAnchor({
required super.menuChildren,
super.controller,
super.clipBehavior,
super.style,
});
@override
State<MenuAnchor> createState() => _MenuBarAnchorState();
}
class _MenuBarAnchorState extends _MenuAnchorState {
@override
bool get _isOpen {
// If it's a bar, then it's "open" if any of its children are open.
for (final _MenuAnchorState child in _anchorChildren) {
if (child._isOpen) {
return true;
}
}
return false;
}
@override
Axis get _orientation => Axis.horizontal;
@override
Widget _buildContents(BuildContext context) {
final bool isOpen = _isOpen;
return FocusScope(
node: _menuScopeNode,
skipTraversal: !isOpen,
canRequestFocus: isOpen,
child: ExcludeFocus(
excluding: !isOpen,
child: Shortcuts(
shortcuts: _kMenuTraversalShortcuts,
child: Actions(
actions: <Type, Action<Intent>>{
DirectionalFocusIntent: _MenuDirectionalFocusAction(),
PreviousFocusIntent: _MenuPreviousFocusAction(),
NextFocusIntent: _MenuNextFocusAction(),
DismissIntent: DismissMenuAction(controller: _menuController),
},
child: Builder(builder: (BuildContext context) {
return _MenuPanel(
menuStyle: widget.style,
clipBehavior: widget.clipBehavior,
orientation: Axis.horizontal,
children: widget.menuChildren,
);
}),
),
),
),
);
}
@override
void _open({Offset? position}) {
assert(_menuController._anchor == this);
// Menu bars can't be opened, because they're already always open.
return;
}
}
class _MenuPreviousFocusAction extends PreviousFocusAction {
@override
bool invoke(PreviousFocusIntent intent) {
assert(_debugMenuInfo('_MenuNextFocusAction invoked with $intent'));
final BuildContext? context = FocusManager.instance.primaryFocus?.context;
if (context == null) {
return super.invoke(intent);
}
final _MenuAnchorState? anchor = _MenuAnchorState._maybeOf(context);
if (anchor == null || !anchor._root._isOpen) {
return super.invoke(intent);
}
return _moveToPreviousFocusable(anchor);
}
static bool _moveToPreviousFocusable(_MenuAnchorState currentMenu) {
final _MenuAnchorState? sibling = currentMenu._previousFocusableSibling;
sibling?._focusButton();
return true;
}
}
class _MenuNextFocusAction extends NextFocusAction {
@override
bool invoke(NextFocusIntent intent) {
assert(_debugMenuInfo('_MenuNextFocusAction invoked with $intent'));
final BuildContext? context = FocusManager.instance.primaryFocus?.context;
if (context == null) {
return super.invoke(intent);
}
final _MenuAnchorState? anchor = _MenuAnchorState._maybeOf(context);
if (anchor == null || !anchor._root._isOpen) {
return super.invoke(intent);
}
return _moveToNextFocusable(anchor);
}
static bool _moveToNextFocusable(_MenuAnchorState currentMenu) {
final _MenuAnchorState? sibling = currentMenu._nextFocusableSibling;
sibling?._focusButton();
return true;
}
}
class _MenuDirectionalFocusAction extends DirectionalFocusAction {
/// Creates a [DirectionalFocusAction].
_MenuDirectionalFocusAction();
@override
void invoke(DirectionalFocusIntent intent) {
assert(_debugMenuInfo('_MenuDirectionalFocusAction invoked with $intent'));
final BuildContext? context = FocusManager.instance.primaryFocus?.context;
if (context == null) {
super.invoke(intent);
return;
}
final _MenuAnchorState? anchor = _MenuAnchorState._maybeOf(context);
if (anchor == null || !anchor._root._isOpen) {
super.invoke(intent);
return;
}
final bool buttonIsFocused = anchor.widget.childFocusNode?.hasPrimaryFocus ?? false;
Axis orientation;
if (buttonIsFocused && anchor._parent != null) {
orientation = anchor._parent!._orientation;
} else {
orientation = anchor._orientation;
}
final bool firstItemIsFocused = anchor._firstItemFocusNode?.hasPrimaryFocus ?? false;
assert(_debugMenuInfo('In _MenuDirectionalFocusAction, current node is ${anchor.widget.childFocusNode?.debugLabel}, '
'button is${buttonIsFocused ? '' : ' not'} focused. Assuming ${orientation.name} orientation.'));
switch (intent.direction) {
case TraversalDirection.up:
switch (orientation) {
case Axis.horizontal:
if (_moveToParent(anchor)) {
return;
}
case Axis.vertical:
if (firstItemIsFocused) {
if (_moveToParent(anchor)) {
return;
}
}
if (_moveToPrevious(anchor)) {
return;
}
}
case TraversalDirection.down:
switch (orientation) {
case Axis.horizontal:
if (_moveToSubmenu(anchor)) {
return;
}
case Axis.vertical:
if (_moveToNext(anchor)) {
return;
}
}
case TraversalDirection.left:
switch (orientation) {
case Axis.horizontal:
switch (Directionality.of(context)) {
case TextDirection.rtl:
if (_moveToNext(anchor)) {
return;
}
case TextDirection.ltr:
if (_moveToPrevious(anchor)) {
return;
}
}
case Axis.vertical:
switch (Directionality.of(context)) {
case TextDirection.rtl:
if (buttonIsFocused) {
if (_moveToSubmenu(anchor)) {
return;
}
} else {
if (_moveToNextFocusableTopLevel(anchor)) {
return;
}
}
case TextDirection.ltr:
switch (anchor._parent?._orientation) {
case Axis.horizontal:
case null:
if (_moveToPreviousFocusableTopLevel(anchor)) {
return;
}
case Axis.vertical:
if (buttonIsFocused) {
if (_moveToPreviousFocusableTopLevel(anchor)) {
return;
}
} else {
if (_moveToParent(anchor)) {
return;
}
}
}
}
}
case TraversalDirection.right:
switch (orientation) {
case Axis.horizontal:
switch (Directionality.of(context)) {
case TextDirection.rtl:
if (_moveToPrevious(anchor)) {
return;
}
case TextDirection.ltr:
if (_moveToNext(anchor)) {
return;
}
}
case Axis.vertical:
switch (Directionality.of(context)) {
case TextDirection.rtl:
switch (anchor._parent?._orientation) {
case Axis.horizontal:
case null:
if (_moveToPreviousFocusableTopLevel(anchor)) {
return;
}
case Axis.vertical:
if (_moveToParent(anchor)) {
return;
}
}
case TextDirection.ltr:
if (buttonIsFocused) {
if (_moveToSubmenu(anchor)) {
return;
}
} else {
if (_moveToNextFocusableTopLevel(anchor)) {
return;
}
}
}
}
}
super.invoke(intent);
}
bool _moveToNext(_MenuAnchorState currentMenu) {
assert(_debugMenuInfo('Moving focus to next item in menu'));
// Need to invalidate the scope data because we're switching scopes, and
// otherwise the anti-hysteresis code will interfere with moving to the
// correct node.
if (currentMenu.widget.childFocusNode != null) {
if (currentMenu.widget.childFocusNode!.nearestScope != null) {
final FocusTraversalPolicy? policy = FocusTraversalGroup.maybeOf(primaryFocus!.context!);
policy?.invalidateScopeData(currentMenu.widget.childFocusNode!.nearestScope!);
}
}
return false;
}
bool _moveToNextFocusableTopLevel(_MenuAnchorState currentMenu) {
final _MenuAnchorState? sibling = currentMenu._topLevel._nextFocusableSibling;
sibling?._focusButton();
return true;
}
bool _moveToParent(_MenuAnchorState currentMenu) {
assert(_debugMenuInfo('Moving focus to parent menu button'));
if (!(currentMenu.widget.childFocusNode?.hasPrimaryFocus ?? true)) {
currentMenu._focusButton();
}
return true;
}
bool _moveToPrevious(_MenuAnchorState currentMenu) {
assert(_debugMenuInfo('Moving focus to previous item in menu'));
// Need to invalidate the scope data because we're switching scopes, and
// otherwise the anti-hysteresis code will interfere with moving to the
// correct node.
if (currentMenu.widget.childFocusNode != null) {
if (currentMenu.widget.childFocusNode!.nearestScope != null) {
final FocusTraversalPolicy? policy = FocusTraversalGroup.maybeOf(primaryFocus!.context!);
policy?.invalidateScopeData(currentMenu.widget.childFocusNode!.nearestScope!);
}
}
return false;
}
bool _moveToPreviousFocusableTopLevel(_MenuAnchorState currentMenu) {
final _MenuAnchorState? sibling = currentMenu._topLevel._previousFocusableSibling;
sibling?._focusButton();
return true;
}
bool _moveToSubmenu(_MenuAnchorState currentMenu) {
assert(_debugMenuInfo('Opening submenu'));
if (!currentMenu._isOpen) {
// If no submenu is open, then an arrow opens the submenu.
currentMenu._open();
return true;
} else {
final FocusNode? firstNode = currentMenu._firstItemFocusNode;
if (firstNode != null && firstNode.nearestScope != firstNode) {
// Don't request focus if the "first" found node is a focus scope, since
// that means that nothing else in the submenu is focusable.
firstNode.requestFocus();
}
return true;
}
}
}
/// An [InheritedWidget] that provides a descendant [MenuAcceleratorLabel] with
/// the function to invoke when the accelerator is pressed.
///
/// This is used when creating your own custom menu item for use with
/// [MenuAnchor] or [MenuBar]. Provided menu items such as [MenuItemButton] and
/// [SubmenuButton] already supply this wrapper internally.
class MenuAcceleratorCallbackBinding extends InheritedWidget {
/// Create a const [MenuAcceleratorCallbackBinding].
///
/// The [child] parameter is required.
const MenuAcceleratorCallbackBinding({
super.key,
this.onInvoke,
this.hasSubmenu = false,
required super.child,
});
/// The function that pressing the accelerator defined in a descendant
/// [MenuAcceleratorLabel] will invoke.
///
/// If set to null, then the accelerator won't be enabled.
final VoidCallback? onInvoke;
/// Whether or not the associated label will host its own submenu or not.
///
/// This setting determines when accelerators are active, since accelerators
/// for menu items that open submenus shouldn't be active when the submenu is
/// open.
final bool hasSubmenu;
@override
bool updateShouldNotify(MenuAcceleratorCallbackBinding oldWidget) {
return onInvoke != oldWidget.onInvoke || hasSubmenu != oldWidget.hasSubmenu;
}
/// Returns the active [MenuAcceleratorCallbackBinding] in the given context, if any,
/// and creates a dependency relationship that will rebuild the context when
/// [onInvoke] changes.
///
/// If no [MenuAcceleratorCallbackBinding] is found, returns null.
///
/// See also:
///
/// * [of], which is similar, but asserts if no [MenuAcceleratorCallbackBinding]
/// is found.
static MenuAcceleratorCallbackBinding? maybeOf(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<MenuAcceleratorCallbackBinding>();
}
/// Returns the active [MenuAcceleratorCallbackBinding] in the given context, and
/// creates a dependency relationship that will rebuild the context when
/// [onInvoke] changes.
///
/// If no [MenuAcceleratorCallbackBinding] is found, returns will assert in debug mode
/// and throw an exception in release mode.
///
/// See also:
///
/// * [maybeOf], which is similar, but returns null if no
/// [MenuAcceleratorCallbackBinding] is found.
static MenuAcceleratorCallbackBinding of(BuildContext context) {
final MenuAcceleratorCallbackBinding? result = maybeOf(context);
assert(() {
if (result == null) {
throw FlutterError(
'MenuAcceleratorWrapper.of() was called with a context that does not '
'contain a MenuAcceleratorWrapper in the given context.\n'
'No MenuAcceleratorWrapper ancestor could be found in the context that '
'was passed to MenuAcceleratorWrapper.of(). This can happen because '
'you are using a widget that looks for a MenuAcceleratorWrapper '
'ancestor, and do not have a MenuAcceleratorWrapper widget ancestor.\n'
'The context used was:\n'
' $context',
);
}
return true;
}());
return result!;
}
}
/// The type of builder function used for building a [MenuAcceleratorLabel]'s
/// [MenuAcceleratorLabel.builder] function.
///
/// {@template flutter.material.menu_anchor.menu_accelerator_child_builder.args}
/// The arguments to the function are as follows:
///
/// * The `context` supplies the [BuildContext] to use.
/// * The `label` is the [MenuAcceleratorLabel.label] attribute for the relevant
/// [MenuAcceleratorLabel] with the accelerator markers stripped out of it.
/// * The `index` is the index of the accelerator character within the
/// `label.characters` that applies to this accelerator. If it is -1, then the
/// accelerator should not be highlighted. Otherwise, the given character
/// should be highlighted somehow in the rendered label (typically with an
/// underscore). Importantly, `index` is not an index into the [String]
/// `label`, it is an index into the [Characters] iterable returned by
/// `label.characters`, so that it is in terms of user-visible characters
/// (a.k.a. grapheme clusters), not Unicode code points.
/// {@endtemplate}
///
/// See also:
///
/// * [MenuAcceleratorLabel.defaultLabelBuilder], which is the implementation
/// used as the default value for [MenuAcceleratorLabel.builder].
typedef MenuAcceleratorChildBuilder = Widget Function(
BuildContext context,
String label,
int index,
);
/// A widget that draws the label text for a menu item (typically a
/// [MenuItemButton] or [SubmenuButton]) and renders its child with information
/// about the currently active keyboard accelerator.
///
/// On platforms other than macOS and iOS, this widget listens for the Alt key
/// to be pressed, and when it is down, will update the label by calling the
/// builder again with the position of the accelerator in the label string.
/// While the Alt key is pressed, it registers a shortcut with the
/// [ShortcutRegistry] mapped to a [VoidCallbackIntent] containing the callback
/// defined by the nearest [MenuAcceleratorCallbackBinding].
///
/// Because the accelerators are registered with the [ShortcutRegistry], any
/// other shortcuts in the widget tree between the [primaryFocus] and the
/// [ShortcutRegistry] that define Alt-based shortcuts using the same keys will
/// take precedence over the accelerators.
///
/// Because accelerators aren't used on macOS and iOS, the label ignores the Alt
/// key on those platforms, and the [builder] is always given -1 as an
/// accelerator index. Accelerator labels are still stripped of their
/// accelerator markers.
///
/// The built-in menu items [MenuItemButton] and [SubmenuButton] already provide
/// the appropriate [MenuAcceleratorCallbackBinding], so unless you are creating
/// your own custom menu item type that takes a [MenuAcceleratorLabel], it is
/// not necessary to provide one.
///
/// {@template flutter.material.MenuAcceleratorLabel.accelerator_sample}
/// {@tool dartpad} This example shows a [MenuBar] that handles keyboard
/// accelerators using [MenuAcceleratorLabel]. To use the accelerators, press
/// the Alt key to see which letters are underlined in the menu bar, and then
/// press the appropriate letter. Accelerators are not supported on macOS or iOS
/// since those platforms don't support them natively, so this demo will only
/// show a regular Material menu bar on those platforms.
///
/// ** See code in examples/api/lib/material/menu_anchor/menu_accelerator_label.0.dart **
/// {@end-tool}
/// {@endtemplate}
class MenuAcceleratorLabel extends StatefulWidget {
/// Creates a const [MenuAcceleratorLabel].
///
/// The [label] parameter is required.
const MenuAcceleratorLabel(
this.label, {
super.key,
this.builder = defaultLabelBuilder,
});
/// The label string that should be displayed.
///
/// The label string provides the label text, as well as the possible
/// characters which could be used as accelerators in the menu system.
///
/// {@template flutter.material.menu_anchor.menu_accelerator_label.label}
/// To indicate which letters in the label are to be used as accelerators, add
/// an "&" character before the character in the string. If more than one
/// character has an "&" in front of it, then the characters appearing earlier
/// in the string are preferred. To represent a literal "&", insert "&&" into
/// the string. All other ampersands will be removed from the string before
/// calling [MenuAcceleratorLabel.builder]. Bare ampersands at the end of the
/// string or before whitespace are stripped and ignored.
/// {@endtemplate}
///
/// See also:
///
/// * [displayLabel], which returns the [label] with all of the ampersands
/// stripped out of it, and double ampersands converted to ampersands.
/// * [stripAcceleratorMarkers], which returns the supplied string with all of
/// the ampersands stripped out of it, and double ampersands converted to
/// ampersands, and optionally calls a callback with the index of the
/// accelerator character found.
final String label;
/// Returns the [label] with any accelerator markers removed.
///
/// This getter just calls [stripAcceleratorMarkers] with the [label].
String get displayLabel => stripAcceleratorMarkers(label);
/// The optional [MenuAcceleratorChildBuilder] which is used to build the
/// widget that displays the label itself.
///
/// The [defaultLabelBuilder] function serves as the default value for
/// [builder], rendering the label as a [RichText] widget with appropriate
/// [TextSpan]s for rendering the label with an underscore under the selected
/// accelerator for the label when accelerators have been activated.
///
/// {@macro flutter.material.menu_anchor.menu_accelerator_child_builder.args}
///
/// When writing the builder function, it's not necessary to take the current
/// platform into account. On platforms which don't support accelerators (e.g.
/// macOS and iOS), the passed accelerator index will always be -1, and the
/// accelerator markers will already be stripped.
final MenuAcceleratorChildBuilder builder;
/// Whether [label] contains an accelerator definition.
///
/// {@macro flutter.material.menu_anchor.menu_accelerator_label.label}
bool get hasAccelerator => RegExp(r'&(?!([&\s]|$))').hasMatch(label);
/// Serves as the default value for [builder], rendering the label as a
/// [RichText] widget with appropriate [TextSpan]s for rendering the label
/// with an underscore under the selected accelerator for the label when the
/// [index] is non-negative, and a [Text] widget when the [index] is negative.
///
/// {@macro flutter.material.menu_anchor.menu_accelerator_child_builder.args}
static Widget defaultLabelBuilder(
BuildContext context,
String label,
int index,
) {
if (index < 0) {
return Text(label);
}
final TextStyle defaultStyle = DefaultTextStyle.of(context).style;
final Characters characters = label.characters;
return RichText(
text: TextSpan(
children: <TextSpan>[
if (index > 0)
TextSpan(text: characters.getRange(0, index).toString(), style: defaultStyle),
TextSpan(
text: characters.getRange(index, index + 1).toString(),
style: defaultStyle.copyWith(decoration: TextDecoration.underline),
),
if (index < characters.length - 1)
TextSpan(text: characters.getRange(index + 1).toString(), style: defaultStyle),
],
),
);
}
/// Strips out any accelerator markers from the given [label], and unescapes
/// any escaped ampersands.
///
/// If [setIndex] is supplied, it will be called before this function returns
/// with the index in the returned string of the accelerator character.
///
/// {@macro flutter.material.menu_anchor.menu_accelerator_label.label}
static String stripAcceleratorMarkers(String label, {void Function(int index)? setIndex}) {
int quotedAmpersands = 0;
final StringBuffer displayLabel = StringBuffer();
int acceleratorIndex = -1;
// Use characters so that we don't split up surrogate pairs and interpret
// them incorrectly.
final Characters labelChars = label.characters;
final Characters ampersand = '&'.characters;
bool lastWasAmpersand = false;
for (int i = 0; i < labelChars.length; i += 1) {
// Stop looking one before the end, since a single ampersand at the end is
// just treated as a quoted ampersand.
final Characters character = labelChars.characterAt(i);
if (lastWasAmpersand) {
lastWasAmpersand = false;
displayLabel.write(character);
continue;
}
if (character != ampersand) {
displayLabel.write(character);
continue;
}
if (i == labelChars.length - 1) {
// Strip bare ampersands at the end of a string.
break;
}
lastWasAmpersand = true;
final Characters acceleratorCharacter = labelChars.characterAt(i + 1);
if (acceleratorIndex == -1 && acceleratorCharacter != ampersand &&
acceleratorCharacter.toString().trim().isNotEmpty) {
// Don't set the accelerator index if the character is an ampersand,
// or whitespace.
acceleratorIndex = i - quotedAmpersands;
}
// As we encounter '&<character>' pairs, the following indices must be
// adjusted so that they correspond with indices in the stripped string.
quotedAmpersands += 1;
}
setIndex?.call(acceleratorIndex);
return displayLabel.toString();
}
@override
State<MenuAcceleratorLabel> createState() => _MenuAcceleratorLabelState();
@override
String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) {
return '$MenuAcceleratorLabel("$label")';
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(StringProperty('label', label));
}
}
class _MenuAcceleratorLabelState extends State<MenuAcceleratorLabel> {
late String _displayLabel;
int _acceleratorIndex = -1;
MenuAcceleratorCallbackBinding? _binding;
_MenuAnchorState? _anchor;
ShortcutRegistry? _shortcutRegistry;
ShortcutRegistryEntry? _shortcutRegistryEntry;
bool _showAccelerators = false;
@override
void initState() {
super.initState();
if (_platformSupportsAccelerators) {
_showAccelerators = _altIsPressed();
HardwareKeyboard.instance.addHandler(_listenToKeyEvent);
}
_updateDisplayLabel();
}
@override
void dispose() {
assert(_platformSupportsAccelerators || _shortcutRegistryEntry == null);
_displayLabel = '';
if (_platformSupportsAccelerators) {
_shortcutRegistryEntry?.dispose();
_shortcutRegistryEntry = null;
_shortcutRegistry = null;
_anchor = null;
HardwareKeyboard.instance.removeHandler(_listenToKeyEvent);
}
super.dispose();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (!_platformSupportsAccelerators) {
return;
}
_binding = MenuAcceleratorCallbackBinding.maybeOf(context);
_anchor = _MenuAnchorState._maybeOf(context);
_shortcutRegistry = ShortcutRegistry.maybeOf(context);
_updateAcceleratorShortcut();
}
@override
void didUpdateWidget(MenuAcceleratorLabel oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.label != oldWidget.label) {
_updateDisplayLabel();
}
}
static bool _altIsPressed() {
return HardwareKeyboard.instance.logicalKeysPressed.intersection(
<LogicalKeyboardKey>{
LogicalKeyboardKey.altLeft,
LogicalKeyboardKey.altRight,
LogicalKeyboardKey.alt,
},
).isNotEmpty;
}
bool _listenToKeyEvent(KeyEvent event) {
assert(_platformSupportsAccelerators);
setState(() {
_showAccelerators = _altIsPressed();
_updateAcceleratorShortcut();
});
// Just listening, so it doesn't ever handle a key.
return false;
}
void _updateAcceleratorShortcut() {
assert(_platformSupportsAccelerators);
_shortcutRegistryEntry?.dispose();
_shortcutRegistryEntry = null;
// Before registering an accelerator as a shortcut it should meet these
// conditions:
//
// 1) Is showing accelerators (i.e. Alt key is down).
// 2) Has an accelerator marker in the label.
// 3) Has an associated action callback for the label (from the
// MenuAcceleratorCallbackBinding).
// 4) Is part of an anchor that either doesn't have a submenu, or doesn't
// have any submenus currently open (only the "deepest" open menu should
// have accelerator shortcuts registered).
if (_showAccelerators && _acceleratorIndex != -1 && _binding?.onInvoke != null && (!_binding!.hasSubmenu || !(_anchor?._isOpen ?? false))) {
final String acceleratorCharacter = _displayLabel[_acceleratorIndex].toLowerCase();
_shortcutRegistryEntry = _shortcutRegistry?.addAll(
<ShortcutActivator, Intent>{
CharacterActivator(acceleratorCharacter, alt: true): VoidCallbackIntent(_binding!.onInvoke!),
},
);
}
}
void _updateDisplayLabel() {
_displayLabel = MenuAcceleratorLabel.stripAcceleratorMarkers(
widget.label,
setIndex: (int index) {
_acceleratorIndex = index;
},
);
}
@override
Widget build(BuildContext context) {
final int index = _showAccelerators ? _acceleratorIndex : -1;
return widget.builder(context, _displayLabel, index);
}
}
/// A label widget that is used as the label for a [MenuItemButton] or
/// [SubmenuButton].
///
/// It not only shows the [SubmenuButton.child] or [MenuItemButton.child], but if
/// there is a shortcut associated with the [MenuItemButton], it will display a
/// mnemonic for the shortcut. For [SubmenuButton]s, it will display a visual
/// indicator that there is a submenu.
class _MenuItemLabel extends StatelessWidget {
/// Creates a const [_MenuItemLabel].
///
/// The [child] and [hasSubmenu] arguments are required.
const _MenuItemLabel({
required this.hasSubmenu,
this.showDecoration = true,
this.leadingIcon,
this.trailingIcon,
this.shortcut,
required this.child,
});
/// Whether or not this menu has a submenu.
///
/// Determines whether the submenu arrow is shown or not.
final bool hasSubmenu;
/// Whether or not this item should show decorations like shortcut labels or
/// submenu arrows. Items in a [MenuBar] don't show these decorations when
/// they are laid out horizontally.
final bool showDecoration;
/// The optional icon that comes before the [child].
final Widget? leadingIcon;
/// The optional icon that comes after the [child].
final Widget? trailingIcon;
/// The shortcut for this label, so that it can generate a string describing
/// the shortcut.
final MenuSerializableShortcut? shortcut;
/// The required label child widget.
final Widget child;
@override
Widget build(BuildContext context) {
final VisualDensity density = Theme.of(context).visualDensity;
final double horizontalPadding = math.max(
_kLabelItemMinSpacing,
_kLabelItemDefaultSpacing + density.horizontal * 2,
);
return Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
if (leadingIcon != null) leadingIcon!,
Padding(
padding: leadingIcon != null ? EdgeInsetsDirectional.only(start: horizontalPadding) : EdgeInsets.zero,
child: child,
),
],
),
if (trailingIcon != null)
Padding(
padding: EdgeInsetsDirectional.only(start: horizontalPadding),
child: trailingIcon,
),
if (showDecoration && shortcut != null)
Padding(
padding: EdgeInsetsDirectional.only(start: horizontalPadding),
child: Text(
_LocalizedShortcutLabeler.instance.getShortcutLabel(
shortcut!,
MaterialLocalizations.of(context),
),
),
),
if (showDecoration && hasSubmenu)
Padding(
padding: EdgeInsetsDirectional.only(start: horizontalPadding),
child: const Icon(
Icons.arrow_right, // Automatically switches with text direction.
size: _kDefaultSubmenuIconSize,
),
),
],
);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<MenuSerializableShortcut>('shortcut', shortcut, defaultValue: null));
properties.add(DiagnosticsProperty<bool>('hasSubmenu', hasSubmenu));
properties.add(DiagnosticsProperty<bool>('showDecoration', showDecoration));
}
}
// Positions the menu in the view while trying to keep as much as possible
// visible in the view.
class _MenuLayout extends SingleChildLayoutDelegate {
const _MenuLayout({
required this.anchorRect,
required this.textDirection,
required this.alignment,
required this.alignmentOffset,
required this.menuPosition,
required this.menuPadding,
required this.avoidBounds,
required this.orientation,
required this.parentOrientation,
});
// Rectangle of underlying button, relative to the overlay's dimensions.
final Rect anchorRect;
// Whether to prefer going to the left or to the right.
final TextDirection textDirection;
// The alignment to use when finding the ideal location for the menu.
final AlignmentGeometry alignment;
// The offset from the alignment position to find the ideal location for the
// menu.
final Offset alignmentOffset;
// The position passed to the open method, if any.
final Offset? menuPosition;
// The padding on the inside of the menu, so it can be accounted for when
// positioning.
final EdgeInsetsGeometry menuPadding;
// List of rectangles that we should avoid overlapping. Unusable screen area.
final Set<Rect> avoidBounds;
// The orientation of this menu
final Axis orientation;
// The orientation of this menu's parent.
final Axis parentOrientation;
@override
BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
// The menu can be at most the size of the overlay minus _kMenuViewPadding
// pixels in each direction.
return BoxConstraints.loose(constraints.biggest).deflate(
const EdgeInsets.all(_kMenuViewPadding),
);
}
@override
Offset getPositionForChild(Size size, Size childSize) {
// size: The size of the overlay.
// childSize: The size of the menu, when fully open, as determined by
// getConstraintsForChild.
final Rect overlayRect = Offset.zero & size;
double x;
double y;
if (menuPosition == null) {
Offset desiredPosition = alignment.resolve(textDirection).withinRect(anchorRect);
final Offset directionalOffset;
if (alignment is AlignmentDirectional) {
directionalOffset = switch (textDirection) {
TextDirection.rtl => Offset(-alignmentOffset.dx, alignmentOffset.dy),
TextDirection.ltr => alignmentOffset,
};
} else {
directionalOffset = alignmentOffset;
}
desiredPosition += directionalOffset;
x = desiredPosition.dx;
y = desiredPosition.dy;
switch (textDirection) {
case TextDirection.rtl:
x -= childSize.width;
case TextDirection.ltr:
break;
}
} else {
final Offset adjustedPosition = menuPosition! + anchorRect.topLeft;
x = adjustedPosition.dx;
y = adjustedPosition.dy;
}
final Iterable<Rect> subScreens = DisplayFeatureSubScreen.subScreensInBounds(overlayRect, avoidBounds);
final Rect allowedRect = _closestScreen(subScreens, anchorRect.center);
bool offLeftSide(double x) => x < allowedRect.left;
bool offRightSide(double x) => x + childSize.width > allowedRect.right;
bool offTop(double y) => y < allowedRect.top;
bool offBottom(double y) => y + childSize.height > allowedRect.bottom;
// Avoid going outside an area defined as the rectangle offset from the
// edge of the screen by the button padding. If the menu is off of the screen,
// move the menu to the other side of the button first, and then if it
// doesn't fit there, then just move it over as much as needed to make it
// fit.
if (childSize.width >= allowedRect.width) {
// It just doesn't fit, so put as much on the screen as possible.
x = allowedRect.left;
} else {
if (offLeftSide(x)) {
// If the parent is a different orientation than the current one, then
// just push it over instead of trying the other side.
if (parentOrientation != orientation) {
x = allowedRect.left;
} else {
final double newX = anchorRect.right + alignmentOffset.dx;
if (!offRightSide(newX)) {
x = newX;
} else {
x = allowedRect.left;
}
}
} else if (offRightSide(x)) {
if (parentOrientation != orientation) {
x = allowedRect.right - childSize.width;
} else {
final double newX = anchorRect.left - childSize.width - alignmentOffset.dx;
if (!offLeftSide(newX)) {
x = newX;
} else {
x = allowedRect.right - childSize.width;
}
}
}
}
if (childSize.height >= allowedRect.height) {
// Too tall to fit, fit as much on as possible.
y = allowedRect.top;
} else {
if (offTop(y)) {
final double newY = anchorRect.bottom;
if (!offBottom(newY)) {
y = newY;
} else {
y = allowedRect.top;
}
} else if (offBottom(y)) {
final double newY = anchorRect.top - childSize.height;
if (!offTop(newY)) {
// Only move the menu up if its parent is horizontal (MenuAnchor/MenuBar).
if (parentOrientation == Axis.horizontal) {
y = newY - alignmentOffset.dy;
} else {
y = newY;
}
} else {
y = allowedRect.bottom - childSize.height;
}
}
}
return Offset(x, y);
}
@override
bool shouldRelayout(_MenuLayout oldDelegate) {
return anchorRect != oldDelegate.anchorRect
|| textDirection != oldDelegate.textDirection
|| alignment != oldDelegate.alignment
|| alignmentOffset != oldDelegate.alignmentOffset
|| menuPosition != oldDelegate.menuPosition
|| menuPadding != oldDelegate.menuPadding
|| orientation != oldDelegate.orientation
|| parentOrientation != oldDelegate.parentOrientation
|| !setEquals(avoidBounds, oldDelegate.avoidBounds);
}
Rect _closestScreen(Iterable<Rect> screens, Offset point) {
Rect closest = screens.first;
for (final Rect screen in screens) {
if ((screen.center - point).distance < (closest.center - point).distance) {
closest = screen;
}
}
return closest;
}
}
/// A widget that manages a list of menu buttons in a menu.
///
/// It sizes itself to the widest/tallest item it contains, and then sizes all
/// the other entries to match.
class _MenuPanel extends StatefulWidget {
const _MenuPanel({
required this.menuStyle,
this.clipBehavior = Clip.none,
required this.orientation,
this.crossAxisUnconstrained = true,
required this.children,
});
/// The menu style that has all the attributes for this menu panel.
final MenuStyle? menuStyle;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.none].
final Clip clipBehavior;
/// Determine if a [UnconstrainedBox] can be applied to the menu panel to allow it to render
/// at its "natural" size.
///
/// Defaults to true. When it is set to false, it can be useful when the menu should
/// be constrained in both main-axis and cross-axis, such as a [DropdownMenu].
final bool crossAxisUnconstrained;
/// The layout orientation of this panel.
final Axis orientation;
/// The list of widgets to use as children of this menu bar.
///
/// These are the top level [SubmenuButton]s.
final List<Widget> children;
@override
State<_MenuPanel> createState() => _MenuPanelState();
}
class _MenuPanelState extends State<_MenuPanel> {
ScrollController scrollController = ScrollController();
@override
Widget build(BuildContext context) {
final (MenuStyle? themeStyle, MenuStyle defaultStyle) = switch (widget.orientation) {
Axis.horizontal => (MenuBarTheme.of(context).style, _MenuBarDefaultsM3(context)),
Axis.vertical => (MenuTheme.of(context).style, _MenuDefaultsM3(context)),
};
final MenuStyle? widgetStyle = widget.menuStyle;
T? effectiveValue<T>(T? Function(MenuStyle? style) getProperty) {
return getProperty(widgetStyle) ?? getProperty(themeStyle) ?? getProperty(defaultStyle);
}
T? resolve<T>(MaterialStateProperty<T>? Function(MenuStyle? style) getProperty) {
return effectiveValue(
(MenuStyle? style) {
return getProperty(style)?.resolve(<MaterialState>{});
},
);
}
final Color? backgroundColor = resolve<Color?>((MenuStyle? style) => style?.backgroundColor);
final Color? shadowColor = resolve<Color?>((MenuStyle? style) => style?.shadowColor);
final Color? surfaceTintColor = resolve<Color?>((MenuStyle? style) => style?.surfaceTintColor);
final double elevation = resolve<double?>((MenuStyle? style) => style?.elevation) ?? 0;
final Size? minimumSize = resolve<Size?>((MenuStyle? style) => style?.minimumSize);
final Size? fixedSize = resolve<Size?>((MenuStyle? style) => style?.fixedSize);
final Size? maximumSize = resolve<Size?>((MenuStyle? style) => style?.maximumSize);
final BorderSide? side = resolve<BorderSide?>((MenuStyle? style) => style?.side);
final OutlinedBorder shape = resolve<OutlinedBorder?>((MenuStyle? style) => style?.shape)!.copyWith(side: side);
final VisualDensity visualDensity =
effectiveValue((MenuStyle? style) => style?.visualDensity) ?? VisualDensity.standard;
final EdgeInsetsGeometry padding =
resolve<EdgeInsetsGeometry?>((MenuStyle? style) => style?.padding) ?? EdgeInsets.zero;
final Offset densityAdjustment = visualDensity.baseSizeAdjustment;
// Per the Material Design team: don't allow the VisualDensity
// adjustment to reduce the width of the left/right padding. If we
// did, VisualDensity.compact, the default for desktop/web, would
// reduce the horizontal padding to zero.
final double dy = densityAdjustment.dy;
final double dx = math.max(0, densityAdjustment.dx);
final EdgeInsetsGeometry resolvedPadding = padding
.add(EdgeInsets.symmetric(horizontal: dx, vertical: dy))
.clamp(EdgeInsets.zero, EdgeInsetsGeometry.infinity);
BoxConstraints effectiveConstraints = visualDensity.effectiveConstraints(
BoxConstraints(
minWidth: minimumSize?.width ?? 0,
minHeight: minimumSize?.height ?? 0,
maxWidth: maximumSize?.width ?? double.infinity,
maxHeight: maximumSize?.height ?? double.infinity,
),
);
if (fixedSize != null) {
final Size size = effectiveConstraints.constrain(fixedSize);
if (size.width.isFinite) {
effectiveConstraints = effectiveConstraints.copyWith(
minWidth: size.width,
maxWidth: size.width,
);
}
if (size.height.isFinite) {
effectiveConstraints = effectiveConstraints.copyWith(
minHeight: size.height,
maxHeight: size.height,
);
}
}
Widget menuPanel = _intrinsicCrossSize(
child: Material(
elevation: elevation,
shape: shape,
color: backgroundColor,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
type: backgroundColor == null ? MaterialType.transparency : MaterialType.canvas,
clipBehavior: widget.clipBehavior,
child: Padding(
padding: resolvedPadding,
child: ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(
scrollbars: false,
overscroll: false,
physics: const ClampingScrollPhysics(),
),
child: PrimaryScrollController(
controller: scrollController,
child: Scrollbar(
thumbVisibility: true,
child: SingleChildScrollView(
controller: scrollController,
scrollDirection: widget.orientation,
child: Flex(
crossAxisAlignment: CrossAxisAlignment.start,
textDirection: Directionality.of(context),
direction: widget.orientation,
mainAxisSize: MainAxisSize.min,
children: widget.children,
),
),
),
),
),
),
),
);
if (widget.crossAxisUnconstrained) {
menuPanel = UnconstrainedBox(
constrainedAxis: widget.orientation,
clipBehavior: Clip.hardEdge,
alignment: AlignmentDirectional.centerStart,
child: menuPanel,
);
}
return ConstrainedBox(
constraints: effectiveConstraints,
child: menuPanel,
);
}
Widget _intrinsicCrossSize({required Widget child}) {
return switch (widget.orientation) {
Axis.horizontal => IntrinsicHeight(child: child),
Axis.vertical => IntrinsicWidth(child: child),
};
}
}
// A widget that defines the menu drawn in the overlay.
class _Submenu extends StatelessWidget {
const _Submenu({
required this.anchor,
required this.menuStyle,
required this.menuPosition,
required this.alignmentOffset,
required this.clipBehavior,
this.crossAxisUnconstrained = true,
required this.menuChildren,
});
final _MenuAnchorState anchor;
final MenuStyle? menuStyle;
final Offset? menuPosition;
final Offset alignmentOffset;
final Clip clipBehavior;
final bool crossAxisUnconstrained;
final List<Widget> menuChildren;
@override
Widget build(BuildContext context) {
// Use the text direction of the context where the button is.
final TextDirection textDirection = Directionality.of(context);
final (MenuStyle? themeStyle, MenuStyle defaultStyle) = switch (anchor._parent?._orientation) {
Axis.horizontal || null => (MenuBarTheme.of(context).style, _MenuBarDefaultsM3(context)),
Axis.vertical => (MenuTheme.of(context).style, _MenuDefaultsM3(context)),
};
T? effectiveValue<T>(T? Function(MenuStyle? style) getProperty) {
return getProperty(menuStyle) ?? getProperty(themeStyle) ?? getProperty(defaultStyle);
}
T? resolve<T>(MaterialStateProperty<T>? Function(MenuStyle? style) getProperty) {
return effectiveValue(
(MenuStyle? style) {
return getProperty(style)?.resolve(<MaterialState>{});
},
);
}
final MaterialStateMouseCursor mouseCursor = _MouseCursor(
(Set<MaterialState> states) => effectiveValue((MenuStyle? style) => style?.mouseCursor?.resolve(states)),
);
final VisualDensity visualDensity =
effectiveValue((MenuStyle? style) => style?.visualDensity) ?? Theme.of(context).visualDensity;
final AlignmentGeometry alignment = effectiveValue((MenuStyle? style) => style?.alignment)!;
final BuildContext anchorContext = anchor._anchorKey.currentContext!;
final RenderBox overlay = Overlay.of(anchorContext).context.findRenderObject()! as RenderBox;
final RenderBox anchorBox = anchorContext.findRenderObject()! as RenderBox;
final Offset upperLeft = anchorBox.localToGlobal(Offset.zero, ancestor: overlay);
final Offset bottomRight = anchorBox.localToGlobal(anchorBox.paintBounds.bottomRight, ancestor: overlay);
final Rect anchorRect = Rect.fromPoints(upperLeft, bottomRight);
final EdgeInsetsGeometry padding =
resolve<EdgeInsetsGeometry?>((MenuStyle? style) => style?.padding) ?? EdgeInsets.zero;
final Offset densityAdjustment = visualDensity.baseSizeAdjustment;
// Per the Material Design team: don't allow the VisualDensity
// adjustment to reduce the width of the left/right padding. If we
// did, VisualDensity.compact, the default for desktop/web, would
// reduce the horizontal padding to zero.
final double dy = densityAdjustment.dy;
final double dx = math.max(0, densityAdjustment.dx);
final EdgeInsetsGeometry resolvedPadding = padding
.add(EdgeInsets.fromLTRB(dx, dy, dx, dy))
.clamp(EdgeInsets.zero, EdgeInsetsGeometry.infinity);
return Theme(
data: Theme.of(context).copyWith(
visualDensity: visualDensity,
),
child: ConstrainedBox(
constraints: BoxConstraints.loose(overlay.paintBounds.size),
child: CustomSingleChildLayout(
delegate: _MenuLayout(
anchorRect: anchorRect,
textDirection: textDirection,
avoidBounds: DisplayFeatureSubScreen.avoidBounds(MediaQuery.of(context)).toSet(),
menuPadding: resolvedPadding,
alignment: alignment,
alignmentOffset: alignmentOffset,
menuPosition: menuPosition,
orientation: anchor._orientation,
parentOrientation: anchor._parent?._orientation ?? Axis.horizontal,
),
child: TapRegion(
groupId: anchor._root,
consumeOutsideTaps: anchor._root._isOpen && anchor.widget.consumeOutsideTap,
onTapOutside: (PointerDownEvent event) {
anchor._close();
},
child: MouseRegion(
cursor: mouseCursor,
hitTestBehavior: HitTestBehavior.deferToChild,
child: FocusScope(
node: anchor._menuScopeNode,
skipTraversal: true,
child: Actions(
actions: <Type, Action<Intent>>{
DirectionalFocusIntent: _MenuDirectionalFocusAction(),
DismissIntent: DismissMenuAction(controller: anchor._menuController),
},
child: Shortcuts(
shortcuts: _kMenuTraversalShortcuts,
child: _MenuPanel(
menuStyle: menuStyle,
clipBehavior: clipBehavior,
orientation: anchor._orientation,
crossAxisUnconstrained: crossAxisUnconstrained,
children: menuChildren,
),
),
),
),
),
),
),
),
);
}
}
/// Wraps the [MaterialStateMouseCursor] so that it can default to
/// [MouseCursor.uncontrolled] if none is set.
class _MouseCursor extends MaterialStateMouseCursor {
const _MouseCursor(this.resolveCallback);
final MaterialPropertyResolver<MouseCursor?> resolveCallback;
@override
MouseCursor resolve(Set<MaterialState> states) => resolveCallback(states) ?? MouseCursor.uncontrolled;
@override
String get debugDescription => 'Menu_MouseCursor';
}
/// A debug print function, which should only be called within an assert, like
/// so:
///
/// assert(_debugMenuInfo('Debug Message'));
///
/// so that the call is entirely removed in release builds.
///
/// Enable debug printing by setting [_kDebugMenus] to true at the top of the
/// file.
bool _debugMenuInfo(String message, [Iterable<String>? details]) {
assert(() {
if (_kDebugMenus) {
debugPrint('MENU: $message');
if (details != null && details.isNotEmpty) {
for (final String detail in details) {
debugPrint(' $detail');
}
}
}
return true;
}());
// Return true so that it can be easily used inside of an assert.
return true;
}
/// Whether [defaultTargetPlatform] is an Apple platform (Mac or iOS).
bool get _isApple {
switch (defaultTargetPlatform) {
case TargetPlatform.iOS:
case TargetPlatform.macOS:
return true;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
return false;
}
}
/// Whether [defaultTargetPlatform] is one that uses symbolic shortcuts.
///
/// Mac and iOS use special symbols for modifier keys instead of their names,
/// render them in a particular order defined by Apple's human interface
/// guidelines, and format them so that the modifier keys always align.
bool get _usesSymbolicModifiers {
return _isApple;
}
bool get _platformSupportsAccelerators {
// On iOS and macOS, pressing the Option key (a.k.a. the Alt key) causes a
// different set of characters to be generated, and the native menus don't
// support accelerators anyhow, so we just disable accelerators on these
// platforms.
return !_isApple;
}
// BEGIN GENERATED TOKEN PROPERTIES - Menu
// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
// dev/tools/gen_defaults/bin/gen_defaults.dart.
class _MenuBarDefaultsM3 extends MenuStyle {
_MenuBarDefaultsM3(this.context)
: super(
elevation: const MaterialStatePropertyAll<double?>(3.0),
shape: const MaterialStatePropertyAll<OutlinedBorder>(_defaultMenuBorder),
alignment: AlignmentDirectional.bottomStart,
);
static const RoundedRectangleBorder _defaultMenuBorder =
RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0)));
final BuildContext context;
late final ColorScheme _colors = Theme.of(context).colorScheme;
@override
MaterialStateProperty<Color?> get backgroundColor {
return MaterialStatePropertyAll<Color?>(_colors.surfaceContainer);
}
@override
MaterialStateProperty<Color?>? get shadowColor {
return MaterialStatePropertyAll<Color?>(_colors.shadow);
}
@override
MaterialStateProperty<Color?>? get surfaceTintColor {
return const MaterialStatePropertyAll<Color?>(Colors.transparent);
}
@override
MaterialStateProperty<EdgeInsetsGeometry?>? get padding {
return const MaterialStatePropertyAll<EdgeInsetsGeometry>(
EdgeInsetsDirectional.symmetric(
horizontal: _kTopLevelMenuHorizontalMinPadding
),
);
}
@override
VisualDensity get visualDensity => Theme.of(context).visualDensity;
}
class _MenuButtonDefaultsM3 extends ButtonStyle {
_MenuButtonDefaultsM3(this.context)
: super(
animationDuration: kThemeChangeDuration,
enableFeedback: true,
alignment: AlignmentDirectional.centerStart,
);
final BuildContext context;
late final ColorScheme _colors = Theme.of(context).colorScheme;
late final TextTheme _textTheme = Theme.of(context).textTheme;
@override
MaterialStateProperty<Color?>? get backgroundColor {
return ButtonStyleButton.allOrNull<Color>(Colors.transparent);
}
// No default shadow color
// No default surface tint color
@override
MaterialStateProperty<double>? get elevation {
return ButtonStyleButton.allOrNull<double>(0.0);
}
@override
MaterialStateProperty<Color?>? get foregroundColor {
return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return _colors.onSurface.withOpacity(0.38);
}
if (states.contains(MaterialState.pressed)) {
return _colors.onSurface;
}
if (states.contains(MaterialState.hovered)) {
return _colors.onSurface;
}
if (states.contains(MaterialState.focused)) {
return _colors.onSurface;
}
return _colors.onSurface;
});
}
@override
MaterialStateProperty<Color?>? get iconColor {
return MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return _colors.onSurface.withOpacity(0.38);
}
if (states.contains(MaterialState.pressed)) {
return _colors.onSurfaceVariant;
}
if (states.contains(MaterialState.hovered)) {
return _colors.onSurfaceVariant;
}
if (states.contains(MaterialState.focused)) {
return _colors.onSurfaceVariant;
}
return _colors.onSurfaceVariant;
});
}
// No default fixedSize
@override
MaterialStateProperty<Size>? get maximumSize {
return ButtonStyleButton.allOrNull<Size>(Size.infinite);
}
@override
MaterialStateProperty<Size>? get minimumSize {
return ButtonStyleButton.allOrNull<Size>(const Size(64.0, 48.0));
}
@override
MaterialStateProperty<MouseCursor?>? get mouseCursor {
return MaterialStateProperty.resolveWith(
(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return SystemMouseCursors.basic;
}
return SystemMouseCursors.click;
},
);
}
@override
MaterialStateProperty<Color?>? get overlayColor {
return MaterialStateProperty.resolveWith(
(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return _colors.onSurface.withOpacity(0.1);
}
if (states.contains(MaterialState.hovered)) {
return _colors.onSurface.withOpacity(0.08);
}
if (states.contains(MaterialState.focused)) {
return _colors.onSurface.withOpacity(0.1);
}
return Colors.transparent;
},
);
}
@override
MaterialStateProperty<EdgeInsetsGeometry>? get padding {
return ButtonStyleButton.allOrNull<EdgeInsetsGeometry>(_scaledPadding(context));
}
// No default side
@override
MaterialStateProperty<OutlinedBorder>? get shape {
return ButtonStyleButton.allOrNull<OutlinedBorder>(const RoundedRectangleBorder());
}
@override
InteractiveInkFeatureFactory? get splashFactory => Theme.of(context).splashFactory;
@override
MaterialTapTargetSize? get tapTargetSize => Theme.of(context).materialTapTargetSize;
@override
MaterialStateProperty<TextStyle?> get textStyle {
// TODO(tahatesser): This is taken from https://m3.material.io/components/menus/specs
// Update this when the token is available.
return MaterialStatePropertyAll<TextStyle?>(_textTheme.labelLarge);
}
@override
VisualDensity? get visualDensity => Theme.of(context).visualDensity;
// The horizontal padding number comes from the spec.
EdgeInsetsGeometry _scaledPadding(BuildContext context) {
VisualDensity visualDensity = Theme.of(context).visualDensity;
// When horizontal VisualDensity is greater than zero, set it to zero
// because the [ButtonStyleButton] has already handle the padding based on the density.
// However, the [ButtonStyleButton] doesn't allow the [VisualDensity] adjustment
// to reduce the width of the left/right padding, so we need to handle it here if
// the density is less than zero, such as on desktop platforms.
if (visualDensity.horizontal > 0) {
visualDensity = VisualDensity(vertical: visualDensity.vertical);
}
// Since the threshold paddings used below are empirical values determined
// at a font size of 14.0, 14.0 is used as the base value for scaling the
// padding.
final double fontSize = Theme.of(context).textTheme.labelLarge?.fontSize ?? 14.0;
final double fontSizeRatio = MediaQuery.textScalerOf(context).scale(fontSize) / 14.0;
return ButtonStyleButton.scaledPadding(
EdgeInsets.symmetric(horizontal: math.max(
_kMenuViewPadding,
_kLabelItemDefaultSpacing + visualDensity.baseSizeAdjustment.dx,
)),
EdgeInsets.symmetric(horizontal: math.max(
_kMenuViewPadding,
8 + visualDensity.baseSizeAdjustment.dx,
)),
const EdgeInsets.symmetric(horizontal: _kMenuViewPadding),
fontSizeRatio,
);
}
}
class _MenuDefaultsM3 extends MenuStyle {
_MenuDefaultsM3(this.context)
: super(
elevation: const MaterialStatePropertyAll<double?>(3.0),
shape: const MaterialStatePropertyAll<OutlinedBorder>(_defaultMenuBorder),
alignment: AlignmentDirectional.topEnd,
);
static const RoundedRectangleBorder _defaultMenuBorder =
RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0)));
final BuildContext context;
late final ColorScheme _colors = Theme.of(context).colorScheme;
@override
MaterialStateProperty<Color?> get backgroundColor {
return MaterialStatePropertyAll<Color?>(_colors.surfaceContainer);
}
@override
MaterialStateProperty<Color?>? get surfaceTintColor {
return const MaterialStatePropertyAll<Color?>(Colors.transparent);
}
@override
MaterialStateProperty<Color?>? get shadowColor {
return MaterialStatePropertyAll<Color?>(_colors.shadow);
}
@override
MaterialStateProperty<EdgeInsetsGeometry?>? get padding {
return const MaterialStatePropertyAll<EdgeInsetsGeometry>(
EdgeInsetsDirectional.symmetric(vertical: _kMenuVerticalMinPadding),
);
}
@override
VisualDensity get visualDensity => Theme.of(context).visualDensity;
}
// END GENERATED TOKEN PROPERTIES - Menu
| flutter/packages/flutter/lib/src/material/menu_anchor.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/menu_anchor.dart",
"repo_id": "flutter",
"token_count": 49560
} | 802 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'page_transitions_theme.dart';
import 'theme.dart';
/// A modal route that replaces the entire screen with a platform-adaptive
/// transition.
///
/// {@macro flutter.material.materialRouteTransitionMixin}
///
/// By default, when a modal route is replaced by another, the previous route
/// remains in memory. To free all the resources when this is not necessary, set
/// [maintainState] to false.
///
/// The `fullscreenDialog` property specifies whether the incoming route is a
/// fullscreen modal dialog. On iOS, those routes animate from the bottom to the
/// top rather than horizontally.
///
/// If `barrierDismissible` is true, then pressing the escape key on the keyboard
/// will cause the current route to be popped with null as the value.
///
/// The type `T` specifies the return type of the route which can be supplied as
/// the route is popped from the stack via [Navigator.pop] by providing the
/// optional `result` argument.
///
/// See also:
///
/// * [MaterialRouteTransitionMixin], which provides the material transition
/// for this route.
/// * [MaterialPage], which is a [Page] of this class.
class MaterialPageRoute<T> extends PageRoute<T> with MaterialRouteTransitionMixin<T> {
/// Construct a MaterialPageRoute whose contents are defined by [builder].
MaterialPageRoute({
required this.builder,
super.settings,
this.maintainState = true,
super.fullscreenDialog,
super.allowSnapshotting = true,
super.barrierDismissible = false,
}) {
assert(opaque);
}
/// Builds the primary contents of the route.
final WidgetBuilder builder;
@override
Widget buildContent(BuildContext context) => builder(context);
@override
final bool maintainState;
@override
String get debugLabel => '${super.debugLabel}(${settings.name})';
}
/// A mixin that provides platform-adaptive transitions for a [PageRoute].
///
/// {@template flutter.material.materialRouteTransitionMixin}
/// For Android, the entrance transition for the page zooms in and fades in
/// while the exiting page zooms out and fades out. The exit transition is similar,
/// but in reverse.
///
/// For iOS, the page slides in from the right and exits in reverse. The page
/// also shifts to the left in parallax when another page enters to cover it.
/// (These directions are flipped in environments with a right-to-left reading
/// direction.)
/// {@endtemplate}
///
/// See also:
///
/// * [PageTransitionsTheme], which defines the default page transitions used
/// by the [MaterialRouteTransitionMixin.buildTransitions].
/// * [ZoomPageTransitionsBuilder], which is the default page transition used
/// by the [PageTransitionsTheme].
/// * [CupertinoPageTransitionsBuilder], which is the default page transition
/// for iOS and macOS.
mixin MaterialRouteTransitionMixin<T> on PageRoute<T> {
/// Builds the primary contents of the route.
@protected
Widget buildContent(BuildContext context);
@override
Duration get transitionDuration => const Duration(milliseconds: 300);
@override
Color? get barrierColor => null;
@override
String? get barrierLabel => null;
@override
bool canTransitionTo(TransitionRoute<dynamic> nextRoute) {
// Don't perform outgoing animation if the next route is a fullscreen dialog.
return (nextRoute is MaterialRouteTransitionMixin && !nextRoute.fullscreenDialog)
|| (nextRoute is CupertinoRouteTransitionMixin && !nextRoute.fullscreenDialog);
}
@override
Widget buildPage(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) {
final Widget result = buildContent(context);
return Semantics(
scopesRoute: true,
explicitChildNodes: true,
child: result,
);
}
@override
Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
final PageTransitionsTheme theme = Theme.of(context).pageTransitionsTheme;
return theme.buildTransitions<T>(this, context, animation, secondaryAnimation, child);
}
}
/// A page that creates a material style [PageRoute].
///
/// {@macro flutter.material.materialRouteTransitionMixin}
///
/// By default, when the created route is replaced by another, the previous
/// route remains in memory. To free all the resources when this is not
/// necessary, set [maintainState] to false.
///
/// The `fullscreenDialog` property specifies whether the created route is a
/// fullscreen modal dialog. On iOS, those routes animate from the bottom to the
/// top rather than horizontally.
///
/// The type `T` specifies the return type of the route which can be supplied as
/// the route is popped from the stack via [Navigator.transitionDelegate] by
/// providing the optional `result` argument to the
/// [RouteTransitionRecord.markForPop] in the [TransitionDelegate.resolve].
///
/// See also:
///
/// * [MaterialPageRoute], which is the [PageRoute] version of this class
class MaterialPage<T> extends Page<T> {
/// Creates a material page.
const MaterialPage({
required this.child,
this.maintainState = true,
this.fullscreenDialog = false,
this.allowSnapshotting = true,
super.key,
super.name,
super.arguments,
super.restorationId,
});
/// The content to be shown in the [Route] created by this page.
final Widget child;
/// {@macro flutter.widgets.ModalRoute.maintainState}
final bool maintainState;
/// {@macro flutter.widgets.PageRoute.fullscreenDialog}
final bool fullscreenDialog;
/// {@macro flutter.widgets.TransitionRoute.allowSnapshotting}
final bool allowSnapshotting;
@override
Route<T> createRoute(BuildContext context) {
return _PageBasedMaterialPageRoute<T>(page: this, allowSnapshotting: allowSnapshotting);
}
}
// A page-based version of MaterialPageRoute.
//
// This route uses the builder from the page to build its content. This ensures
// the content is up to date after page updates.
class _PageBasedMaterialPageRoute<T> extends PageRoute<T> with MaterialRouteTransitionMixin<T> {
_PageBasedMaterialPageRoute({
required MaterialPage<T> page,
super.allowSnapshotting,
}) : super(settings: page) {
assert(opaque);
}
MaterialPage<T> get _page => settings as MaterialPage<T>;
@override
Widget buildContent(BuildContext context) {
return _page.child;
}
@override
bool get maintainState => _page.maintainState;
@override
bool get fullscreenDialog => _page.fullscreenDialog;
@override
String get debugLabel => '${super.debugLabel}(${_page.name})';
}
| flutter/packages/flutter/lib/src/material/page.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/page.dart",
"repo_id": "flutter",
"token_count": 1960
} | 803 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'app_bar.dart';
import 'app_bar_theme.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'debug.dart';
import 'input_border.dart';
import 'input_decorator.dart';
import 'material_localizations.dart';
import 'scaffold.dart';
import 'text_field.dart';
import 'theme.dart';
/// Shows a full screen search page and returns the search result selected by
/// the user when the page is closed.
///
/// The search page consists of an app bar with a search field and a body which
/// can either show suggested search queries or the search results.
///
/// The appearance of the search page is determined by the provided
/// `delegate`. The initial query string is given by `query`, which defaults
/// to the empty string. When `query` is set to null, `delegate.query` will
/// be used as the initial query.
///
/// This method returns the selected search result, which can be set in the
/// [SearchDelegate.close] call. If the search page is closed with the system
/// back button, it returns null.
///
/// A given [SearchDelegate] can only be associated with one active [showSearch]
/// call. Call [SearchDelegate.close] before re-using the same delegate instance
/// for another [showSearch] call.
///
/// The `useRootNavigator` argument is used to determine whether to push the
/// search page to the [Navigator] furthest from or nearest to the given
/// `context`. By default, `useRootNavigator` is `false` and the search page
/// route created by this method is pushed to the nearest navigator to the
/// given `context`. It can not be `null`.
///
/// The transition to the search page triggered by this method looks best if the
/// screen triggering the transition contains an [AppBar] at the top and the
/// transition is called from an [IconButton] that's part of [AppBar.actions].
/// The animation provided by [SearchDelegate.transitionAnimation] can be used
/// to trigger additional animations in the underlying page while the search
/// page fades in or out. This is commonly used to animate an [AnimatedIcon] in
/// the [AppBar.leading] position e.g. from the hamburger menu to the back arrow
/// used to exit the search page.
///
/// ## Handling emojis and other complex characters
/// {@macro flutter.widgets.EditableText.onChanged}
///
/// See also:
///
/// * [SearchDelegate] to define the content of the search page.
Future<T?> showSearch<T>({
required BuildContext context,
required SearchDelegate<T> delegate,
String? query = '',
bool useRootNavigator = false,
}) {
delegate.query = query ?? delegate.query;
delegate._currentBody = _SearchBody.suggestions;
return Navigator.of(context, rootNavigator: useRootNavigator).push(_SearchPageRoute<T>(
delegate: delegate,
));
}
/// Delegate for [showSearch] to define the content of the search page.
///
/// The search page always shows an [AppBar] at the top where users can
/// enter their search queries. The buttons shown before and after the search
/// query text field can be customized via [SearchDelegate.buildLeading]
/// and [SearchDelegate.buildActions]. Additionally, a widget can be placed
/// across the bottom of the [AppBar] via [SearchDelegate.buildBottom].
///
/// The body below the [AppBar] can either show suggested queries (returned by
/// [SearchDelegate.buildSuggestions]) or - once the user submits a search - the
/// results of the search as returned by [SearchDelegate.buildResults].
///
/// [SearchDelegate.query] always contains the current query entered by the user
/// and should be used to build the suggestions and results.
///
/// The results can be brought on screen by calling [SearchDelegate.showResults]
/// and you can go back to showing the suggestions by calling
/// [SearchDelegate.showSuggestions].
///
/// Once the user has selected a search result, [SearchDelegate.close] should be
/// called to remove the search page from the top of the navigation stack and
/// to notify the caller of [showSearch] about the selected search result.
///
/// A given [SearchDelegate] can only be associated with one active [showSearch]
/// call. Call [SearchDelegate.close] before re-using the same delegate instance
/// for another [showSearch] call.
///
/// ## Handling emojis and other complex characters
/// {@macro flutter.widgets.EditableText.onChanged}
abstract class SearchDelegate<T> {
/// Constructor to be called by subclasses which may specify
/// [searchFieldLabel], either [searchFieldStyle] or [searchFieldDecorationTheme],
/// [keyboardType] and/or [textInputAction]. Only one of [searchFieldLabel]
/// and [searchFieldDecorationTheme] may be non-null.
///
/// {@tool snippet}
/// ```dart
/// class CustomSearchHintDelegate extends SearchDelegate<String> {
/// CustomSearchHintDelegate({
/// required String hintText,
/// }) : super(
/// searchFieldLabel: hintText,
/// keyboardType: TextInputType.text,
/// textInputAction: TextInputAction.search,
/// );
///
/// @override
/// Widget buildLeading(BuildContext context) => const Text('leading');
///
/// @override
/// PreferredSizeWidget buildBottom(BuildContext context) {
/// return const PreferredSize(
/// preferredSize: Size.fromHeight(56.0),
/// child: Text('bottom'));
/// }
///
/// @override
/// Widget buildSuggestions(BuildContext context) => const Text('suggestions');
///
/// @override
/// Widget buildResults(BuildContext context) => const Text('results');
///
/// @override
/// List<Widget> buildActions(BuildContext context) => <Widget>[];
/// }
/// ```
/// {@end-tool}
SearchDelegate({
this.searchFieldLabel,
this.searchFieldStyle,
this.searchFieldDecorationTheme,
this.keyboardType,
this.textInputAction = TextInputAction.search,
}) : assert(searchFieldStyle == null || searchFieldDecorationTheme == null);
/// Suggestions shown in the body of the search page while the user types a
/// query into the search field.
///
/// The delegate method is called whenever the content of [query] changes.
/// The suggestions should be based on the current [query] string. If the query
/// string is empty, it is good practice to show suggested queries based on
/// past queries or the current context.
///
/// Usually, this method will return a [ListView] with one [ListTile] per
/// suggestion. When [ListTile.onTap] is called, [query] should be updated
/// with the corresponding suggestion and the results page should be shown
/// by calling [showResults].
Widget buildSuggestions(BuildContext context);
/// The results shown after the user submits a search from the search page.
///
/// The current value of [query] can be used to determine what the user
/// searched for.
///
/// This method might be applied more than once to the same query.
/// If your [buildResults] method is computationally expensive, you may want
/// to cache the search results for one or more queries.
///
/// Typically, this method returns a [ListView] with the search results.
/// When the user taps on a particular search result, [close] should be called
/// with the selected result as argument. This will close the search page and
/// communicate the result back to the initial caller of [showSearch].
Widget buildResults(BuildContext context);
/// A widget to display before the current query in the [AppBar].
///
/// Typically an [IconButton] configured with a [BackButtonIcon] that exits
/// the search with [close]. One can also use an [AnimatedIcon] driven by
/// [transitionAnimation], which animates from e.g. a hamburger menu to the
/// back button as the search overlay fades in.
///
/// Returns null if no widget should be shown.
///
/// See also:
///
/// * [AppBar.leading], the intended use for the return value of this method.
Widget? buildLeading(BuildContext context);
/// {@macro flutter.material.appbar.automaticallyImplyLeading}
bool? automaticallyImplyLeading;
/// {@macro flutter.material.appbar.leadingWidth}
double? leadingWidth;
/// Widgets to display after the search query in the [AppBar].
///
/// If the [query] is not empty, this should typically contain a button to
/// clear the query and show the suggestions again (via [showSuggestions]) if
/// the results are currently shown.
///
/// Returns null if no widget should be shown.
///
/// See also:
///
/// * [AppBar.actions], the intended use for the return value of this method.
List<Widget>? buildActions(BuildContext context);
/// Widget to display across the bottom of the [AppBar].
///
/// Returns null by default, i.e. a bottom widget is not included.
///
/// See also:
///
/// * [AppBar.bottom], the intended use for the return value of this method.
///
PreferredSizeWidget? buildBottom(BuildContext context) => null;
/// Widget to display a flexible space in the [AppBar].
///
/// Returns null by default, i.e. a flexible space widget is not included.
///
/// See also:
///
/// * [AppBar.flexibleSpace], the intended use for the return value of this method.
Widget? buildFlexibleSpace(BuildContext context) => null;
/// The theme used to configure the search page.
///
/// The returned [ThemeData] will be used to wrap the entire search page,
/// so it can be used to configure any of its components with the appropriate
/// theme properties.
///
/// Unless overridden, the default theme will configure the AppBar containing
/// the search input text field with a white background and black text on light
/// themes. For dark themes the default is a dark grey background with light
/// color text.
///
/// See also:
///
/// * [AppBarTheme], which configures the AppBar's appearance.
/// * [InputDecorationTheme], which configures the appearance of the search
/// text field.
ThemeData appBarTheme(BuildContext context) {
final ThemeData theme = Theme.of(context);
final ColorScheme colorScheme = theme.colorScheme;
return theme.copyWith(
appBarTheme: AppBarTheme(
systemOverlayStyle: colorScheme.brightness == Brightness.dark
? SystemUiOverlayStyle.light
: SystemUiOverlayStyle.dark,
backgroundColor: colorScheme.brightness == Brightness.dark ? Colors.grey[900] : Colors.white,
iconTheme: theme.primaryIconTheme.copyWith(color: Colors.grey),
titleTextStyle: theme.textTheme.titleLarge,
toolbarTextStyle: theme.textTheme.bodyMedium,
),
inputDecorationTheme: searchFieldDecorationTheme ??
InputDecorationTheme(
hintStyle: searchFieldStyle ?? theme.inputDecorationTheme.hintStyle,
border: InputBorder.none,
),
);
}
/// The current query string shown in the [AppBar].
///
/// The user manipulates this string via the keyboard.
///
/// If the user taps on a suggestion provided by [buildSuggestions] this
/// string should be updated to that suggestion via the setter.
String get query => _queryTextController.text;
/// Changes the current query string.
///
/// Setting the query string programmatically moves the cursor to the end of the text field.
set query(String value) {
_queryTextController.text = value;
if (_queryTextController.text.isNotEmpty) {
_queryTextController.selection = TextSelection.fromPosition(TextPosition(offset: _queryTextController.text.length));
}
}
/// Transition from the suggestions returned by [buildSuggestions] to the
/// [query] results returned by [buildResults].
///
/// If the user taps on a suggestion provided by [buildSuggestions] the
/// screen should typically transition to the page showing the search
/// results for the suggested query. This transition can be triggered
/// by calling this method.
///
/// See also:
///
/// * [showSuggestions] to show the search suggestions again.
void showResults(BuildContext context) {
_focusNode?.unfocus();
_currentBody = _SearchBody.results;
}
/// Transition from showing the results returned by [buildResults] to showing
/// the suggestions returned by [buildSuggestions].
///
/// Calling this method will also put the input focus back into the search
/// field of the [AppBar].
///
/// If the results are currently shown this method can be used to go back
/// to showing the search suggestions.
///
/// See also:
///
/// * [showResults] to show the search results.
void showSuggestions(BuildContext context) {
assert(_focusNode != null, '_focusNode must be set by route before showSuggestions is called.');
_focusNode!.requestFocus();
_currentBody = _SearchBody.suggestions;
}
/// Closes the search page and returns to the underlying route.
///
/// The value provided for `result` is used as the return value of the call
/// to [showSearch] that launched the search initially.
void close(BuildContext context, T result) {
_currentBody = null;
_focusNode?.unfocus();
Navigator.of(context)
..popUntil((Route<dynamic> route) => route == _route)
..pop(result);
}
/// The hint text that is shown in the search field when it is empty.
///
/// If this value is set to null, the value of
/// `MaterialLocalizations.of(context).searchFieldLabel` will be used instead.
final String? searchFieldLabel;
/// The style of the [searchFieldLabel].
///
/// If this value is set to null, the value of the ambient [Theme]'s
/// [InputDecorationTheme.hintStyle] will be used instead.
///
/// Only one of [searchFieldStyle] or [searchFieldDecorationTheme] can
/// be non-null.
final TextStyle? searchFieldStyle;
/// The [InputDecorationTheme] used to configure the search field's visuals.
///
/// Only one of [searchFieldStyle] or [searchFieldDecorationTheme] can
/// be non-null.
final InputDecorationTheme? searchFieldDecorationTheme;
/// The type of action button to use for the keyboard.
///
/// Defaults to the default value specified in [TextField].
final TextInputType? keyboardType;
/// The text input action configuring the soft keyboard to a particular action
/// button.
///
/// Defaults to [TextInputAction.search].
final TextInputAction textInputAction;
/// [Animation] triggered when the search pages fades in or out.
///
/// This animation is commonly used to animate [AnimatedIcon]s of
/// [IconButton]s returned by [buildLeading] or [buildActions]. It can also be
/// used to animate [IconButton]s contained within the route below the search
/// page.
Animation<double> get transitionAnimation => _proxyAnimation;
// The focus node to use for manipulating focus on the search page. This is
// managed, owned, and set by the _SearchPageRoute using this delegate.
FocusNode? _focusNode;
final TextEditingController _queryTextController = TextEditingController();
final ProxyAnimation _proxyAnimation = ProxyAnimation(kAlwaysDismissedAnimation);
final ValueNotifier<_SearchBody?> _currentBodyNotifier = ValueNotifier<_SearchBody?>(null);
_SearchBody? get _currentBody => _currentBodyNotifier.value;
set _currentBody(_SearchBody? value) {
_currentBodyNotifier.value = value;
}
_SearchPageRoute<T>? _route;
/// Releases the resources.
@mustCallSuper
void dispose() {
_currentBodyNotifier.dispose();
_focusNode?.dispose();
_queryTextController.dispose();
_proxyAnimation.parent = null;
}
}
/// Describes the body that is currently shown under the [AppBar] in the
/// search page.
enum _SearchBody {
/// Suggested queries are shown in the body.
///
/// The suggested queries are generated by [SearchDelegate.buildSuggestions].
suggestions,
/// Search results are currently shown in the body.
///
/// The search results are generated by [SearchDelegate.buildResults].
results,
}
class _SearchPageRoute<T> extends PageRoute<T> {
_SearchPageRoute({
required this.delegate,
}) {
assert(
delegate._route == null,
'The ${delegate.runtimeType} instance is currently used by another active '
'search. Please close that search by calling close() on the SearchDelegate '
'before opening another search with the same delegate instance.',
);
delegate._route = this;
}
final SearchDelegate<T> delegate;
@override
Color? get barrierColor => null;
@override
String? get barrierLabel => null;
@override
Duration get transitionDuration => const Duration(milliseconds: 300);
@override
bool get maintainState => false;
@override
Widget buildTransitions(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
Widget child,
) {
return FadeTransition(
opacity: animation,
child: child,
);
}
@override
Animation<double> createAnimation() {
final Animation<double> animation = super.createAnimation();
delegate._proxyAnimation.parent = animation;
return animation;
}
@override
Widget buildPage(
BuildContext context,
Animation<double> animation,
Animation<double> secondaryAnimation,
) {
return _SearchPage<T>(
delegate: delegate,
animation: animation,
);
}
@override
void didComplete(T? result) {
super.didComplete(result);
assert(delegate._route == this);
delegate._route = null;
delegate._currentBody = null;
}
}
class _SearchPage<T> extends StatefulWidget {
const _SearchPage({
required this.delegate,
required this.animation,
});
final SearchDelegate<T> delegate;
final Animation<double> animation;
@override
State<StatefulWidget> createState() => _SearchPageState<T>();
}
class _SearchPageState<T> extends State<_SearchPage<T>> {
// This node is owned, but not hosted by, the search page. Hosting is done by
// the text field.
FocusNode focusNode = FocusNode();
@override
void initState() {
super.initState();
widget.delegate._queryTextController.addListener(_onQueryChanged);
widget.animation.addStatusListener(_onAnimationStatusChanged);
widget.delegate._currentBodyNotifier.addListener(_onSearchBodyChanged);
focusNode.addListener(_onFocusChanged);
widget.delegate._focusNode = focusNode;
}
@override
void dispose() {
super.dispose();
widget.delegate._queryTextController.removeListener(_onQueryChanged);
widget.animation.removeStatusListener(_onAnimationStatusChanged);
widget.delegate._currentBodyNotifier.removeListener(_onSearchBodyChanged);
widget.delegate._focusNode = null;
focusNode.dispose();
}
void _onAnimationStatusChanged(AnimationStatus status) {
if (status != AnimationStatus.completed) {
return;
}
widget.animation.removeStatusListener(_onAnimationStatusChanged);
if (widget.delegate._currentBody == _SearchBody.suggestions) {
focusNode.requestFocus();
}
}
@override
void didUpdateWidget(_SearchPage<T> oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.delegate != oldWidget.delegate) {
oldWidget.delegate._queryTextController.removeListener(_onQueryChanged);
widget.delegate._queryTextController.addListener(_onQueryChanged);
oldWidget.delegate._currentBodyNotifier.removeListener(_onSearchBodyChanged);
widget.delegate._currentBodyNotifier.addListener(_onSearchBodyChanged);
oldWidget.delegate._focusNode = null;
widget.delegate._focusNode = focusNode;
}
}
void _onFocusChanged() {
if (focusNode.hasFocus && widget.delegate._currentBody != _SearchBody.suggestions) {
widget.delegate.showSuggestions(context);
}
}
void _onQueryChanged() {
setState(() {
// rebuild ourselves because query changed.
});
}
void _onSearchBodyChanged() {
setState(() {
// rebuild ourselves because search body changed.
});
}
@override
Widget build(BuildContext context) {
assert(debugCheckHasMaterialLocalizations(context));
final ThemeData theme = widget.delegate.appBarTheme(context);
final String searchFieldLabel = widget.delegate.searchFieldLabel
?? MaterialLocalizations.of(context).searchFieldLabel;
Widget? body;
switch (widget.delegate._currentBody) {
case _SearchBody.suggestions:
body = KeyedSubtree(
key: const ValueKey<_SearchBody>(_SearchBody.suggestions),
child: widget.delegate.buildSuggestions(context),
);
case _SearchBody.results:
body = KeyedSubtree(
key: const ValueKey<_SearchBody>(_SearchBody.results),
child: widget.delegate.buildResults(context),
);
case null:
break;
}
late final String routeName;
switch (theme.platform) {
case TargetPlatform.iOS:
case TargetPlatform.macOS:
routeName = '';
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
routeName = searchFieldLabel;
}
return Semantics(
explicitChildNodes: true,
scopesRoute: true,
namesRoute: true,
label: routeName,
child: Theme(
data: theme,
child: Scaffold(
appBar: AppBar(
leadingWidth: widget.delegate.leadingWidth,
automaticallyImplyLeading: widget.delegate.automaticallyImplyLeading ?? true,
leading: widget.delegate.buildLeading(context),
title: TextField(
controller: widget.delegate._queryTextController,
focusNode: focusNode,
style: widget.delegate.searchFieldStyle ?? theme.textTheme.titleLarge,
textInputAction: widget.delegate.textInputAction,
keyboardType: widget.delegate.keyboardType,
onSubmitted: (String _) => widget.delegate.showResults(context),
decoration: InputDecoration(hintText: searchFieldLabel),
),
flexibleSpace: widget.delegate.buildFlexibleSpace(context),
actions: widget.delegate.buildActions(context),
bottom: widget.delegate.buildBottom(context),
),
body: AnimatedSwitcher(
duration: const Duration(milliseconds: 300),
child: body,
),
),
),
);
}
}
| flutter/packages/flutter/lib/src/material/search.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/search.dart",
"repo_id": "flutter",
"token_count": 6885
} | 804 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'button_style.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'debug.dart';
import 'icons.dart';
import 'ink_well.dart';
import 'material.dart';
import 'material_localizations.dart';
import 'material_state.dart';
import 'text_button.dart';
import 'text_theme.dart';
import 'theme.dart';
// TODO(dragostis): Missing functionality:
// * mobile horizontal mode with adding/removing steps
// * alternative labeling
// * stepper feedback in the case of high-latency interactions
/// The state of a [Step] which is used to control the style of the circle and
/// text.
///
/// See also:
///
/// * [Step]
enum StepState {
/// A step that displays its index in its circle.
indexed,
/// A step that displays a pencil icon in its circle.
editing,
/// A step that displays a tick icon in its circle.
complete,
/// A step that is disabled and does not to react to taps.
disabled,
/// A step that is currently having an error. e.g. the user has submitted wrong
/// input.
error,
}
/// Defines the [Stepper]'s main axis.
enum StepperType {
/// A vertical layout of the steps with their content in-between the titles.
vertical,
/// A horizontal layout of the steps with their content below the titles.
horizontal,
}
/// Container for all the information necessary to build a Stepper widget's
/// forward and backward controls for any given step.
///
/// Used by [Stepper.controlsBuilder].
@immutable
class ControlsDetails {
/// Creates a set of details describing the Stepper.
const ControlsDetails({
required this.currentStep,
required this.stepIndex,
this.onStepCancel,
this.onStepContinue,
});
/// Index that is active for the surrounding [Stepper] widget. This may be
/// different from [stepIndex] if the user has just changed steps and we are
/// currently animating toward that step.
final int currentStep;
/// Index of the step for which these controls are being built. This is
/// not necessarily the active index, if the user has just changed steps and
/// this step is animating away. To determine whether a given builder is building
/// the active step or the step being navigated away from, see [isActive].
final int stepIndex;
/// The callback called when the 'continue' button is tapped.
///
/// If null, the 'continue' button will be disabled.
final VoidCallback? onStepContinue;
/// The callback called when the 'cancel' button is tapped.
///
/// If null, the 'cancel' button will be disabled.
final VoidCallback? onStepCancel;
/// True if the indicated step is also the current active step. If the user has
/// just activated the transition to a new step, some [Stepper.type] values will
/// lead to both steps being rendered for the duration of the animation shifting
/// between steps.
bool get isActive => currentStep == stepIndex;
}
/// A builder that creates a widget given the two callbacks `onStepContinue` and
/// `onStepCancel`.
///
/// Used by [Stepper.controlsBuilder].
///
/// See also:
///
/// * [WidgetBuilder], which is similar but only takes a [BuildContext].
typedef ControlsWidgetBuilder = Widget Function(BuildContext context, ControlsDetails details);
/// A builder that creates the icon widget for the [Step] at [stepIndex], given
/// [stepState].
typedef StepIconBuilder = Widget? Function(int stepIndex, StepState stepState);
const TextStyle _kStepStyle = TextStyle(
fontSize: 12.0,
color: Colors.white,
);
const Color _kErrorLight = Colors.red;
final Color _kErrorDark = Colors.red.shade400;
const Color _kCircleActiveLight = Colors.white;
const Color _kCircleActiveDark = Colors.black87;
const Color _kDisabledLight = Colors.black38;
const Color _kDisabledDark = Colors.white38;
const double _kStepSize = 24.0;
const double _kTriangleSqrt = 0.866025; // sqrt(3.0) / 2.0
const double _kTriangleHeight = _kStepSize * _kTriangleSqrt;
const double _kMaxStepSize = 80.0;
/// A material step used in [Stepper]. The step can have a title and subtitle,
/// an icon within its circle, some content and a state that governs its
/// styling.
///
/// See also:
///
/// * [Stepper]
/// * <https://material.io/archive/guidelines/components/steppers.html>
@immutable
class Step {
/// Creates a step for a [Stepper].
const Step({
required this.title,
this.subtitle,
required this.content,
this.state = StepState.indexed,
this.isActive = false,
this.label,
this.stepStyle,
});
/// The title of the step that typically describes it.
final Widget title;
/// The subtitle of the step that appears below the title and has a smaller
/// font size. It typically gives more details that complement the title.
///
/// If null, the subtitle is not shown.
final Widget? subtitle;
/// The content of the step that appears below the [title] and [subtitle].
///
/// Below the content, every step has a 'continue' and 'cancel' button.
final Widget content;
/// The state of the step which determines the styling of its components
/// and whether steps are interactive.
final StepState state;
/// Whether or not the step is active. The flag only influences styling.
final bool isActive;
/// Only [StepperType.horizontal], Optional widget that appears under the [title].
/// By default, uses the `bodyLarge` theme.
final Widget? label;
/// Optional overrides for the step's default visual configuration.
final StepStyle? stepStyle;
}
/// A material stepper widget that displays progress through a sequence of
/// steps. Steppers are particularly useful in the case of forms where one step
/// requires the completion of another one, or where multiple steps need to be
/// completed in order to submit the whole form.
///
/// The widget is a flexible wrapper. A parent class should pass [currentStep]
/// to this widget based on some logic triggered by the three callbacks that it
/// provides.
///
/// {@tool dartpad}
/// An example the shows how to use the [Stepper], and the [Stepper] UI
/// appearance.
///
/// ** See code in examples/api/lib/material/stepper/stepper.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [Step]
/// * <https://material.io/archive/guidelines/components/steppers.html>
class Stepper extends StatefulWidget {
/// Creates a stepper from a list of steps.
///
/// This widget is not meant to be rebuilt with a different list of steps
/// unless a key is provided in order to distinguish the old stepper from the
/// new one.
const Stepper({
super.key,
required this.steps,
this.controller,
this.physics,
this.type = StepperType.vertical,
this.currentStep = 0,
this.onStepTapped,
this.onStepContinue,
this.onStepCancel,
this.controlsBuilder,
this.elevation,
this.margin,
this.connectorColor,
this.connectorThickness,
this.stepIconBuilder,
this.stepIconHeight,
this.stepIconWidth,
this.stepIconMargin,
}) : assert(0 <= currentStep && currentStep < steps.length),
assert(stepIconHeight == null || (stepIconHeight >= _kStepSize && stepIconHeight <= _kMaxStepSize),
'stepIconHeight must be greater than $_kStepSize and less or equal to $_kMaxStepSize'),
assert(stepIconWidth == null || (stepIconWidth >= _kStepSize && stepIconWidth <= _kMaxStepSize),
'stepIconWidth must be greater than $_kStepSize and less or equal to $_kMaxStepSize'),
assert(
stepIconHeight == null || stepIconWidth == null || stepIconHeight == stepIconWidth,
'If either stepIconHeight or stepIconWidth is specified, both must be specified and '
'the values must be equal.');
/// The steps of the stepper whose titles, subtitles, icons always get shown.
///
/// The length of [steps] must not change.
final List<Step> steps;
/// How the stepper's scroll view should respond to user input.
///
/// For example, determines how the scroll view continues to
/// animate after the user stops dragging the scroll view.
///
/// If the stepper is contained within another scrollable it
/// can be helpful to set this property to [ClampingScrollPhysics].
final ScrollPhysics? physics;
/// An object that can be used to control the position to which this scroll
/// view is scrolled.
///
/// To control the initial scroll offset of the scroll view, provide a
/// [controller] with its [ScrollController.initialScrollOffset] property set.
final ScrollController? controller;
/// The type of stepper that determines the layout. In the case of
/// [StepperType.horizontal], the content of the current step is displayed
/// underneath as opposed to the [StepperType.vertical] case where it is
/// displayed in-between.
final StepperType type;
/// The index into [steps] of the current step whose content is displayed.
final int currentStep;
/// The callback called when a step is tapped, with its index passed as
/// an argument.
final ValueChanged<int>? onStepTapped;
/// The callback called when the 'continue' button is tapped.
///
/// If null, the 'continue' button will be disabled.
final VoidCallback? onStepContinue;
/// The callback called when the 'cancel' button is tapped.
///
/// If null, the 'cancel' button will be disabled.
final VoidCallback? onStepCancel;
/// The callback for creating custom controls.
///
/// If null, the default controls from the current theme will be used.
///
/// This callback which takes in a context and a [ControlsDetails] object, which
/// contains step information and two functions: [onStepContinue] and [onStepCancel].
/// These can be used to control the stepper. For example, reading the
/// [ControlsDetails.currentStep] value within the callback can change the text
/// of the continue or cancel button depending on which step users are at.
///
/// {@tool dartpad}
/// Creates a stepper control with custom buttons.
///
/// ```dart
/// Widget build(BuildContext context) {
/// return Stepper(
/// controlsBuilder:
/// (BuildContext context, ControlsDetails details) {
/// return Row(
/// children: <Widget>[
/// TextButton(
/// onPressed: details.onStepContinue,
/// child: Text('Continue to Step ${details.stepIndex + 1}'),
/// ),
/// TextButton(
/// onPressed: details.onStepCancel,
/// child: Text('Back to Step ${details.stepIndex - 1}'),
/// ),
/// ],
/// );
/// },
/// steps: const <Step>[
/// Step(
/// title: Text('A'),
/// content: SizedBox(
/// width: 100.0,
/// height: 100.0,
/// ),
/// ),
/// Step(
/// title: Text('B'),
/// content: SizedBox(
/// width: 100.0,
/// height: 100.0,
/// ),
/// ),
/// ],
/// );
/// }
/// ```
/// ** See code in examples/api/lib/material/stepper/stepper.controls_builder.0.dart **
/// {@end-tool}
final ControlsWidgetBuilder? controlsBuilder;
/// The elevation of this stepper's [Material] when [type] is [StepperType.horizontal].
final double? elevation;
/// Custom margin on vertical stepper.
final EdgeInsetsGeometry? margin;
/// Customize connected lines colors.
///
/// Resolves in the following states:
/// * [MaterialState.selected].
/// * [MaterialState.disabled].
///
/// If not set then the widget will use default colors, primary for selected state
/// and grey.shade400 for disabled state.
final MaterialStateProperty<Color>? connectorColor;
/// The thickness of the connecting lines.
final double? connectorThickness;
/// Callback for creating custom icons for the [steps].
///
/// When overriding icon for [StepState.error], please return
/// a widget whose width and height are 14 pixels or less to avoid overflow.
///
/// If null, the default icons will be used for respective [StepState].
final StepIconBuilder? stepIconBuilder;
/// Overrides the default step icon size height.
final double? stepIconHeight;
/// Overrides the default step icon size width.
final double? stepIconWidth;
/// Overrides the default step icon margin.
final EdgeInsets? stepIconMargin;
@override
State<Stepper> createState() => _StepperState();
}
class _StepperState extends State<Stepper> with TickerProviderStateMixin {
late List<GlobalKey> _keys;
final Map<int, StepState> _oldStates = <int, StepState>{};
@override
void initState() {
super.initState();
_keys = List<GlobalKey>.generate(
widget.steps.length,
(int i) => GlobalKey(),
);
for (int i = 0; i < widget.steps.length; i += 1) {
_oldStates[i] = widget.steps[i].state;
}
}
@override
void didUpdateWidget(Stepper oldWidget) {
super.didUpdateWidget(oldWidget);
assert(widget.steps.length == oldWidget.steps.length);
for (int i = 0; i < oldWidget.steps.length; i += 1) {
_oldStates[i] = oldWidget.steps[i].state;
}
}
EdgeInsetsGeometry? get _stepIconMargin => widget.stepIconMargin;
double? get _stepIconHeight => widget.stepIconHeight;
double? get _stepIconWidth => widget.stepIconWidth;
double get _heightFactor {
return (_isLabel() && _stepIconHeight != null) ? 2.5 : 2.0;
}
bool _isFirst(int index) {
return index == 0;
}
bool _isLast(int index) {
return widget.steps.length - 1 == index;
}
bool _isCurrent(int index) {
return widget.currentStep == index;
}
bool _isDark() {
return Theme.of(context).brightness == Brightness.dark;
}
bool _isLabel() {
for (final Step step in widget.steps) {
if (step.label != null) {
return true;
}
}
return false;
}
StepStyle? _stepStyle(int index) {
return widget.steps[index].stepStyle;
}
Color _connectorColor(bool isActive) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
final Set<MaterialState> states = <MaterialState>{
if (isActive) MaterialState.selected else MaterialState.disabled,
};
final Color? resolvedConnectorColor = widget.connectorColor?.resolve(states);
return resolvedConnectorColor ?? (isActive ? colorScheme.primary : Colors.grey.shade400);
}
Widget _buildLine(bool visible, bool isActive) {
return Container(
width: visible ? widget.connectorThickness ?? 1.0 : 0.0,
height: 16.0,
color: _connectorColor(isActive),
);
}
Widget _buildCircleChild(int index, bool oldState) {
final StepState state = oldState ? _oldStates[index]! : widget.steps[index].state;
final bool isDarkActive = _isDark() && widget.steps[index].isActive;
final Widget? icon = widget.stepIconBuilder?.call(index, state);
if (icon != null) {
return icon;
}
TextStyle? textStyle = _stepStyle(index)?.indexStyle;
textStyle ??= isDarkActive ? _kStepStyle.copyWith(color: Colors.black87) : _kStepStyle;
switch (state) {
case StepState.indexed:
case StepState.disabled:
return Text(
'${index + 1}',
style: textStyle,
);
case StepState.editing:
return Icon(
Icons.edit,
color: isDarkActive ? _kCircleActiveDark : _kCircleActiveLight,
size: 18.0,
);
case StepState.complete:
return Icon(
Icons.check,
color: isDarkActive ? _kCircleActiveDark : _kCircleActiveLight,
size: 18.0,
);
case StepState.error:
return const Center(child: Text('!', style: _kStepStyle));
}
}
Color _circleColor(int index) {
final bool isActive = widget.steps[index].isActive;
final ColorScheme colorScheme = Theme.of(context).colorScheme;
final Set<MaterialState> states = <MaterialState>{
if (isActive) MaterialState.selected else MaterialState.disabled,
};
final Color? resolvedConnectorColor = widget.connectorColor?.resolve(states);
if (resolvedConnectorColor != null) {
return resolvedConnectorColor;
}
if (!_isDark()) {
return isActive ? colorScheme.primary : colorScheme.onSurface.withOpacity(0.38);
} else {
return isActive ? colorScheme.secondary : colorScheme.background;
}
}
Widget _buildCircle(int index, bool oldState) {
return Container(
margin:_stepIconMargin ?? const EdgeInsets.symmetric(vertical: 8.0),
width: _stepIconWidth ?? _kStepSize,
height: _stepIconHeight ?? _kStepSize,
child: AnimatedContainer(
curve: Curves.fastOutSlowIn,
duration: kThemeAnimationDuration,
decoration: BoxDecoration(
color: _stepStyle(index)?.color ?? _circleColor(index),
shape: BoxShape.circle,
border: _stepStyle(index)?.border,
boxShadow: _stepStyle(index)?.boxShadow != null ? <BoxShadow>[_stepStyle(index)!.boxShadow!] : null,
gradient: _stepStyle(index)?.gradient,
),
child: Center(
child: _buildCircleChild(index, oldState && widget.steps[index].state == StepState.error),
),
),
);
}
Widget _buildTriangle(int index, bool oldState) {
Color? color = _stepStyle(index)?.errorColor;
color ??= _isDark() ? _kErrorDark : _kErrorLight;
return Container(
margin: _stepIconMargin ?? const EdgeInsets.symmetric(vertical: 8.0),
width: _stepIconWidth ?? _kStepSize,
height: _stepIconHeight ?? _kStepSize,
child: Center(
child: SizedBox(
width: _stepIconWidth ?? _kStepSize,
height: _stepIconHeight != null ? _stepIconHeight! * _kTriangleSqrt : _kTriangleHeight,
child: CustomPaint(
painter: _TrianglePainter(
color: color,
),
child: Align(
alignment: const Alignment(0.0, 0.8), // 0.8 looks better than the geometrical 0.33.
child: _buildCircleChild(index, oldState && widget.steps[index].state != StepState.error),
),
),
),
),
);
}
Widget _buildIcon(int index) {
if (widget.steps[index].state != _oldStates[index]) {
return AnimatedCrossFade(
firstChild: _buildCircle(index, true),
secondChild: _buildTriangle(index, true),
firstCurve: const Interval(0.0, 0.6, curve: Curves.fastOutSlowIn),
secondCurve: const Interval(0.4, 1.0, curve: Curves.fastOutSlowIn),
sizeCurve: Curves.fastOutSlowIn,
crossFadeState: widget.steps[index].state == StepState.error ? CrossFadeState.showSecond : CrossFadeState.showFirst,
duration: kThemeAnimationDuration,
);
} else {
if (widget.steps[index].state != StepState.error) {
return _buildCircle(index, false);
} else {
return _buildTriangle(index, false);
}
}
}
Widget _buildVerticalControls(int stepIndex) {
if (widget.controlsBuilder != null) {
return widget.controlsBuilder!(
context,
ControlsDetails(
currentStep: widget.currentStep,
onStepContinue: widget.onStepContinue,
onStepCancel: widget.onStepCancel,
stepIndex: stepIndex,
),
);
}
final Color cancelColor = switch (Theme.of(context).brightness) {
Brightness.light => Colors.black54,
Brightness.dark => Colors.white70,
};
final ThemeData themeData = Theme.of(context);
final ColorScheme colorScheme = themeData.colorScheme;
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
const OutlinedBorder buttonShape = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2)));
const EdgeInsets buttonPadding = EdgeInsets.symmetric(horizontal: 16.0);
return Container(
margin: const EdgeInsets.only(top: 16.0),
child: ConstrainedBox(
constraints: const BoxConstraints.tightFor(height: 48.0),
child: Row(
// The Material spec no longer includes a Stepper widget. The continue
// and cancel button styles have been configured to match the original
// version of this widget.
children: <Widget>[
TextButton(
onPressed: widget.onStepContinue,
style: ButtonStyle(
foregroundColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {
return states.contains(MaterialState.disabled) ? null : (_isDark() ? colorScheme.onSurface : colorScheme.onPrimary);
}),
backgroundColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {
return _isDark() || states.contains(MaterialState.disabled) ? null : colorScheme.primary;
}),
padding: const MaterialStatePropertyAll<EdgeInsetsGeometry>(buttonPadding),
shape: const MaterialStatePropertyAll<OutlinedBorder>(buttonShape),
),
child: Text(
themeData.useMaterial3
? localizations.continueButtonLabel
: localizations.continueButtonLabel.toUpperCase()
),
),
Container(
margin: const EdgeInsetsDirectional.only(start: 8.0),
child: TextButton(
onPressed: widget.onStepCancel,
style: TextButton.styleFrom(
foregroundColor: cancelColor,
padding: buttonPadding,
shape: buttonShape,
),
child: Text(
themeData.useMaterial3
? localizations.cancelButtonLabel
: localizations.cancelButtonLabel.toUpperCase()
),
),
),
],
),
),
);
}
TextStyle _titleStyle(int index) {
final ThemeData themeData = Theme.of(context);
final TextTheme textTheme = themeData.textTheme;
switch (widget.steps[index].state) {
case StepState.indexed:
case StepState.editing:
case StepState.complete:
return textTheme.bodyLarge!;
case StepState.disabled:
return textTheme.bodyLarge!.copyWith(
color: _isDark() ? _kDisabledDark : _kDisabledLight,
);
case StepState.error:
return textTheme.bodyLarge!.copyWith(
color: _isDark() ? _kErrorDark : _kErrorLight,
);
}
}
TextStyle _subtitleStyle(int index) {
final ThemeData themeData = Theme.of(context);
final TextTheme textTheme = themeData.textTheme;
switch (widget.steps[index].state) {
case StepState.indexed:
case StepState.editing:
case StepState.complete:
return textTheme.bodySmall!;
case StepState.disabled:
return textTheme.bodySmall!.copyWith(
color: _isDark() ? _kDisabledDark : _kDisabledLight,
);
case StepState.error:
return textTheme.bodySmall!.copyWith(
color: _isDark() ? _kErrorDark : _kErrorLight,
);
}
}
TextStyle _labelStyle(int index) {
final ThemeData themeData = Theme.of(context);
final TextTheme textTheme = themeData.textTheme;
switch (widget.steps[index].state) {
case StepState.indexed:
case StepState.editing:
case StepState.complete:
return textTheme.bodyLarge!;
case StepState.disabled:
return textTheme.bodyLarge!.copyWith(
color: _isDark() ? _kDisabledDark : _kDisabledLight,
);
case StepState.error:
return textTheme.bodyLarge!.copyWith(
color: _isDark() ? _kErrorDark : _kErrorLight,
);
}
}
Widget _buildHeaderText(int index) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
AnimatedDefaultTextStyle(
style: _titleStyle(index),
duration: kThemeAnimationDuration,
curve: Curves.fastOutSlowIn,
child: widget.steps[index].title,
),
if (widget.steps[index].subtitle != null)
Container(
margin: const EdgeInsets.only(top: 2.0),
child: AnimatedDefaultTextStyle(
style: _subtitleStyle(index),
duration: kThemeAnimationDuration,
curve: Curves.fastOutSlowIn,
child: widget.steps[index].subtitle!,
),
),
],
);
}
Widget _buildLabelText(int index) {
if (widget.steps[index].label != null) {
return AnimatedDefaultTextStyle(
style: _labelStyle(index),
duration: kThemeAnimationDuration,
child: widget.steps[index].label!,
);
}
return const SizedBox.shrink();
}
Widget _buildVerticalHeader(int index) {
final bool isActive = widget.steps[index].isActive;
return Container(
margin: const EdgeInsets.symmetric(horizontal: 24.0),
child: Row(
children: <Widget>[
Column(
children: <Widget>[
// Line parts are always added in order for the ink splash to
// flood the tips of the connector lines.
_buildLine(!_isFirst(index), isActive),
_buildIcon(index),
_buildLine(!_isLast(index), isActive),
],
),
Expanded(
child: Container(
margin: const EdgeInsetsDirectional.only(start: 12.0),
child: _buildHeaderText(index),
),
),
],
),
);
}
Widget _buildVerticalBody(int index) {
final double? marginLeft = _stepIconMargin?.resolve(TextDirection.ltr).left;
final double? marginRight = _stepIconMargin?.resolve(TextDirection.ltr).right;
final double? additionalMarginLeft = marginLeft != null ? marginLeft / 2.0 : null;
final double? additionalMarginRight = marginRight != null ? marginRight / 2.0 : null;
return Stack(
children: <Widget>[
PositionedDirectional(
// When use margin affects the left or right side of the child, we
// need to add half of the margin to the start or end of the child
// respectively to get the correct positioning.
start: 24.0 + (additionalMarginLeft ?? 0.0) + (additionalMarginRight ?? 0.0),
top: 0.0,
bottom: 0.0,
child: SizedBox(
// The line is drawn from the center of the circle vertically until
// it reaches the bottom and then horizontally to the edge of the
// stepper.
width: _stepIconWidth ?? _kStepSize,
child: Center(
child: SizedBox(
width: widget.connectorThickness ?? 1.0,
child: Container(
color: _connectorColor(widget.steps[index].isActive),
),
),
),
),
),
AnimatedCrossFade(
firstChild: Container(height: 0.0),
secondChild: Container(
margin: EdgeInsetsDirectional.only(
// Adjust [controlsBuilder] padding so that the content is
// centered vertically.
start: 60.0 + (marginLeft ?? 0.0),
end: 24.0,
bottom: 24.0,
),
child: Column(
children: <Widget>[
widget.steps[index].content,
_buildVerticalControls(index),
],
),
),
firstCurve: const Interval(0.0, 0.6, curve: Curves.fastOutSlowIn),
secondCurve: const Interval(0.4, 1.0, curve: Curves.fastOutSlowIn),
sizeCurve: Curves.fastOutSlowIn,
crossFadeState: _isCurrent(index) ? CrossFadeState.showSecond : CrossFadeState.showFirst,
duration: kThemeAnimationDuration,
),
],
);
}
Widget _buildVertical() {
return ListView(
controller: widget.controller,
shrinkWrap: true,
physics: widget.physics,
children: <Widget>[
for (int i = 0; i < widget.steps.length; i += 1)
Column(
key: _keys[i],
children: <Widget>[
InkWell(
onTap: widget.steps[i].state != StepState.disabled ? () {
// In the vertical case we need to scroll to the newly tapped
// step.
Scrollable.ensureVisible(
_keys[i].currentContext!,
curve: Curves.fastOutSlowIn,
duration: kThemeAnimationDuration,
);
widget.onStepTapped?.call(i);
} : null,
canRequestFocus: widget.steps[i].state != StepState.disabled,
child: _buildVerticalHeader(i),
),
_buildVerticalBody(i),
],
),
],
);
}
Widget _buildHorizontal() {
final List<Widget> children = <Widget>[
for (int i = 0; i < widget.steps.length; i += 1) ...<Widget>[
InkResponse(
onTap: widget.steps[i].state != StepState.disabled ? () {
widget.onStepTapped?.call(i);
} : null,
canRequestFocus: widget.steps[i].state != StepState.disabled,
child: Row(
children: <Widget>[
SizedBox(
height: _isLabel() ? 104.0 : 72.0,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
if (widget.steps[i].label != null) const SizedBox(height: 24.0,),
Center(child: _buildIcon(i)),
if (widget.steps[i].label != null) SizedBox(height : 24.0, child: _buildLabelText(i),),
],
),
),
Container(
margin: _stepIconMargin ?? const EdgeInsetsDirectional.only(start: 12.0),
child: _buildHeaderText(i),
),
],
),
),
if (!_isLast(i))
Expanded(
child: Container(
key: Key('line$i'),
margin: _stepIconMargin ?? const EdgeInsets.symmetric(horizontal: 8.0),
height: widget.steps[i].stepStyle?.connectorThickness ?? widget.connectorThickness ?? 1.0,
color: widget.steps[i].stepStyle?.connectorColor ?? _connectorColor(widget.steps[i].isActive),
),
),
],
];
final List<Widget> stepPanels = <Widget>[];
for (int i = 0; i < widget.steps.length; i += 1) {
stepPanels.add(
Visibility(
maintainState: true,
visible: i == widget.currentStep,
child: widget.steps[i].content,
),
);
}
return Column(
children: <Widget>[
Material(
elevation: widget.elevation ?? 2,
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 24.0),
height: _stepIconHeight != null ? _stepIconHeight! * _heightFactor : null,
child: Row(
children: children,
),
),
),
Expanded(
child: ListView(
controller: widget.controller,
physics: widget.physics,
padding: const EdgeInsets.all(24.0),
children: <Widget>[
AnimatedSize(
curve: Curves.fastOutSlowIn,
duration: kThemeAnimationDuration,
child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: stepPanels),
),
_buildVerticalControls(widget.currentStep),
],
),
),
],
);
}
@override
Widget build(BuildContext context) {
assert(debugCheckHasMaterial(context));
assert(debugCheckHasMaterialLocalizations(context));
assert(() {
if (context.findAncestorWidgetOfExactType<Stepper>() != null) {
throw FlutterError(
'Steppers must not be nested.\n'
'The material specification advises that one should avoid embedding '
'steppers within steppers. '
'https://material.io/archive/guidelines/components/steppers.html#steppers-usage',
);
}
return true;
}());
return switch (widget.type) {
StepperType.vertical => _buildVertical(),
StepperType.horizontal => _buildHorizontal(),
};
}
}
// Paints a triangle whose base is the bottom of the bounding rectangle and its
// top vertex the middle of its top.
class _TrianglePainter extends CustomPainter {
_TrianglePainter({
required this.color,
});
final Color color;
@override
bool hitTest(Offset point) => true; // Hitting the rectangle is fine enough.
@override
bool shouldRepaint(_TrianglePainter oldPainter) {
return oldPainter.color != color;
}
@override
void paint(Canvas canvas, Size size) {
final double base = size.width;
final double halfBase = size.width / 2.0;
final double height = size.height;
final List<Offset> points = <Offset>[
Offset(0.0, height),
Offset(base, height),
Offset(halfBase, 0.0),
];
canvas.drawPath(
Path()..addPolygon(points, true),
Paint()..color = color,
);
}
}
/// This class is used to override the default visual properties of [Step] widgets within a [Stepper].
///
/// To customize the appearance of a [Step] create an instance of this class with non-null parameters
/// for the step properties whose default value you want to override.
///
/// Example usage:
/// ```dart
/// Step(
/// title: const Text('Step 1'),
/// content: const Text('Content for Step 1'),
/// stepStyle: StepStyle(
/// color: Colors.blue,
/// errorColor: Colors.red,
/// border: Border.all(color: Colors.grey),
/// boxShadow: const BoxShadow(blurRadius: 3.0, color: Colors.black26),
/// gradient: const LinearGradient(colors: <Color>[Colors.red, Colors.blue]),
/// indexStyle: const TextStyle(color: Colors.white),
/// ),
/// )
/// ```
///
/// {@tool dartpad}
/// An example that uses [StepStyle] to customize the appearance of each [Step] in a [Stepper].
///
/// ** See code in examples/api/lib/material/stepper/step_style.0.dart **
/// {@end-tool}
@immutable
class StepStyle with Diagnosticable {
/// Constructs a [StepStyle].
const StepStyle({
this.color,
this.errorColor,
this.connectorColor,
this.connectorThickness,
this.border,
this.boxShadow,
this.gradient,
this.indexStyle,
});
/// Overrides the default color of the circle in the step.
final Color? color;
/// Overrides the default color of the error indicator in the step.
final Color? errorColor;
/// Overrides the default color of the connector line between two steps.
///
/// This property only applies when [Stepper.type] is [StepperType.horizontal].
final Color? connectorColor;
/// Overrides the default thickness of the connector line between two steps.
///
/// This property only applies when [Stepper.type] is [StepperType.horizontal].
final double? connectorThickness;
/// Add a border around the step.
///
/// Will be applied to the circle in the step.
final BoxBorder? border;
/// Add a shadow around the step.
final BoxShadow? boxShadow;
/// Add a gradient around the step.
///
/// If [gradient] is specified, [color] will be ignored.
final Gradient? gradient;
/// Overrides the default style of the index in the step.
final TextStyle? indexStyle;
/// Returns a copy of this ButtonStyle with the given fields replaced with
/// the new values.
StepStyle copyWith({
Color? color,
Color? errorColor,
Color? connectorColor,
double? connectorThickness,
BoxBorder? border,
BoxShadow? boxShadow,
Gradient? gradient,
TextStyle? indexStyle,
}) {
return StepStyle(
color: color ?? this.color,
errorColor: errorColor ?? this.errorColor,
connectorColor: connectorColor ?? this.connectorColor,
connectorThickness: connectorThickness ?? this.connectorThickness,
border: border ?? this.border,
boxShadow: boxShadow ?? this.boxShadow,
gradient: gradient ?? this.gradient,
indexStyle: indexStyle ?? this.indexStyle,
);
}
/// Returns a copy of this StepStyle where the non-null fields in [stepStyle]
/// have replaced the corresponding null fields in this StepStyle.
///
/// In other words, [stepStyle] is used to fill in unspecified (null) fields
/// this StepStyle.
StepStyle merge(StepStyle? stepStyle) {
if (stepStyle == null) {
return this;
}
return copyWith(
color: stepStyle.color,
errorColor: stepStyle.errorColor,
connectorColor: stepStyle.connectorColor,
connectorThickness: stepStyle.connectorThickness,
border: stepStyle.border,
boxShadow: stepStyle.boxShadow,
gradient: stepStyle.gradient,
indexStyle: stepStyle.indexStyle,
);
}
@override
int get hashCode {
return Object.hash(
color,
errorColor,
connectorColor,
connectorThickness,
border,
boxShadow,
gradient,
indexStyle,
);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is StepStyle &&
other.color == color &&
other.errorColor == errorColor &&
other.connectorColor == connectorColor &&
other.connectorThickness == connectorThickness &&
other.border == border &&
other.boxShadow == boxShadow &&
other.gradient == gradient &&
other.indexStyle == indexStyle;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
final ThemeData theme = ThemeData.fallback();
final TextTheme defaultTextTheme = theme.textTheme;
properties.add(ColorProperty('color', color, defaultValue: null));
properties.add(ColorProperty('errorColor', errorColor, defaultValue: null));
properties.add(ColorProperty('connectorColor', connectorColor, defaultValue: null));
properties.add(DoubleProperty('connectorThickness', connectorThickness, defaultValue: null));
properties.add(DiagnosticsProperty<BoxBorder>('border', border, defaultValue: null));
properties.add(DiagnosticsProperty<BoxShadow>('boxShadow', boxShadow, defaultValue: null));
properties.add(DiagnosticsProperty<Gradient>('gradient', gradient, defaultValue: null));
properties.add(DiagnosticsProperty<TextStyle>('indexStyle', indexStyle, defaultValue: defaultTextTheme.bodyLarge));
}
}
| flutter/packages/flutter/lib/src/material/stepper.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/stepper.dart",
"repo_id": "flutter",
"token_count": 15010
} | 805 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart';
import 'typography.dart';
/// Material design text theme.
///
/// Definitions for the various typographical styles found in Material Design
/// (e.g., labelLarge, bodySmall). Rather than creating a [TextTheme] directly,
/// you can obtain an instance as [Typography.black] or [Typography.white].
///
/// To obtain the current text theme, call [Theme.of] with the current
/// [BuildContext] and read the [ThemeData.textTheme] property.
///
/// The names of the TextTheme properties match this table from the
/// [Material Design spec](https://m3.material.io/styles/typography/tokens).
///
/// 
///
/// The Material Design typography scheme was significantly changed in the
/// current (2021) version of the specification
/// ([https://m3.material.io/styles/typography/tokens](https://m3.material.io/styles/typography/tokens)).
///
/// The names of the 2018 TextTheme properties match this table from the
/// [Material Design spec](https://material.io/design/typography/the-type-system.html#type-scale)
/// with two exceptions: the styles called H1-H6 in the spec are
/// headline1-headline6 in the API, and body1,body2 are called
/// bodyText1 and bodyText2.
///
/// The 2018 spec has thirteen text styles:
///
/// | NAME | SIZE | WEIGHT | SPACING | |
/// |------------|------|---------|----------|-------------|
/// | headline1 | 96.0 | light | -1.5 | |
/// | headline2 | 60.0 | light | -0.5 | |
/// | headline3 | 48.0 | regular | 0.0 | |
/// | headline4 | 34.0 | regular | 0.25 | |
/// | headline5 | 24.0 | regular | 0.0 | |
/// | headline6 | 20.0 | medium | 0.15 | |
/// | subtitle1 | 16.0 | regular | 0.15 | |
/// | subtitle2 | 14.0 | medium | 0.1 | |
/// | body1 | 16.0 | regular | 0.5 | (bodyText1) |
/// | body2 | 14.0 | regular | 0.25 | (bodyText2) |
/// | button | 14.0 | medium | 1.25 | |
/// | caption | 12.0 | regular | 0.4 | |
/// | overline | 10.0 | regular | 1.5 | |
///
/// ...where "light" is `FontWeight.w300`, "regular" is `FontWeight.w400` and
/// "medium" is `FontWeight.w500`.
///
/// By default, text styles are initialized to match the 2018 Material Design
/// specification as listed above. To provide backwards compatibility, the 2014
/// specification is also available.
///
/// To explicitly configure a [Theme] for the 2018 sizes, weights, and letter
/// spacings, you can initialize its [ThemeData.typography] value using
/// [Typography.material2018]. The [Typography] constructor defaults to this
/// configuration. To configure a [Theme] for the 2014 sizes, weights, and letter
/// spacings, initialize its [ThemeData.typography] value using
/// [Typography.material2014].
///
/// See also:
///
/// * [Typography], the class that generates [TextTheme]s appropriate for a platform.
/// * [Theme], for other aspects of a Material Design application that can be
/// globally adjusted, such as the color scheme.
/// * <https://material.io/design/typography/>
@immutable
class TextTheme with Diagnosticable {
/// Creates a text theme that uses the given values.
///
/// Rather than creating a new text theme, consider using [Typography.black]
/// or [Typography.white], which implement the typography styles in the
/// Material Design specification:
///
/// <https://material.io/design/typography/#type-scale>
///
/// If you do decide to create your own text theme, consider using one of
/// those predefined themes as a starting point for [copyWith] or [apply].
///
/// The 2018 styles cannot be mixed with the 2021 styles. Only one or the
/// other is allowed in this constructor. The 2018 styles are deprecated and
/// will eventually be removed.
const TextTheme({
TextStyle? displayLarge,
TextStyle? displayMedium,
TextStyle? displaySmall,
this.headlineLarge,
TextStyle? headlineMedium,
TextStyle? headlineSmall,
TextStyle? titleLarge,
TextStyle? titleMedium,
TextStyle? titleSmall,
TextStyle? bodyLarge,
TextStyle? bodyMedium,
TextStyle? bodySmall,
TextStyle? labelLarge,
this.labelMedium,
TextStyle? labelSmall,
@Deprecated(
'Use displayLarge instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? headline1,
@Deprecated(
'Use displayMedium instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? headline2,
@Deprecated(
'Use displaySmall instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? headline3,
@Deprecated(
'Use headlineMedium instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? headline4,
@Deprecated(
'Use headlineSmall instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? headline5,
@Deprecated(
'Use titleLarge instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? headline6,
@Deprecated(
'Use titleMedium instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? subtitle1,
@Deprecated(
'Use titleSmall instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? subtitle2,
@Deprecated(
'Use bodyLarge instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? bodyText1,
@Deprecated(
'Use bodyMedium instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? bodyText2,
@Deprecated(
'Use bodySmall instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? caption,
@Deprecated(
'Use labelLarge instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? button,
@Deprecated(
'Use labelSmall instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? overline,
}) : assert(
(displayLarge == null && displayMedium == null && displaySmall == null && headlineMedium == null &&
headlineSmall == null && titleLarge == null && titleMedium == null && titleSmall == null &&
bodyLarge == null && bodyMedium == null && bodySmall == null && labelLarge == null && labelSmall == null) ||
(headline1 == null && headline2 == null && headline3 == null && headline4 == null &&
headline5 == null && headline6 == null && subtitle1 == null && subtitle2 == null &&
bodyText1 == null && bodyText2 == null && caption == null && button == null && overline == null),
'Cannot mix 2018 and 2021 terms in call to TextTheme() constructor.'
),
displayLarge = displayLarge ?? headline1,
displayMedium = displayMedium ?? headline2,
displaySmall = displaySmall ?? headline3,
headlineMedium = headlineMedium ?? headline4,
headlineSmall = headlineSmall ?? headline5,
titleLarge = titleLarge ?? headline6,
titleMedium = titleMedium ?? subtitle1,
titleSmall = titleSmall ?? subtitle2,
bodyLarge = bodyLarge ?? bodyText1,
bodyMedium = bodyMedium ?? bodyText2,
bodySmall = bodySmall ?? caption,
labelLarge = labelLarge ?? button,
labelSmall = labelSmall ?? overline;
/// Largest of the display styles.
///
/// As the largest text on the screen, display styles are reserved for short,
/// important text or numerals. They work best on large screens.
final TextStyle? displayLarge;
/// Middle size of the display styles.
///
/// As the largest text on the screen, display styles are reserved for short,
/// important text or numerals. They work best on large screens.
final TextStyle? displayMedium;
/// Smallest of the display styles.
///
/// As the largest text on the screen, display styles are reserved for short,
/// important text or numerals. They work best on large screens.
final TextStyle? displaySmall;
/// Largest of the headline styles.
///
/// Headline styles are smaller than display styles. They're best-suited for
/// short, high-emphasis text on smaller screens.
final TextStyle? headlineLarge;
/// Middle size of the headline styles.
///
/// Headline styles are smaller than display styles. They're best-suited for
/// short, high-emphasis text on smaller screens.
final TextStyle? headlineMedium;
/// Smallest of the headline styles.
///
/// Headline styles are smaller than display styles. They're best-suited for
/// short, high-emphasis text on smaller screens.
final TextStyle? headlineSmall;
/// Largest of the title styles.
///
/// Titles are smaller than headline styles and should be used for shorter,
/// medium-emphasis text.
final TextStyle? titleLarge;
/// Middle size of the title styles.
///
/// Titles are smaller than headline styles and should be used for shorter,
/// medium-emphasis text.
final TextStyle? titleMedium;
/// Smallest of the title styles.
///
/// Titles are smaller than headline styles and should be used for shorter,
/// medium-emphasis text.
final TextStyle? titleSmall;
/// Largest of the body styles.
///
/// Body styles are used for longer passages of text.
final TextStyle? bodyLarge;
/// Middle size of the body styles.
///
/// Body styles are used for longer passages of text.
///
/// The default text style for [Material].
final TextStyle? bodyMedium;
/// Smallest of the body styles.
///
/// Body styles are used for longer passages of text.
final TextStyle? bodySmall;
/// Largest of the label styles.
///
/// Label styles are smaller, utilitarian styles, used for areas of the UI
/// such as text inside of components or very small supporting text in the
/// content body, like captions.
///
/// Used for text on [ElevatedButton], [TextButton] and [OutlinedButton].
final TextStyle? labelLarge;
/// Middle size of the label styles.
///
/// Label styles are smaller, utilitarian styles, used for areas of the UI
/// such as text inside of components or very small supporting text in the
/// content body, like captions.
final TextStyle? labelMedium;
/// Smallest of the label styles.
///
/// Label styles are smaller, utilitarian styles, used for areas of the UI
/// such as text inside of components or very small supporting text in the
/// content body, like captions.
final TextStyle? labelSmall;
/// Extremely large text.
@Deprecated(
'Use displayLarge instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? get headline1 => displayLarge;
/// Very, very large text.
///
/// Used for the date in the dialog shown by [showDatePicker].
@Deprecated(
'Use displayMedium instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? get headline2 => displayMedium;
/// Very large text.
@Deprecated(
'Use displaySmall instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? get headline3 => displaySmall;
/// Large text.
@Deprecated(
'Use headlineMedium instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? get headline4 => headlineMedium;
/// Used for large text in dialogs (e.g., the month and year in the dialog
/// shown by [showDatePicker]).
@Deprecated(
'Use headlineSmall instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? get headline5 => headlineSmall;
/// Used for the primary text in app bars and dialogs (e.g., [AppBar.title]
/// and [AlertDialog.title]).
@Deprecated(
'Use titleLarge instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? get headline6 => titleLarge;
/// Used for the primary text in lists (e.g., [ListTile.title]).
@Deprecated(
'Use titleMedium instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? get subtitle1 => titleMedium;
/// For medium emphasis text that's a little smaller than [titleMedium].
@Deprecated(
'Use titleSmall instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? get subtitle2 => titleSmall;
/// Used for emphasizing text that would otherwise be [bodyMedium].
@Deprecated(
'Use bodyLarge instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? get bodyText1 => bodyLarge;
/// The default text style for [Material].
@Deprecated(
'Use bodyMedium instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? get bodyText2 => bodyMedium;
/// Used for auxiliary text associated with images.
@Deprecated(
'Use bodySmall instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? get caption => bodySmall;
/// Used for text on [ElevatedButton], [TextButton] and [OutlinedButton].
@Deprecated(
'Use labelLarge instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? get button => labelLarge;
/// The smallest style.
///
/// Typically used for captions or to introduce a (larger) headline.
@Deprecated(
'Use labelSmall instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? get overline => labelSmall;
/// Creates a copy of this text theme but with the given fields replaced with
/// the new values.
///
/// Consider using [Typography.black] or [Typography.white], which implement
/// the typography styles in the Material Design specification, as a starting
/// point.
///
/// {@tool snippet}
///
/// ```dart
/// /// A Widget that sets the ambient theme's title text color for its
/// /// descendants, while leaving other ambient theme attributes alone.
/// class TitleColorThemeCopy extends StatelessWidget {
/// const TitleColorThemeCopy({super.key, required this.titleColor, required this.child});
///
/// final Color titleColor;
/// final Widget child;
///
/// @override
/// Widget build(BuildContext context) {
/// final ThemeData theme = Theme.of(context);
/// return Theme(
/// data: theme.copyWith(
/// textTheme: theme.textTheme.copyWith(
/// titleLarge: theme.textTheme.titleLarge!.copyWith(
/// color: titleColor,
/// ),
/// ),
/// ),
/// child: child,
/// );
/// }
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [merge] is used instead of [copyWith] when you want to merge all
/// of the fields of a TextTheme instead of individual fields.
TextTheme copyWith({
TextStyle? displayLarge,
TextStyle? displayMedium,
TextStyle? displaySmall,
TextStyle? headlineLarge,
TextStyle? headlineMedium,
TextStyle? headlineSmall,
TextStyle? titleLarge,
TextStyle? titleMedium,
TextStyle? titleSmall,
TextStyle? bodyLarge,
TextStyle? bodyMedium,
TextStyle? bodySmall,
TextStyle? labelLarge,
TextStyle? labelMedium,
TextStyle? labelSmall,
@Deprecated(
'Use displayLarge instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? headline1,
@Deprecated(
'Use displayMedium instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? headline2,
@Deprecated(
'Use displaySmall instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? headline3,
@Deprecated(
'Use headlineMedium instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? headline4,
@Deprecated(
'Use headlineSmall instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? headline5,
@Deprecated(
'Use titleLarge instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? headline6,
@Deprecated(
'Use titleMedium instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? subtitle1,
@Deprecated(
'Use titleSmall instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? subtitle2,
@Deprecated(
'Use bodyLarge instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? bodyText1,
@Deprecated(
'Use bodyMedium instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? bodyText2,
@Deprecated(
'Use bodySmall instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? caption,
@Deprecated(
'Use labelLarge instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? button,
@Deprecated(
'Use labelSmall instead. '
'This feature was deprecated after v3.1.0-0.0.pre.',
)
TextStyle? overline,
}) {
assert(
(displayLarge == null && displayMedium == null && displaySmall == null && headlineMedium == null &&
headlineSmall == null && titleLarge == null && titleMedium == null && titleSmall == null &&
bodyLarge == null && bodyMedium == null && bodySmall == null && labelLarge == null && labelSmall == null) ||
(headline1 == null && headline2 == null && headline3 == null && headline4 == null &&
headline5 == null && headline6 == null && subtitle1 == null && subtitle2 == null &&
bodyText1 == null && bodyText2 == null && caption == null && button == null && overline == null),
'Cannot mix 2018 and 2021 terms in call to TextTheme() constructor.'
);
return TextTheme(
displayLarge: displayLarge ?? headline1 ?? this.displayLarge,
displayMedium: displayMedium ?? headline2 ?? this.displayMedium,
displaySmall: displaySmall ?? headline3 ?? this.displaySmall,
headlineLarge: headlineLarge ?? this.headlineLarge,
headlineMedium: headlineMedium ?? headline4 ?? this.headlineMedium,
headlineSmall: headlineSmall ?? headline5 ?? this.headlineSmall,
titleLarge: titleLarge ?? headline6 ?? this.titleLarge,
titleMedium: titleMedium ?? subtitle1 ?? this.titleMedium,
titleSmall: titleSmall ?? subtitle2 ?? this.titleSmall,
bodyLarge: bodyLarge ?? bodyText1 ?? this.bodyLarge,
bodyMedium: bodyMedium ?? bodyText2 ?? this.bodyMedium,
bodySmall: bodySmall ?? caption ?? this.bodySmall,
labelLarge: labelLarge ?? button ?? this.labelLarge,
labelMedium: labelMedium ?? this.labelMedium,
labelSmall: labelSmall ?? overline ?? this.labelSmall,
);
}
/// Creates a new [TextTheme] where each text style from this object has been
/// merged with the matching text style from the `other` object.
///
/// The merging is done by calling [TextStyle.merge] on each respective pair
/// of text styles from this and the [other] text themes and is subject to
/// the value of [TextStyle.inherit] flag. For more details, see the
/// documentation on [TextStyle.merge] and [TextStyle.inherit].
///
/// If this theme, or the `other` theme has members that are null, then the
/// non-null one (if any) is used. If the `other` theme is itself null, then
/// this [TextTheme] is returned unchanged. If values in both are set, then
/// the values are merged using [TextStyle.merge].
///
/// This is particularly useful if one [TextTheme] defines one set of
/// properties and another defines a different set, e.g. having colors
/// defined in one text theme and font sizes in another, or when one
/// [TextTheme] has only some fields defined, and you want to define the rest
/// by merging it with a default theme.
///
/// {@tool snippet}
///
/// ```dart
/// /// A Widget that sets the ambient theme's title text color for its
/// /// descendants, while leaving other ambient theme attributes alone.
/// class TitleColorTheme extends StatelessWidget {
/// const TitleColorTheme({super.key, required this.child, required this.titleColor});
///
/// final Color titleColor;
/// final Widget child;
///
/// @override
/// Widget build(BuildContext context) {
/// ThemeData theme = Theme.of(context);
/// // This partialTheme is incomplete: it only has the title style
/// // defined. Just replacing theme.textTheme with partialTheme would
/// // set the title, but everything else would be null. This isn't very
/// // useful, so merge it with the existing theme to keep all of the
/// // preexisting definitions for the other styles.
/// final TextTheme partialTheme = TextTheme(titleLarge: TextStyle(color: titleColor));
/// theme = theme.copyWith(textTheme: theme.textTheme.merge(partialTheme));
/// return Theme(data: theme, child: child);
/// }
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [copyWith] is used instead of [merge] when you wish to override
/// individual fields in the [TextTheme] instead of merging all of the
/// fields of two [TextTheme]s.
TextTheme merge(TextTheme? other) {
if (other == null) {
return this;
}
return copyWith(
displayLarge: displayLarge?.merge(other.displayLarge) ?? other.displayLarge,
displayMedium: displayMedium?.merge(other.displayMedium) ?? other.displayMedium,
displaySmall: displaySmall?.merge(other.displaySmall) ?? other.displaySmall,
headlineLarge: headlineLarge?.merge(other.headlineLarge) ?? other.headlineLarge,
headlineMedium: headlineMedium?.merge(other.headlineMedium) ?? other.headlineMedium,
headlineSmall: headlineSmall?.merge(other.headlineSmall) ?? other.headlineSmall,
titleLarge: titleLarge?.merge(other.titleLarge) ?? other.titleLarge,
titleMedium: titleMedium?.merge(other.titleMedium) ?? other.titleMedium,
titleSmall: titleSmall?.merge(other.titleSmall) ?? other.titleSmall,
bodyLarge: bodyLarge?.merge(other.bodyLarge) ?? other.bodyLarge,
bodyMedium: bodyMedium?.merge(other.bodyMedium) ?? other.bodyMedium,
bodySmall: bodySmall?.merge(other.bodySmall) ?? other.bodySmall,
labelLarge: labelLarge?.merge(other.labelLarge) ?? other.labelLarge,
labelMedium: labelMedium?.merge(other.labelMedium) ?? other.labelMedium,
labelSmall: labelSmall?.merge(other.labelSmall) ?? other.labelSmall,
);
}
/// Creates a copy of this text theme but with the given field replaced in
/// each of the individual text styles.
///
/// The `displayColor` is applied to [displayLarge], [displayMedium],
/// [displaySmall], [headlineLarge], [headlineMedium], and [bodySmall]. The
/// `bodyColor` is applied to the remaining text styles.
///
/// Consider using [Typography.black] or [Typography.white], which implement
/// the typography styles in the Material Design specification, as a starting
/// point.
TextTheme apply({
String? fontFamily,
List<String>? fontFamilyFallback,
String? package,
double fontSizeFactor = 1.0,
double fontSizeDelta = 0.0,
Color? displayColor,
Color? bodyColor,
TextDecoration? decoration,
Color? decorationColor,
TextDecorationStyle? decorationStyle,
}) {
return TextTheme(
displayLarge: displayLarge?.apply(
color: displayColor,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSizeFactor: fontSizeFactor,
fontSizeDelta: fontSizeDelta,
package: package,
),
displayMedium: displayMedium?.apply(
color: displayColor,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSizeFactor: fontSizeFactor,
fontSizeDelta: fontSizeDelta,
package: package,
),
displaySmall: displaySmall?.apply(
color: displayColor,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSizeFactor: fontSizeFactor,
fontSizeDelta: fontSizeDelta,
package: package,
),
headlineLarge: headlineLarge?.apply(
color: displayColor,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSizeFactor: fontSizeFactor,
fontSizeDelta: fontSizeDelta,
package: package,
),
headlineMedium: headlineMedium?.apply(
color: displayColor,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSizeFactor: fontSizeFactor,
fontSizeDelta: fontSizeDelta,
package: package,
),
headlineSmall: headlineSmall?.apply(
color: bodyColor,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSizeFactor: fontSizeFactor,
fontSizeDelta: fontSizeDelta,
package: package,
),
titleLarge: titleLarge?.apply(
color: bodyColor,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSizeFactor: fontSizeFactor,
fontSizeDelta: fontSizeDelta,
package: package,
),
titleMedium: titleMedium?.apply(
color: bodyColor,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSizeFactor: fontSizeFactor,
fontSizeDelta: fontSizeDelta,
package: package,
),
titleSmall: titleSmall?.apply(
color: bodyColor,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSizeFactor: fontSizeFactor,
fontSizeDelta: fontSizeDelta,
package: package,
),
bodyLarge: bodyLarge?.apply(
color: bodyColor,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSizeFactor: fontSizeFactor,
fontSizeDelta: fontSizeDelta,
package: package,
),
bodyMedium: bodyMedium?.apply(
color: bodyColor,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSizeFactor: fontSizeFactor,
fontSizeDelta: fontSizeDelta,
package: package,
),
bodySmall: bodySmall?.apply(
color: displayColor,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSizeFactor: fontSizeFactor,
fontSizeDelta: fontSizeDelta,
package: package,
),
labelLarge: labelLarge?.apply(
color: bodyColor,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSizeFactor: fontSizeFactor,
fontSizeDelta: fontSizeDelta,
package: package,
),
labelMedium: labelMedium?.apply(
color: bodyColor,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSizeFactor: fontSizeFactor,
fontSizeDelta: fontSizeDelta,
package: package,
),
labelSmall: labelSmall?.apply(
color: bodyColor,
decoration: decoration,
decorationColor: decorationColor,
decorationStyle: decorationStyle,
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
fontSizeFactor: fontSizeFactor,
fontSizeDelta: fontSizeDelta,
package: package,
),
);
}
/// Linearly interpolate between two text themes.
///
/// {@macro dart.ui.shadow.lerp}
static TextTheme lerp(TextTheme? a, TextTheme? b, double t) {
if (identical(a, b) && a != null) {
return a;
}
return TextTheme(
displayLarge: TextStyle.lerp(a?.displayLarge, b?.displayLarge, t),
displayMedium: TextStyle.lerp(a?.displayMedium, b?.displayMedium, t),
displaySmall: TextStyle.lerp(a?.displaySmall, b?.displaySmall, t),
headlineLarge: TextStyle.lerp(a?.headlineLarge, b?.headlineLarge, t),
headlineMedium: TextStyle.lerp(a?.headlineMedium, b?.headlineMedium, t),
headlineSmall: TextStyle.lerp(a?.headlineSmall, b?.headlineSmall, t),
titleLarge: TextStyle.lerp(a?.titleLarge, b?.titleLarge, t),
titleMedium: TextStyle.lerp(a?.titleMedium, b?.titleMedium, t),
titleSmall: TextStyle.lerp(a?.titleSmall, b?.titleSmall, t),
bodyLarge: TextStyle.lerp(a?.bodyLarge, b?.bodyLarge, t),
bodyMedium: TextStyle.lerp(a?.bodyMedium, b?.bodyMedium, t),
bodySmall: TextStyle.lerp(a?.bodySmall, b?.bodySmall, t),
labelLarge: TextStyle.lerp(a?.labelLarge, b?.labelLarge, t),
labelMedium: TextStyle.lerp(a?.labelMedium, b?.labelMedium, t),
labelSmall: TextStyle.lerp(a?.labelSmall, b?.labelSmall, t),
);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is TextTheme
&& displayLarge == other.displayLarge
&& displayMedium == other.displayMedium
&& displaySmall == other.displaySmall
&& headlineLarge == other.headlineLarge
&& headlineMedium == other.headlineMedium
&& headlineSmall == other.headlineSmall
&& titleLarge == other.titleLarge
&& titleMedium == other.titleMedium
&& titleSmall == other.titleSmall
&& bodyLarge == other.bodyLarge
&& bodyMedium == other.bodyMedium
&& bodySmall == other.bodySmall
&& labelLarge == other.labelLarge
&& labelMedium == other.labelMedium
&& labelSmall == other.labelSmall;
}
@override
int get hashCode => Object.hash(
displayLarge,
displayMedium,
displaySmall,
headlineLarge,
headlineMedium,
headlineSmall,
titleLarge,
titleMedium,
titleSmall,
bodyLarge,
bodyMedium,
bodySmall,
labelLarge,
labelMedium,
labelSmall,
);
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
final TextTheme defaultTheme = Typography.material2018(platform: defaultTargetPlatform).black;
properties.add(DiagnosticsProperty<TextStyle>('displayLarge', displayLarge, defaultValue: defaultTheme.displayLarge));
properties.add(DiagnosticsProperty<TextStyle>('displayMedium', displayMedium, defaultValue: defaultTheme.displayMedium));
properties.add(DiagnosticsProperty<TextStyle>('displaySmall', displaySmall, defaultValue: defaultTheme.displaySmall));
properties.add(DiagnosticsProperty<TextStyle>('headlineLarge', headlineLarge, defaultValue: defaultTheme.headlineLarge));
properties.add(DiagnosticsProperty<TextStyle>('headlineMedium', headlineMedium, defaultValue: defaultTheme.headlineMedium));
properties.add(DiagnosticsProperty<TextStyle>('headlineSmall', headlineSmall, defaultValue: defaultTheme.headlineSmall));
properties.add(DiagnosticsProperty<TextStyle>('titleLarge', titleLarge, defaultValue: defaultTheme.titleLarge));
properties.add(DiagnosticsProperty<TextStyle>('titleMedium', titleMedium, defaultValue: defaultTheme.titleMedium));
properties.add(DiagnosticsProperty<TextStyle>('titleSmall', titleSmall, defaultValue: defaultTheme.titleSmall));
properties.add(DiagnosticsProperty<TextStyle>('bodyLarge', bodyLarge, defaultValue: defaultTheme.bodyLarge));
properties.add(DiagnosticsProperty<TextStyle>('bodyMedium', bodyMedium, defaultValue: defaultTheme.bodyMedium));
properties.add(DiagnosticsProperty<TextStyle>('bodySmall', bodySmall, defaultValue: defaultTheme.bodySmall));
properties.add(DiagnosticsProperty<TextStyle>('labelLarge', labelLarge, defaultValue: defaultTheme.labelLarge));
properties.add(DiagnosticsProperty<TextStyle>('labelMedium', labelMedium, defaultValue: defaultTheme.labelMedium));
properties.add(DiagnosticsProperty<TextStyle>('labelSmall', labelSmall, defaultValue: defaultTheme.labelSmall));
}
}
| flutter/packages/flutter/lib/src/material/text_theme.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/text_theme.dart",
"repo_id": "flutter",
"token_count": 11832
} | 806 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui show lerpDouble;
import 'package:flutter/foundation.dart';
import 'basic_types.dart';
/// Base class for [Alignment] that allows for text-direction aware
/// resolution.
///
/// A property or argument of this type accepts classes created either with [
/// Alignment] and its variants, or [AlignmentDirectional.new].
///
/// To convert an [AlignmentGeometry] object of indeterminate type into an
/// [Alignment] object, call the [resolve] method.
@immutable
abstract class AlignmentGeometry {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const AlignmentGeometry();
double get _x;
double get _start;
double get _y;
/// Returns the sum of two [AlignmentGeometry] objects.
///
/// If you know you are adding two [Alignment] or two [AlignmentDirectional]
/// objects, consider using the `+` operator instead, which always returns an
/// object of the same type as the operands, and is typed accordingly.
///
/// If [add] is applied to two objects of the same type ([Alignment] or
/// [AlignmentDirectional]), an object of that type will be returned (though
/// this is not reflected in the type system). Otherwise, an object
/// representing a combination of both is returned. That object can be turned
/// into a concrete [Alignment] using [resolve].
AlignmentGeometry add(AlignmentGeometry other) {
return _MixedAlignment(
_x + other._x,
_start + other._start,
_y + other._y,
);
}
/// Returns the negation of the given [AlignmentGeometry] object.
///
/// This is the same as multiplying the object by -1.0.
///
/// This operator returns an object of the same type as the operand.
AlignmentGeometry operator -();
/// Scales the [AlignmentGeometry] object in each dimension by the given factor.
///
/// This operator returns an object of the same type as the operand.
AlignmentGeometry operator *(double other);
/// Divides the [AlignmentGeometry] object in each dimension by the given factor.
///
/// This operator returns an object of the same type as the operand.
AlignmentGeometry operator /(double other);
/// Integer divides the [AlignmentGeometry] object in each dimension by the given factor.
///
/// This operator returns an object of the same type as the operand.
AlignmentGeometry operator ~/(double other);
/// Computes the remainder in each dimension by the given factor.
///
/// This operator returns an object of the same type as the operand.
AlignmentGeometry operator %(double other);
/// Linearly interpolate between two [AlignmentGeometry] objects.
///
/// If either is null, this function interpolates from [Alignment.center], and
/// the result is an object of the same type as the non-null argument.
///
/// If [lerp] is applied to two objects of the same type ([Alignment] or
/// [AlignmentDirectional]), an object of that type will be returned (though
/// this is not reflected in the type system). Otherwise, an object
/// representing a combination of both is returned. That object can be turned
/// into a concrete [Alignment] using [resolve].
///
/// {@macro dart.ui.shadow.lerp}
static AlignmentGeometry? lerp(AlignmentGeometry? a, AlignmentGeometry? b, double t) {
if (identical(a, b)) {
return a;
}
if (a == null) {
return b! * t;
}
if (b == null) {
return a * (1.0 - t);
}
if (a is Alignment && b is Alignment) {
return Alignment.lerp(a, b, t);
}
if (a is AlignmentDirectional && b is AlignmentDirectional) {
return AlignmentDirectional.lerp(a, b, t);
}
return _MixedAlignment(
ui.lerpDouble(a._x, b._x, t)!,
ui.lerpDouble(a._start, b._start, t)!,
ui.lerpDouble(a._y, b._y, t)!,
);
}
/// Convert this instance into an [Alignment], which uses literal
/// coordinates (the `x` coordinate being explicitly a distance from the
/// left).
///
/// See also:
///
/// * [Alignment], for which this is a no-op (returns itself).
/// * [AlignmentDirectional], which flips the horizontal direction
/// based on the `direction` argument.
Alignment resolve(TextDirection? direction);
@override
String toString() {
if (_start == 0.0) {
return Alignment._stringify(_x, _y);
}
if (_x == 0.0) {
return AlignmentDirectional._stringify(_start, _y);
}
return '${Alignment._stringify(_x, _y)} + ${AlignmentDirectional._stringify(_start, 0.0)}';
}
@override
bool operator ==(Object other) {
return other is AlignmentGeometry
&& other._x == _x
&& other._start == _start
&& other._y == _y;
}
@override
int get hashCode => Object.hash(_x, _start, _y);
}
/// A point within a rectangle.
///
/// `Alignment(0.0, 0.0)` represents the center of the rectangle. The distance
/// from -1.0 to +1.0 is the distance from one side of the rectangle to the
/// other side of the rectangle. Therefore, 2.0 units horizontally (or
/// vertically) is equivalent to the width (or height) of the rectangle.
///
/// `Alignment(-1.0, -1.0)` represents the top left of the rectangle.
///
/// `Alignment(1.0, 1.0)` represents the bottom right of the rectangle.
///
/// `Alignment(0.0, 3.0)` represents a point that is horizontally centered with
/// respect to the rectangle and vertically below the bottom of the rectangle by
/// the height of the rectangle.
///
/// `Alignment(0.0, -0.5)` represents a point that is horizontally centered with
/// respect to the rectangle and vertically half way between the top edge and
/// the center.
///
/// `Alignment(x, y)` in a rectangle with height h and width w describes
/// the point (x * w/2 + w/2, y * h/2 + h/2) in the coordinate system of the
/// rectangle.
///
/// [Alignment] uses visual coordinates, which means increasing [x] moves the
/// point from left to right. To support layouts with a right-to-left
/// [TextDirection], consider using [AlignmentDirectional], in which the
/// direction the point moves when increasing the horizontal value depends on
/// the [TextDirection].
///
/// A variety of widgets use [Alignment] in their configuration, most
/// notably:
///
/// * [Align] positions a child according to an [Alignment].
///
/// See also:
///
/// * [AlignmentDirectional], which has a horizontal coordinate orientation
/// that depends on the [TextDirection].
/// * [AlignmentGeometry], which is an abstract type that is agnostic as to
/// whether the horizontal direction depends on the [TextDirection].
class Alignment extends AlignmentGeometry {
/// Creates an alignment.
const Alignment(this.x, this.y);
/// The distance fraction in the horizontal direction.
///
/// A value of -1.0 corresponds to the leftmost edge. A value of 1.0
/// corresponds to the rightmost edge. Values are not limited to that range;
/// values less than -1.0 represent positions to the left of the left edge,
/// and values greater than 1.0 represent positions to the right of the right
/// edge.
final double x;
/// The distance fraction in the vertical direction.
///
/// A value of -1.0 corresponds to the topmost edge. A value of 1.0
/// corresponds to the bottommost edge. Values are not limited to that range;
/// values less than -1.0 represent positions above the top, and values
/// greater than 1.0 represent positions below the bottom.
final double y;
@override
double get _x => x;
@override
double get _start => 0.0;
@override
double get _y => y;
/// The top left corner.
static const Alignment topLeft = Alignment(-1.0, -1.0);
/// The center point along the top edge.
static const Alignment topCenter = Alignment(0.0, -1.0);
/// The top right corner.
static const Alignment topRight = Alignment(1.0, -1.0);
/// The center point along the left edge.
static const Alignment centerLeft = Alignment(-1.0, 0.0);
/// The center point, both horizontally and vertically.
static const Alignment center = Alignment(0.0, 0.0);
/// The center point along the right edge.
static const Alignment centerRight = Alignment(1.0, 0.0);
/// The bottom left corner.
static const Alignment bottomLeft = Alignment(-1.0, 1.0);
/// The center point along the bottom edge.
static const Alignment bottomCenter = Alignment(0.0, 1.0);
/// The bottom right corner.
static const Alignment bottomRight = Alignment(1.0, 1.0);
@override
AlignmentGeometry add(AlignmentGeometry other) {
if (other is Alignment) {
return this + other;
}
return super.add(other);
}
/// Returns the difference between two [Alignment]s.
Alignment operator -(Alignment other) {
return Alignment(x - other.x, y - other.y);
}
/// Returns the sum of two [Alignment]s.
Alignment operator +(Alignment other) {
return Alignment(x + other.x, y + other.y);
}
/// Returns the negation of the given [Alignment].
@override
Alignment operator -() {
return Alignment(-x, -y);
}
/// Scales the [Alignment] in each dimension by the given factor.
@override
Alignment operator *(double other) {
return Alignment(x * other, y * other);
}
/// Divides the [Alignment] in each dimension by the given factor.
@override
Alignment operator /(double other) {
return Alignment(x / other, y / other);
}
/// Integer divides the [Alignment] in each dimension by the given factor.
@override
Alignment operator ~/(double other) {
return Alignment((x ~/ other).toDouble(), (y ~/ other).toDouble());
}
/// Computes the remainder in each dimension by the given factor.
@override
Alignment operator %(double other) {
return Alignment(x % other, y % other);
}
/// Returns the offset that is this fraction in the direction of the given offset.
Offset alongOffset(Offset other) {
final double centerX = other.dx / 2.0;
final double centerY = other.dy / 2.0;
return Offset(centerX + x * centerX, centerY + y * centerY);
}
/// Returns the offset that is this fraction within the given size.
Offset alongSize(Size other) {
final double centerX = other.width / 2.0;
final double centerY = other.height / 2.0;
return Offset(centerX + x * centerX, centerY + y * centerY);
}
/// Returns the point that is this fraction within the given rect.
Offset withinRect(Rect rect) {
final double halfWidth = rect.width / 2.0;
final double halfHeight = rect.height / 2.0;
return Offset(
rect.left + halfWidth + x * halfWidth,
rect.top + halfHeight + y * halfHeight,
);
}
/// Returns a rect of the given size, aligned within given rect as specified
/// by this alignment.
///
/// For example, a 100×100 size inscribed on a 200×200 rect using
/// [Alignment.topLeft] would be the 100×100 rect at the top left of
/// the 200×200 rect.
Rect inscribe(Size size, Rect rect) {
final double halfWidthDelta = (rect.width - size.width) / 2.0;
final double halfHeightDelta = (rect.height - size.height) / 2.0;
return Rect.fromLTWH(
rect.left + halfWidthDelta + x * halfWidthDelta,
rect.top + halfHeightDelta + y * halfHeightDelta,
size.width,
size.height,
);
}
/// Linearly interpolate between two [Alignment]s.
///
/// If either is null, this function interpolates from [Alignment.center].
///
/// {@macro dart.ui.shadow.lerp}
static Alignment? lerp(Alignment? a, Alignment? b, double t) {
if (identical(a, b)) {
return a;
}
if (a == null) {
return Alignment(ui.lerpDouble(0.0, b!.x, t)!, ui.lerpDouble(0.0, b.y, t)!);
}
if (b == null) {
return Alignment(ui.lerpDouble(a.x, 0.0, t)!, ui.lerpDouble(a.y, 0.0, t)!);
}
return Alignment(ui.lerpDouble(a.x, b.x, t)!, ui.lerpDouble(a.y, b.y, t)!);
}
@override
Alignment resolve(TextDirection? direction) => this;
static String _stringify(double x, double y) {
if (x == -1.0 && y == -1.0) {
return 'Alignment.topLeft';
}
if (x == 0.0 && y == -1.0) {
return 'Alignment.topCenter';
}
if (x == 1.0 && y == -1.0) {
return 'Alignment.topRight';
}
if (x == -1.0 && y == 0.0) {
return 'Alignment.centerLeft';
}
if (x == 0.0 && y == 0.0) {
return 'Alignment.center';
}
if (x == 1.0 && y == 0.0) {
return 'Alignment.centerRight';
}
if (x == -1.0 && y == 1.0) {
return 'Alignment.bottomLeft';
}
if (x == 0.0 && y == 1.0) {
return 'Alignment.bottomCenter';
}
if (x == 1.0 && y == 1.0) {
return 'Alignment.bottomRight';
}
return 'Alignment(${x.toStringAsFixed(1)}, '
'${y.toStringAsFixed(1)})';
}
@override
String toString() => _stringify(x, y);
}
/// An offset that's expressed as a fraction of a [Size], but whose horizontal
/// component is dependent on the writing direction.
///
/// This can be used to indicate an offset from the left in [TextDirection.ltr]
/// text and an offset from the right in [TextDirection.rtl] text without having
/// to be aware of the current text direction.
///
/// See also:
///
/// * [Alignment], a variant that is defined in physical terms (i.e.
/// whose horizontal component does not depend on the text direction).
class AlignmentDirectional extends AlignmentGeometry {
/// Creates a directional alignment.
const AlignmentDirectional(this.start, this.y);
/// The distance fraction in the horizontal direction.
///
/// A value of -1.0 corresponds to the edge on the "start" side, which is the
/// left side in [TextDirection.ltr] contexts and the right side in
/// [TextDirection.rtl] contexts. A value of 1.0 corresponds to the opposite
/// edge, the "end" side. Values are not limited to that range; values less
/// than -1.0 represent positions beyond the start edge, and values greater than
/// 1.0 represent positions beyond the end edge.
///
/// This value is normalized into an [Alignment.x] value by the [resolve]
/// method.
final double start;
/// The distance fraction in the vertical direction.
///
/// A value of -1.0 corresponds to the topmost edge. A value of 1.0
/// corresponds to the bottommost edge. Values are not limited to that range;
/// values less than -1.0 represent positions above the top, and values
/// greater than 1.0 represent positions below the bottom.
///
/// This value is passed through to [Alignment.y] unmodified by the
/// [resolve] method.
final double y;
@override
double get _x => 0.0;
@override
double get _start => start;
@override
double get _y => y;
/// The top corner on the "start" side.
static const AlignmentDirectional topStart = AlignmentDirectional(-1.0, -1.0);
/// The center point along the top edge.
///
/// Consider using [Alignment.topCenter] instead, as it does not need
/// to be [resolve]d to be used.
static const AlignmentDirectional topCenter = AlignmentDirectional(0.0, -1.0);
/// The top corner on the "end" side.
static const AlignmentDirectional topEnd = AlignmentDirectional(1.0, -1.0);
/// The center point along the "start" edge.
static const AlignmentDirectional centerStart = AlignmentDirectional(-1.0, 0.0);
/// The center point, both horizontally and vertically.
///
/// Consider using [Alignment.center] instead, as it does not need to
/// be [resolve]d to be used.
static const AlignmentDirectional center = AlignmentDirectional(0.0, 0.0);
/// The center point along the "end" edge.
static const AlignmentDirectional centerEnd = AlignmentDirectional(1.0, 0.0);
/// The bottom corner on the "start" side.
static const AlignmentDirectional bottomStart = AlignmentDirectional(-1.0, 1.0);
/// The center point along the bottom edge.
///
/// Consider using [Alignment.bottomCenter] instead, as it does not
/// need to be [resolve]d to be used.
static const AlignmentDirectional bottomCenter = AlignmentDirectional(0.0, 1.0);
/// The bottom corner on the "end" side.
static const AlignmentDirectional bottomEnd = AlignmentDirectional(1.0, 1.0);
@override
AlignmentGeometry add(AlignmentGeometry other) {
if (other is AlignmentDirectional) {
return this + other;
}
return super.add(other);
}
/// Returns the difference between two [AlignmentDirectional]s.
AlignmentDirectional operator -(AlignmentDirectional other) {
return AlignmentDirectional(start - other.start, y - other.y);
}
/// Returns the sum of two [AlignmentDirectional]s.
AlignmentDirectional operator +(AlignmentDirectional other) {
return AlignmentDirectional(start + other.start, y + other.y);
}
/// Returns the negation of the given [AlignmentDirectional].
@override
AlignmentDirectional operator -() {
return AlignmentDirectional(-start, -y);
}
/// Scales the [AlignmentDirectional] in each dimension by the given factor.
@override
AlignmentDirectional operator *(double other) {
return AlignmentDirectional(start * other, y * other);
}
/// Divides the [AlignmentDirectional] in each dimension by the given factor.
@override
AlignmentDirectional operator /(double other) {
return AlignmentDirectional(start / other, y / other);
}
/// Integer divides the [AlignmentDirectional] in each dimension by the given factor.
@override
AlignmentDirectional operator ~/(double other) {
return AlignmentDirectional((start ~/ other).toDouble(), (y ~/ other).toDouble());
}
/// Computes the remainder in each dimension by the given factor.
@override
AlignmentDirectional operator %(double other) {
return AlignmentDirectional(start % other, y % other);
}
/// Linearly interpolate between two [AlignmentDirectional]s.
///
/// If either is null, this function interpolates from [AlignmentDirectional.center].
///
/// {@macro dart.ui.shadow.lerp}
static AlignmentDirectional? lerp(AlignmentDirectional? a, AlignmentDirectional? b, double t) {
if (identical(a, b)) {
return a;
}
if (a == null) {
return AlignmentDirectional(ui.lerpDouble(0.0, b!.start, t)!, ui.lerpDouble(0.0, b.y, t)!);
}
if (b == null) {
return AlignmentDirectional(ui.lerpDouble(a.start, 0.0, t)!, ui.lerpDouble(a.y, 0.0, t)!);
}
return AlignmentDirectional(ui.lerpDouble(a.start, b.start, t)!, ui.lerpDouble(a.y, b.y, t)!);
}
@override
Alignment resolve(TextDirection? direction) {
assert(direction != null, 'Cannot resolve $runtimeType without a TextDirection.');
return switch (direction!) {
TextDirection.rtl => Alignment(-start, y),
TextDirection.ltr => Alignment(start, y),
};
}
static String _stringify(double start, double y) {
if (start == -1.0 && y == -1.0) {
return 'AlignmentDirectional.topStart';
}
if (start == 0.0 && y == -1.0) {
return 'AlignmentDirectional.topCenter';
}
if (start == 1.0 && y == -1.0) {
return 'AlignmentDirectional.topEnd';
}
if (start == -1.0 && y == 0.0) {
return 'AlignmentDirectional.centerStart';
}
if (start == 0.0 && y == 0.0) {
return 'AlignmentDirectional.center';
}
if (start == 1.0 && y == 0.0) {
return 'AlignmentDirectional.centerEnd';
}
if (start == -1.0 && y == 1.0) {
return 'AlignmentDirectional.bottomStart';
}
if (start == 0.0 && y == 1.0) {
return 'AlignmentDirectional.bottomCenter';
}
if (start == 1.0 && y == 1.0) {
return 'AlignmentDirectional.bottomEnd';
}
return 'AlignmentDirectional(${start.toStringAsFixed(1)}, '
'${y.toStringAsFixed(1)})';
}
@override
String toString() => _stringify(start, y);
}
class _MixedAlignment extends AlignmentGeometry {
const _MixedAlignment(this._x, this._start, this._y);
@override
final double _x;
@override
final double _start;
@override
final double _y;
@override
_MixedAlignment operator -() {
return _MixedAlignment(
-_x,
-_start,
-_y,
);
}
@override
_MixedAlignment operator *(double other) {
return _MixedAlignment(
_x * other,
_start * other,
_y * other,
);
}
@override
_MixedAlignment operator /(double other) {
return _MixedAlignment(
_x / other,
_start / other,
_y / other,
);
}
@override
_MixedAlignment operator ~/(double other) {
return _MixedAlignment(
(_x ~/ other).toDouble(),
(_start ~/ other).toDouble(),
(_y ~/ other).toDouble(),
);
}
@override
_MixedAlignment operator %(double other) {
return _MixedAlignment(
_x % other,
_start % other,
_y % other,
);
}
@override
Alignment resolve(TextDirection? direction) {
assert(direction != null, 'Cannot resolve $runtimeType without a TextDirection.');
return switch (direction!) {
TextDirection.rtl => Alignment(_x - _start, _y),
TextDirection.ltr => Alignment(_x + _start, _y),
};
}
}
/// The vertical alignment of text within an input box.
///
/// A single [y] value that can range from -1.0 to 1.0. -1.0 aligns to the top
/// of an input box so that the top of the first line of text fits within the
/// box and its padding. 0.0 aligns to the center of the box. 1.0 aligns so that
/// the bottom of the last line of text aligns with the bottom interior edge of
/// the input box.
///
/// See also:
///
/// * [TextField.textAlignVertical], which is passed on to the [InputDecorator].
/// * [CupertinoTextField.textAlignVertical], which behaves in the same way as
/// the parameter in TextField.
/// * [InputDecorator.textAlignVertical], which defines the alignment of
/// prefix, input, and suffix within an [InputDecorator].
class TextAlignVertical {
/// Creates a TextAlignVertical from any y value between -1.0 and 1.0.
const TextAlignVertical({
required this.y,
}) : assert(y >= -1.0 && y <= 1.0);
/// A value ranging from -1.0 to 1.0 that defines the topmost and bottommost
/// locations of the top and bottom of the input box.
final double y;
/// Aligns a TextField's input Text with the topmost location within a
/// TextField's input box.
static const TextAlignVertical top = TextAlignVertical(y: -1.0);
/// Aligns a TextField's input Text to the center of the TextField.
static const TextAlignVertical center = TextAlignVertical(y: 0.0);
/// Aligns a TextField's input Text with the bottommost location within a
/// TextField.
static const TextAlignVertical bottom = TextAlignVertical(y: 1.0);
@override
String toString() {
return '${objectRuntimeType(this, 'TextAlignVertical')}(y: $y)';
}
}
| flutter/packages/flutter/lib/src/painting/alignment.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/painting/alignment.dart",
"repo_id": "flutter",
"token_count": 7673
} | 807 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:developer' as developer;
import 'dart:math' as math;
import 'dart:ui' as ui show FlutterView, Image;
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
import 'alignment.dart';
import 'basic_types.dart';
import 'binding.dart';
import 'borders.dart';
import 'box_fit.dart';
import 'debug.dart';
import 'image_provider.dart';
import 'image_stream.dart';
/// How to paint any portions of a box not covered by an image.
enum ImageRepeat {
/// Repeat the image in both the x and y directions until the box is filled.
repeat,
/// Repeat the image in the x direction until the box is filled horizontally.
repeatX,
/// Repeat the image in the y direction until the box is filled vertically.
repeatY,
/// Leave uncovered portions of the box transparent.
noRepeat,
}
/// An image for a box decoration.
///
/// The image is painted using [paintImage], which describes the meanings of the
/// various fields on this class in more detail.
@immutable
class DecorationImage {
/// Creates an image to show in a [BoxDecoration].
const DecorationImage({
required this.image,
this.onError,
this.colorFilter,
this.fit,
this.alignment = Alignment.center,
this.centerSlice,
this.repeat = ImageRepeat.noRepeat,
this.matchTextDirection = false,
this.scale = 1.0,
this.opacity = 1.0,
this.filterQuality = FilterQuality.low,
this.invertColors = false,
this.isAntiAlias = false,
});
/// The image to be painted into the decoration.
///
/// Typically this will be an [AssetImage] (for an image shipped with the
/// application) or a [NetworkImage] (for an image obtained from the network).
final ImageProvider image;
/// An optional error callback for errors emitted when loading [image].
final ImageErrorListener? onError;
/// A color filter to apply to the image before painting it.
final ColorFilter? colorFilter;
/// How the image should be inscribed into the box.
///
/// The default is [BoxFit.scaleDown] if [centerSlice] is null, and
/// [BoxFit.fill] if [centerSlice] is not null.
///
/// See the discussion at [paintImage] for more details.
final BoxFit? fit;
/// How to align the image within its bounds.
///
/// The alignment aligns the given position in the image to the given position
/// in the layout bounds. For example, an [Alignment] alignment of (-1.0,
/// -1.0) aligns the image to the top-left corner of its layout bounds, while a
/// [Alignment] alignment of (1.0, 1.0) aligns the bottom right of the
/// image with the bottom right corner of its layout bounds. Similarly, an
/// alignment of (0.0, 1.0) aligns the bottom middle of the image with the
/// middle of the bottom edge of its layout bounds.
///
/// To display a subpart of an image, consider using a [CustomPainter] and
/// [Canvas.drawImageRect].
///
/// If the [alignment] is [TextDirection]-dependent (i.e. if it is a
/// [AlignmentDirectional]), then a [TextDirection] must be available
/// when the image is painted.
///
/// Defaults to [Alignment.center].
///
/// See also:
///
/// * [Alignment], a class with convenient constants typically used to
/// specify an [AlignmentGeometry].
/// * [AlignmentDirectional], like [Alignment] for specifying alignments
/// relative to text direction.
final AlignmentGeometry alignment;
/// The center slice for a nine-patch image.
///
/// The region of the image inside the center slice will be stretched both
/// horizontally and vertically to fit the image into its destination. The
/// region of the image above and below the center slice will be stretched
/// only horizontally and the region of the image to the left and right of
/// the center slice will be stretched only vertically.
///
/// The stretching will be applied in order to make the image fit into the box
/// specified by [fit]. When [centerSlice] is not null, [fit] defaults to
/// [BoxFit.fill], which distorts the destination image size relative to the
/// image's original aspect ratio. Values of [BoxFit] which do not distort the
/// destination image size will result in [centerSlice] having no effect
/// (since the nine regions of the image will be rendered with the same
/// scaling, as if it wasn't specified).
final Rect? centerSlice;
/// How to paint any portions of the box that would not otherwise be covered
/// by the image.
final ImageRepeat repeat;
/// Whether to paint the image in the direction of the [TextDirection].
///
/// If this is true, then in [TextDirection.ltr] contexts, the image will be
/// drawn with its origin in the top left (the "normal" painting direction for
/// images); and in [TextDirection.rtl] contexts, the image will be drawn with
/// a scaling factor of -1 in the horizontal direction so that the origin is
/// in the top right.
final bool matchTextDirection;
/// Defines image pixels to be shown per logical pixels.
///
/// By default the value of scale is 1.0. The scale for the image is
/// calculated by multiplying [scale] with [scale] of the given [ImageProvider].
final double scale;
/// If non-null, the value is multiplied with the opacity of each image
/// pixel before painting onto the canvas.
///
/// This is more efficient than using [Opacity] or [FadeTransition] to
/// change the opacity of an image.
final double opacity;
/// Used to set the filterQuality of the image.
///
/// Defaults to [FilterQuality.low] to scale the image, which corresponds to
/// bilinear interpolation.
final FilterQuality filterQuality;
/// Whether the colors of the image are inverted when drawn.
///
/// Inverting the colors of an image applies a new color filter to the paint.
/// If there is another specified color filter, the invert will be applied
/// after it. This is primarily used for implementing smart invert on iOS.
///
/// See also:
///
/// * [Paint.invertColors], for the dart:ui implementation.
final bool invertColors;
/// Whether to paint the image with anti-aliasing.
///
/// Anti-aliasing alleviates the sawtooth artifact when the image is rotated.
final bool isAntiAlias;
/// Creates a [DecorationImagePainter] for this [DecorationImage].
///
/// The `onChanged` argument will be called whenever the image needs to be
/// repainted, e.g. because it is loading incrementally or because it is
/// animated.
DecorationImagePainter createPainter(VoidCallback onChanged) {
return _DecorationImagePainter._(this, onChanged);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is DecorationImage
&& other.image == image
&& other.colorFilter == colorFilter
&& other.fit == fit
&& other.alignment == alignment
&& other.centerSlice == centerSlice
&& other.repeat == repeat
&& other.matchTextDirection == matchTextDirection
&& other.scale == scale
&& other.opacity == opacity
&& other.filterQuality == filterQuality
&& other.invertColors == invertColors
&& other.isAntiAlias == isAntiAlias;
}
@override
int get hashCode => Object.hash(
image,
colorFilter,
fit,
alignment,
centerSlice,
repeat,
matchTextDirection,
scale,
opacity,
filterQuality,
invertColors,
isAntiAlias,
);
@override
String toString() {
final List<String> properties = <String>[
'$image',
if (colorFilter != null)
'$colorFilter',
if (fit != null &&
!(fit == BoxFit.fill && centerSlice != null) &&
!(fit == BoxFit.scaleDown && centerSlice == null))
'$fit',
'$alignment',
if (centerSlice != null)
'centerSlice: $centerSlice',
if (repeat != ImageRepeat.noRepeat)
'$repeat',
if (matchTextDirection)
'match text direction',
'scale ${scale.toStringAsFixed(1)}',
'opacity ${opacity.toStringAsFixed(1)}',
'$filterQuality',
if (invertColors)
'invert colors',
if (isAntiAlias)
'use anti-aliasing',
];
return '${objectRuntimeType(this, 'DecorationImage')}(${properties.join(", ")})';
}
/// Linearly interpolates between two [DecorationImage]s.
///
/// The `t` argument represents position on the timeline, with 0.0 meaning
/// that the interpolation has not started, returning `a`, 1.0 meaning that
/// the interpolation has finished, returning `b`, and values in between
/// meaning that the interpolation is at the relevant point on the timeline
/// between `a` and `this`. The interpolation can be extrapolated beyond 0.0
/// and 1.0, so negative values and values greater than 1.0 are valid (and can
/// easily be generated by curves such as [Curves.elasticInOut]).
///
/// Values for `t` are usually obtained from an [Animation<double>], such as
/// an [AnimationController].
static DecorationImage? lerp(DecorationImage? a, DecorationImage? b, double t) {
if (identical(a, b) || t == 0.0) {
return a;
}
if (t == 1.0) {
return b;
}
return _BlendedDecorationImage(a, b, t);
}
}
/// The painter for a [DecorationImage].
///
/// To obtain a painter, call [DecorationImage.createPainter].
///
/// To paint, call [paint]. The `onChanged` callback passed to
/// [DecorationImage.createPainter] will be called if the image needs to paint
/// again (e.g. because it is animated or because it had not yet loaded the
/// first time the [paint] method was called).
///
/// This object should be disposed using the [dispose] method when it is no
/// longer needed.
abstract interface class DecorationImagePainter {
/// Draw the image onto the given canvas.
///
/// The image is drawn at the position and size given by the `rect` argument.
///
/// The image is clipped to the given `clipPath`, if any.
///
/// The `configuration` object is used to resolve the image (e.g. to pick
/// resolution-specific assets), and to implement the
/// [DecorationImage.matchTextDirection] feature.
///
/// If the image needs to be painted again, e.g. because it is animated or
/// because it had not yet been loaded the first time this method was called,
/// then the `onChanged` callback passed to [DecorationImage.createPainter]
/// will be called.
///
/// The `blend` argument specifies the opacity that should be applied to the
/// image due to this image being blended with another. The `blendMode`
/// argument can be specified to override the [DecorationImagePainter]'s
/// default [BlendMode] behavior. It is usually set to [BlendMode.srcOver] if
/// this is the first or only image being blended, and [BlendMode.plus] if it
/// is being blended with an image below.
void paint(Canvas canvas, Rect rect, Path? clipPath, ImageConfiguration configuration, { double blend = 1.0, BlendMode blendMode = BlendMode.srcOver });
/// Releases the resources used by this painter.
///
/// This should be called whenever the painter is no longer needed.
///
/// After this method has been called, the object is no longer usable.
void dispose();
}
class _DecorationImagePainter implements DecorationImagePainter {
_DecorationImagePainter._(this._details, this._onChanged) {
// TODO(polina-c): stop duplicating code across disposables
// https://github.com/flutter/flutter/issues/137435
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectCreated(
library: 'package:flutter/painting.dart',
className: '$_DecorationImagePainter',
object: this,
);
}
}
final DecorationImage _details;
final VoidCallback _onChanged;
ImageStream? _imageStream;
ImageInfo? _image;
@override
void paint(Canvas canvas, Rect rect, Path? clipPath, ImageConfiguration configuration, { double blend = 1.0, BlendMode blendMode = BlendMode.srcOver }) {
bool flipHorizontally = false;
if (_details.matchTextDirection) {
assert(() {
// We check this first so that the assert will fire immediately, not just
// when the image is ready.
if (configuration.textDirection == null) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('DecorationImage.matchTextDirection can only be used when a TextDirection is available.'),
ErrorDescription(
'When DecorationImagePainter.paint() was called, there was no text direction provided '
'in the ImageConfiguration object to match.',
),
DiagnosticsProperty<DecorationImage>('The DecorationImage was', _details, style: DiagnosticsTreeStyle.errorProperty),
DiagnosticsProperty<ImageConfiguration>('The ImageConfiguration was', configuration, style: DiagnosticsTreeStyle.errorProperty),
]);
}
return true;
}());
if (configuration.textDirection == TextDirection.rtl) {
flipHorizontally = true;
}
}
final ImageStream newImageStream = _details.image.resolve(configuration);
if (newImageStream.key != _imageStream?.key) {
final ImageStreamListener listener = ImageStreamListener(
_handleImage,
onError: _details.onError,
);
_imageStream?.removeListener(listener);
_imageStream = newImageStream;
_imageStream!.addListener(listener);
}
if (_image == null) {
return;
}
if (clipPath != null) {
canvas.save();
canvas.clipPath(clipPath);
}
paintImage(
canvas: canvas,
rect: rect,
image: _image!.image,
debugImageLabel: _image!.debugLabel,
scale: _details.scale * _image!.scale,
colorFilter: _details.colorFilter,
fit: _details.fit,
alignment: _details.alignment.resolve(configuration.textDirection),
centerSlice: _details.centerSlice,
repeat: _details.repeat,
flipHorizontally: flipHorizontally,
opacity: _details.opacity * blend,
filterQuality: _details.filterQuality,
invertColors: _details.invertColors,
isAntiAlias: _details.isAntiAlias,
blendMode: blendMode,
);
if (clipPath != null) {
canvas.restore();
}
}
void _handleImage(ImageInfo value, bool synchronousCall) {
if (_image == value) {
return;
}
if (_image != null && _image!.isCloneOf(value)) {
value.dispose();
return;
}
_image?.dispose();
_image = value;
if (!synchronousCall) {
_onChanged();
}
}
@override
void dispose() {
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this);
}
_imageStream?.removeListener(ImageStreamListener(
_handleImage,
onError: _details.onError,
));
_image?.dispose();
_image = null;
}
@override
String toString() {
return '${objectRuntimeType(this, 'DecorationImagePainter')}(stream: $_imageStream, image: $_image) for $_details';
}
}
/// Used by [paintImage] to report image sizes drawn at the end of the frame.
Map<String, ImageSizeInfo> _pendingImageSizeInfo = <String, ImageSizeInfo>{};
/// [ImageSizeInfo]s that were reported on the last frame.
///
/// Used to prevent duplicative reports from frame to frame.
Set<ImageSizeInfo> _lastFrameImageSizeInfo = <ImageSizeInfo>{};
/// Flushes inter-frame tracking of image size information from [paintImage].
///
/// Has no effect if asserts are disabled.
@visibleForTesting
void debugFlushLastFrameImageSizeInfo() {
assert(() {
_lastFrameImageSizeInfo = <ImageSizeInfo>{};
return true;
}());
}
/// Paints an image into the given rectangle on the canvas.
///
/// The arguments have the following meanings:
///
/// * `canvas`: The canvas onto which the image will be painted.
///
/// * `rect`: The region of the canvas into which the image will be painted.
/// The image might not fill the entire rectangle (e.g., depending on the
/// `fit`). If `rect` is empty, nothing is painted.
///
/// * `image`: The image to paint onto the canvas.
///
/// * `scale`: The number of image pixels for each logical pixel.
///
/// * `opacity`: The opacity to paint the image onto the canvas with.
///
/// * `colorFilter`: If non-null, the color filter to apply when painting the
/// image.
///
/// * `fit`: How the image should be inscribed into `rect`. If null, the
/// default behavior depends on `centerSlice`. If `centerSlice` is also null,
/// the default behavior is [BoxFit.scaleDown]. If `centerSlice` is
/// non-null, the default behavior is [BoxFit.fill]. See [BoxFit] for
/// details.
///
/// * `alignment`: How the destination rectangle defined by applying `fit` is
/// aligned within `rect`. For example, if `fit` is [BoxFit.contain] and
/// `alignment` is [Alignment.bottomRight], the image will be as large
/// as possible within `rect` and placed with its bottom right corner at the
/// bottom right corner of `rect`. Defaults to [Alignment.center].
///
/// * `centerSlice`: The image is drawn in nine portions described by splitting
/// the image by drawing two horizontal lines and two vertical lines, where
/// `centerSlice` describes the rectangle formed by the four points where
/// these four lines intersect each other. (This forms a 3-by-3 grid
/// of regions, the center region being described by `centerSlice`.)
/// The four regions in the corners are drawn, without scaling, in the four
/// corners of the destination rectangle defined by applying `fit`. The
/// remaining five regions are drawn by stretching them to fit such that they
/// exactly cover the destination rectangle while maintaining their relative
/// positions. See also [Canvas.drawImageNine].
///
/// * `repeat`: If the image does not fill `rect`, whether and how the image
/// should be repeated to fill `rect`. By default, the image is not repeated.
/// See [ImageRepeat] for details.
///
/// * `flipHorizontally`: Whether to flip the image horizontally. This is
/// occasionally used with images in right-to-left environments, for images
/// that were designed for left-to-right locales (or vice versa). Be careful,
/// when using this, to not flip images with integral shadows, text, or other
/// effects that will look incorrect when flipped.
///
/// * `invertColors`: Inverting the colors of an image applies a new color
/// filter to the paint. If there is another specified color filter, the
/// invert will be applied after it. This is primarily used for implementing
/// smart invert on iOS.
///
/// * `filterQuality`: Use this to change the quality when scaling an image.
/// Use the [FilterQuality.low] quality setting to scale the image, which corresponds to
/// bilinear interpolation, rather than the default [FilterQuality.none] which corresponds
/// to nearest-neighbor.
///
/// See also:
///
/// * [paintBorder], which paints a border around a rectangle on a canvas.
/// * [DecorationImage], which holds a configuration for calling this function.
/// * [BoxDecoration], which uses this function to paint a [DecorationImage].
void paintImage({
required Canvas canvas,
required Rect rect,
required ui.Image image,
String? debugImageLabel,
double scale = 1.0,
double opacity = 1.0,
ColorFilter? colorFilter,
BoxFit? fit,
Alignment alignment = Alignment.center,
Rect? centerSlice,
ImageRepeat repeat = ImageRepeat.noRepeat,
bool flipHorizontally = false,
bool invertColors = false,
FilterQuality filterQuality = FilterQuality.low,
bool isAntiAlias = false,
BlendMode blendMode = BlendMode.srcOver,
}) {
assert(
image.debugGetOpenHandleStackTraces()?.isNotEmpty ?? true,
'Cannot paint an image that is disposed.\n'
'The caller of paintImage is expected to wait to dispose the image until '
'after painting has completed.',
);
if (rect.isEmpty) {
return;
}
Size outputSize = rect.size;
Size inputSize = Size(image.width.toDouble(), image.height.toDouble());
Offset? sliceBorder;
if (centerSlice != null) {
sliceBorder = inputSize / scale - centerSlice.size as Offset;
outputSize = outputSize - sliceBorder as Size;
inputSize = inputSize - sliceBorder * scale as Size;
}
fit ??= centerSlice == null ? BoxFit.scaleDown : BoxFit.fill;
assert(centerSlice == null || (fit != BoxFit.none && fit != BoxFit.cover));
final FittedSizes fittedSizes = applyBoxFit(fit, inputSize / scale, outputSize);
final Size sourceSize = fittedSizes.source * scale;
Size destinationSize = fittedSizes.destination;
if (centerSlice != null) {
outputSize += sliceBorder!;
destinationSize += sliceBorder;
// We don't have the ability to draw a subset of the image at the same time
// as we apply a nine-patch stretch.
assert(sourceSize == inputSize, 'centerSlice was used with a BoxFit that does not guarantee that the image is fully visible.');
}
if (repeat != ImageRepeat.noRepeat && destinationSize == outputSize) {
// There's no need to repeat the image because we're exactly filling the
// output rect with the image.
repeat = ImageRepeat.noRepeat;
}
final Paint paint = Paint()..isAntiAlias = isAntiAlias;
if (colorFilter != null) {
paint.colorFilter = colorFilter;
}
paint.color = Color.fromRGBO(0, 0, 0, clampDouble(opacity, 0.0, 1.0));
paint.filterQuality = filterQuality;
paint.invertColors = invertColors;
paint.blendMode = blendMode;
final double halfWidthDelta = (outputSize.width - destinationSize.width) / 2.0;
final double halfHeightDelta = (outputSize.height - destinationSize.height) / 2.0;
final double dx = halfWidthDelta + (flipHorizontally ? -alignment.x : alignment.x) * halfWidthDelta;
final double dy = halfHeightDelta + alignment.y * halfHeightDelta;
final Offset destinationPosition = rect.topLeft.translate(dx, dy);
final Rect destinationRect = destinationPosition & destinationSize;
// Set to true if we added a saveLayer to the canvas to invert/flip the image.
bool invertedCanvas = false;
// Output size and destination rect are fully calculated.
// Implement debug-mode and profile-mode features:
// - cacheWidth/cacheHeight warning
// - debugInvertOversizedImages
// - debugOnPaintImage
// - Flutter.ImageSizesForFrame events in timeline
if (!kReleaseMode) {
// We can use the devicePixelRatio of the views directly here (instead of
// going through a MediaQuery) because if it changes, whatever is aware of
// the MediaQuery will be repainting the image anyways.
// Furthermore, for the memory check below we just assume that all images
// are decoded for the view with the highest device pixel ratio and use that
// as an upper bound for the display size of the image.
final double maxDevicePixelRatio = PaintingBinding.instance.platformDispatcher.views.fold(
0.0,
(double previousValue, ui.FlutterView view) => math.max(previousValue, view.devicePixelRatio),
);
final ImageSizeInfo sizeInfo = ImageSizeInfo(
// Some ImageProvider implementations may not have given this.
source: debugImageLabel ?? '<Unknown Image(${image.width}×${image.height})>',
imageSize: Size(image.width.toDouble(), image.height.toDouble()),
displaySize: outputSize * maxDevicePixelRatio,
);
assert(() {
if (debugInvertOversizedImages &&
sizeInfo.decodedSizeInBytes > sizeInfo.displaySizeInBytes + debugImageOverheadAllowance) {
final int overheadInKilobytes = (sizeInfo.decodedSizeInBytes - sizeInfo.displaySizeInBytes) ~/ 1024;
final int outputWidth = sizeInfo.displaySize.width.toInt();
final int outputHeight = sizeInfo.displaySize.height.toInt();
FlutterError.reportError(FlutterErrorDetails(
exception: 'Image $debugImageLabel has a display size of '
'$outputWidth×$outputHeight but a decode size of '
'${image.width}×${image.height}, which uses an additional '
'${overheadInKilobytes}KB (assuming a device pixel ratio of '
'$maxDevicePixelRatio).\n\n'
'Consider resizing the asset ahead of time, supplying a cacheWidth '
'parameter of $outputWidth, a cacheHeight parameter of '
'$outputHeight, or using a ResizeImage.',
library: 'painting library',
context: ErrorDescription('while painting an image'),
));
// Invert the colors of the canvas.
canvas.saveLayer(
destinationRect,
Paint()..colorFilter = const ColorFilter.matrix(<double>[
-1, 0, 0, 0, 255,
0, -1, 0, 0, 255,
0, 0, -1, 0, 255,
0, 0, 0, 1, 0,
]),
);
// Flip the canvas vertically.
final double dy = -(rect.top + rect.height / 2.0);
canvas.translate(0.0, -dy);
canvas.scale(1.0, -1.0);
canvas.translate(0.0, dy);
invertedCanvas = true;
}
return true;
}());
// Avoid emitting events that are the same as those emitted in the last frame.
if (!_lastFrameImageSizeInfo.contains(sizeInfo)) {
final ImageSizeInfo? existingSizeInfo = _pendingImageSizeInfo[sizeInfo.source];
if (existingSizeInfo == null || existingSizeInfo.displaySizeInBytes < sizeInfo.displaySizeInBytes) {
_pendingImageSizeInfo[sizeInfo.source!] = sizeInfo;
}
debugOnPaintImage?.call(sizeInfo);
SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) {
_lastFrameImageSizeInfo = _pendingImageSizeInfo.values.toSet();
if (_pendingImageSizeInfo.isEmpty) {
return;
}
developer.postEvent(
'Flutter.ImageSizesForFrame',
<String, Object>{
for (final ImageSizeInfo imageSizeInfo in _pendingImageSizeInfo.values)
imageSizeInfo.source!: imageSizeInfo.toJson(),
},
);
_pendingImageSizeInfo = <String, ImageSizeInfo>{};
}, debugLabel: 'paintImage.recordImageSizes');
}
}
final bool needSave = centerSlice != null || repeat != ImageRepeat.noRepeat || flipHorizontally;
if (needSave) {
canvas.save();
}
if (repeat != ImageRepeat.noRepeat) {
canvas.clipRect(rect);
}
if (flipHorizontally) {
final double dx = -(rect.left + rect.width / 2.0);
canvas.translate(-dx, 0.0);
canvas.scale(-1.0, 1.0);
canvas.translate(dx, 0.0);
}
if (centerSlice == null) {
final Rect sourceRect = alignment.inscribe(
sourceSize, Offset.zero & inputSize,
);
if (repeat == ImageRepeat.noRepeat) {
canvas.drawImageRect(image, sourceRect, destinationRect, paint);
} else {
for (final Rect tileRect in _generateImageTileRects(rect, destinationRect, repeat)) {
canvas.drawImageRect(image, sourceRect, tileRect, paint);
}
}
} else {
canvas.scale(1 / scale);
if (repeat == ImageRepeat.noRepeat) {
canvas.drawImageNine(image, _scaleRect(centerSlice, scale), _scaleRect(destinationRect, scale), paint);
} else {
for (final Rect tileRect in _generateImageTileRects(rect, destinationRect, repeat)) {
canvas.drawImageNine(image, _scaleRect(centerSlice, scale), _scaleRect(tileRect, scale), paint);
}
}
}
if (needSave) {
canvas.restore();
}
if (invertedCanvas) {
canvas.restore();
}
}
Iterable<Rect> _generateImageTileRects(Rect outputRect, Rect fundamentalRect, ImageRepeat repeat) {
int startX = 0;
int startY = 0;
int stopX = 0;
int stopY = 0;
final double strideX = fundamentalRect.width;
final double strideY = fundamentalRect.height;
if (repeat == ImageRepeat.repeat || repeat == ImageRepeat.repeatX) {
startX = ((outputRect.left - fundamentalRect.left) / strideX).floor();
stopX = ((outputRect.right - fundamentalRect.right) / strideX).ceil();
}
if (repeat == ImageRepeat.repeat || repeat == ImageRepeat.repeatY) {
startY = ((outputRect.top - fundamentalRect.top) / strideY).floor();
stopY = ((outputRect.bottom - fundamentalRect.bottom) / strideY).ceil();
}
return <Rect>[
for (int i = startX; i <= stopX; ++i)
for (int j = startY; j <= stopY; ++j)
fundamentalRect.shift(Offset(i * strideX, j * strideY)),
];
}
Rect _scaleRect(Rect rect, double scale) => Rect.fromLTRB(rect.left * scale, rect.top * scale, rect.right * scale, rect.bottom * scale);
// Implements DecorationImage.lerp when the image is different.
//
// This class just paints both decorations on top of each other, blended together.
//
// The Decoration properties are faked by just forwarded to the target image.
class _BlendedDecorationImage implements DecorationImage {
const _BlendedDecorationImage(this.a, this.b, this.t) : assert(a != null || b != null);
final DecorationImage? a;
final DecorationImage? b;
final double t;
@override
ImageProvider get image => b?.image ?? a!.image;
@override
ImageErrorListener? get onError => b?.onError ?? a!.onError;
@override
ColorFilter? get colorFilter => b?.colorFilter ?? a!.colorFilter;
@override
BoxFit? get fit => b?.fit ?? a!.fit;
@override
AlignmentGeometry get alignment => b?.alignment ?? a!.alignment;
@override
Rect? get centerSlice => b?.centerSlice ?? a!.centerSlice;
@override
ImageRepeat get repeat => b?.repeat ?? a!.repeat;
@override
bool get matchTextDirection => b?.matchTextDirection ?? a!.matchTextDirection;
@override
double get scale => b?.scale ?? a!.scale;
@override
double get opacity => b?.opacity ?? a!.opacity;
@override
FilterQuality get filterQuality => b?.filterQuality ?? a!.filterQuality;
@override
bool get invertColors => b?.invertColors ?? a!.invertColors;
@override
bool get isAntiAlias => b?.isAntiAlias ?? a!.isAntiAlias;
@override
DecorationImagePainter createPainter(VoidCallback onChanged) {
return _BlendedDecorationImagePainter._(
a?.createPainter(onChanged),
b?.createPainter(onChanged),
t,
);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is _BlendedDecorationImage
&& other.a == a
&& other.b == b
&& other.t == t;
}
@override
int get hashCode => Object.hash(a, b, t);
@override
String toString() {
return '${objectRuntimeType(this, '_BlendedDecorationImage')}($a, $b, $t)';
}
}
class _BlendedDecorationImagePainter implements DecorationImagePainter {
_BlendedDecorationImagePainter._(this.a, this.b, this.t) {
// TODO(polina-c): stop duplicating code across disposables
// https://github.com/flutter/flutter/issues/137435
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectCreated(
library: 'package:flutter/painting.dart',
className: '$_BlendedDecorationImagePainter',
object: this,
);
}
}
final DecorationImagePainter? a;
final DecorationImagePainter? b;
final double t;
@override
void paint(Canvas canvas, Rect rect, Path? clipPath, ImageConfiguration configuration, { double blend = 1.0, BlendMode blendMode = BlendMode.srcOver }) {
canvas.saveLayer(null, Paint());
a?.paint(canvas, rect, clipPath, configuration, blend: blend * (1.0 - t), blendMode: blendMode);
b?.paint(canvas, rect, clipPath, configuration, blend: blend * t, blendMode: a != null ? BlendMode.plus : blendMode);
canvas.restore();
}
@override
void dispose() {
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this);
}
a?.dispose();
b?.dispose();
}
@override
String toString() {
return '${objectRuntimeType(this, '_BlendedDecorationImagePainter')}($a, $b, $t)';
}
}
| flutter/packages/flutter/lib/src/painting/decoration_image.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/painting/decoration_image.dart",
"repo_id": "flutter",
"token_count": 10684
} | 808 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'basic_types.dart';
/// Draw a line between two points, which cuts diagonally back and forth across
/// the line that connects the two points.
///
/// The line will cross the line `zigs - 1` times.
///
/// If `zigs` is 1, then this will draw two sides of a triangle from `start` to
/// `end`, with the third point being `width` away from the line, as measured
/// perpendicular to that line.
///
/// If `width` is positive, the first `zig` will be to the left of the `start`
/// point when facing the `end` point. To reverse the zigging polarity, provide
/// a negative `width`.
///
/// The line is drawn using the provided `paint` on the provided `canvas`.
void paintZigZag(Canvas canvas, Paint paint, Offset start, Offset end, int zigs, double width) {
assert(zigs.isFinite);
assert(zigs > 0);
canvas.save();
canvas.translate(start.dx, start.dy);
end = end - start;
canvas.rotate(math.atan2(end.dy, end.dx));
final double length = end.distance;
final double spacing = length / (zigs * 2.0);
final Path path = Path()
..moveTo(0.0, 0.0);
for (int index = 0; index < zigs; index += 1) {
final double x = (index * 2.0 + 1.0) * spacing;
final double y = width * ((index % 2.0) * 2.0 - 1.0);
path.lineTo(x, y);
}
path.lineTo(length, 0.0);
canvas.drawPath(path, paint);
canvas.restore();
}
| flutter/packages/flutter/lib/src/painting/paint_utilities.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/painting/paint_utilities.dart",
"repo_id": "flutter",
"token_count": 506
} | 809 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'simulation.dart';
import 'utils.dart';
export 'tolerance.dart' show Tolerance;
/// Structure that describes a spring's constants.
///
/// Used to configure a [SpringSimulation].
class SpringDescription {
/// Creates a spring given the mass, stiffness, and the damping coefficient.
///
/// See [mass], [stiffness], and [damping] for the units of the arguments.
const SpringDescription({
required this.mass,
required this.stiffness,
required this.damping,
});
/// Creates a spring given the mass (m), stiffness (k), and damping ratio (ζ).
/// The damping ratio is especially useful trying to determining the type of
/// spring to create. A ratio of 1.0 creates a critically damped spring, > 1.0
/// creates an overdamped spring and < 1.0 an underdamped one.
///
/// See [mass] and [stiffness] for the units for those arguments. The damping
/// ratio is unitless.
SpringDescription.withDampingRatio({
required this.mass,
required this.stiffness,
double ratio = 1.0,
}) : damping = ratio * 2.0 * math.sqrt(mass * stiffness);
/// The mass of the spring (m). The units are arbitrary, but all springs
/// within a system should use the same mass units.
final double mass;
/// The spring constant (k). The units of stiffness are M/T², where M is the
/// mass unit used for the value of the [mass] property, and T is the time
/// unit used for driving the [SpringSimulation].
final double stiffness;
/// The damping coefficient (c).
///
/// Do not confuse the damping _coefficient_ (c) with the damping _ratio_ (ζ).
/// To create a [SpringDescription] with a damping ratio, use the [
/// SpringDescription.withDampingRatio] constructor.
///
/// The units of the damping coefficient are M/T, where M is the mass unit
/// used for the value of the [mass] property, and T is the time unit used for
/// driving the [SpringSimulation].
final double damping;
@override
String toString() => '${objectRuntimeType(this, 'SpringDescription')}(mass: ${mass.toStringAsFixed(1)}, stiffness: ${stiffness.toStringAsFixed(1)}, damping: ${damping.toStringAsFixed(1)})';
}
/// The kind of spring solution that the [SpringSimulation] is using to simulate the spring.
///
/// See [SpringSimulation.type].
enum SpringType {
/// A spring that does not bounce and returns to its rest position in the
/// shortest possible time.
criticallyDamped,
/// A spring that bounces.
underDamped,
/// A spring that does not bounce but takes longer to return to its rest
/// position than a [criticallyDamped] one.
overDamped,
}
/// A spring simulation.
///
/// Models a particle attached to a spring that follows Hooke's law.
class SpringSimulation extends Simulation {
/// Creates a spring simulation from the provided spring description, start
/// distance, end distance, and initial velocity.
///
/// The units for the start and end distance arguments are arbitrary, but must
/// be consistent with the units used for other lengths in the system.
///
/// The units for the velocity are L/T, where L is the aforementioned
/// arbitrary unit of length, and T is the time unit used for driving the
/// [SpringSimulation].
SpringSimulation(
SpringDescription spring,
double start,
double end,
double velocity, {
super.tolerance,
}) : _endPosition = end,
_solution = _SpringSolution(spring, start - end, velocity);
final double _endPosition;
final _SpringSolution _solution;
/// The kind of spring being simulated, for debugging purposes.
///
/// This is derived from the [SpringDescription] provided to the [
/// SpringSimulation] constructor.
SpringType get type => _solution.type;
@override
double x(double time) => _endPosition + _solution.x(time);
@override
double dx(double time) => _solution.dx(time);
@override
bool isDone(double time) {
return nearZero(_solution.x(time), tolerance.distance) &&
nearZero(_solution.dx(time), tolerance.velocity);
}
@override
String toString() => '${objectRuntimeType(this, 'SpringSimulation')}(end: ${_endPosition.toStringAsFixed(1)}, $type)';
}
/// A [SpringSimulation] where the value of [x] is guaranteed to have exactly the
/// end value when the simulation [isDone].
class ScrollSpringSimulation extends SpringSimulation {
/// Creates a spring simulation from the provided spring description, start
/// distance, end distance, and initial velocity.
///
/// See the [SpringSimulation.new] constructor on the superclass for a
/// discussion of the arguments' units.
ScrollSpringSimulation(
super.spring,
super.start,
super.end,
super.velocity, {
super.tolerance,
});
@override
double x(double time) => isDone(time) ? _endPosition : super.x(time);
}
// SPRING IMPLEMENTATIONS
abstract class _SpringSolution {
factory _SpringSolution(
SpringDescription spring,
double initialPosition,
double initialVelocity,
) {
final double cmk = spring.damping * spring.damping - 4 * spring.mass * spring.stiffness;
if (cmk == 0.0) {
return _CriticalSolution(spring, initialPosition, initialVelocity);
}
if (cmk > 0.0) {
return _OverdampedSolution(spring, initialPosition, initialVelocity);
}
return _UnderdampedSolution(spring, initialPosition, initialVelocity);
}
double x(double time);
double dx(double time);
SpringType get type;
}
class _CriticalSolution implements _SpringSolution {
factory _CriticalSolution(
SpringDescription spring,
double distance,
double velocity,
) {
final double r = -spring.damping / (2.0 * spring.mass);
final double c1 = distance;
final double c2 = velocity - (r * distance);
return _CriticalSolution.withArgs(r, c1, c2);
}
_CriticalSolution.withArgs(double r, double c1, double c2)
: _r = r,
_c1 = c1,
_c2 = c2;
final double _r, _c1, _c2;
@override
double x(double time) {
return (_c1 + _c2 * time) * math.pow(math.e, _r * time);
}
@override
double dx(double time) {
final double power = math.pow(math.e, _r * time) as double;
return _r * (_c1 + _c2 * time) * power + _c2 * power;
}
@override
SpringType get type => SpringType.criticallyDamped;
}
class _OverdampedSolution implements _SpringSolution {
factory _OverdampedSolution(
SpringDescription spring,
double distance,
double velocity,
) {
final double cmk = spring.damping * spring.damping - 4 * spring.mass * spring.stiffness;
final double r1 = (-spring.damping - math.sqrt(cmk)) / (2.0 * spring.mass);
final double r2 = (-spring.damping + math.sqrt(cmk)) / (2.0 * spring.mass);
final double c2 = (velocity - r1 * distance) / (r2 - r1);
final double c1 = distance - c2;
return _OverdampedSolution.withArgs(r1, r2, c1, c2);
}
_OverdampedSolution.withArgs(double r1, double r2, double c1, double c2)
: _r1 = r1,
_r2 = r2,
_c1 = c1,
_c2 = c2;
final double _r1, _r2, _c1, _c2;
@override
double x(double time) {
return _c1 * math.pow(math.e, _r1 * time) +
_c2 * math.pow(math.e, _r2 * time);
}
@override
double dx(double time) {
return _c1 * _r1 * math.pow(math.e, _r1 * time) +
_c2 * _r2 * math.pow(math.e, _r2 * time);
}
@override
SpringType get type => SpringType.overDamped;
}
class _UnderdampedSolution implements _SpringSolution {
factory _UnderdampedSolution(
SpringDescription spring,
double distance,
double velocity,
) {
final double w = math.sqrt(4.0 * spring.mass * spring.stiffness - spring.damping * spring.damping) /
(2.0 * spring.mass);
final double r = -(spring.damping / 2.0 * spring.mass);
final double c1 = distance;
final double c2 = (velocity - r * distance) / w;
return _UnderdampedSolution.withArgs(w, r, c1, c2);
}
_UnderdampedSolution.withArgs(double w, double r, double c1, double c2)
: _w = w,
_r = r,
_c1 = c1,
_c2 = c2;
final double _w, _r, _c1, _c2;
@override
double x(double time) {
return (math.pow(math.e, _r * time) as double) *
(_c1 * math.cos(_w * time) + _c2 * math.sin(_w * time));
}
@override
double dx(double time) {
final double power = math.pow(math.e, _r * time) as double;
final double cosine = math.cos(_w * time);
final double sine = math.sin(_w * time);
return power * (_c2 * _w * cosine - _c1 * _w * sine) +
_r * power * (_c2 * sine + _c1 * cosine);
}
@override
SpringType get type => SpringType.underDamped;
}
| flutter/packages/flutter/lib/src/physics/spring_simulation.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/physics/spring_simulation.dart",
"repo_id": "flutter",
"token_count": 3011
} | 810 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/scheduler.dart';
import 'package:vector_math/vector_math_64.dart';
import 'debug.dart';
/// Information collected for an annotation that is found in the layer tree.
///
/// See also:
///
/// * [Layer.findAnnotations], which create and use objects of this class.
@immutable
class AnnotationEntry<T> {
/// Create an entry of found annotation by providing the object and related
/// information.
const AnnotationEntry({
required this.annotation,
required this.localPosition,
});
/// The annotation object that is found.
final T annotation;
/// The target location described by the local coordinate space of the
/// annotation object.
final Offset localPosition;
@override
String toString() {
return '${objectRuntimeType(this, 'AnnotationEntry')}(annotation: $annotation, localPosition: $localPosition)';
}
}
/// Information collected about a list of annotations that are found in the
/// layer tree.
///
/// See also:
///
/// * [AnnotationEntry], which are members of this class.
/// * [Layer.findAllAnnotations], and [Layer.findAnnotations], which create and
/// use an object of this class.
class AnnotationResult<T> {
final List<AnnotationEntry<T>> _entries = <AnnotationEntry<T>>[];
/// Add a new entry to the end of the result.
///
/// Usually, entries should be added in order from most specific to least
/// specific, typically during an upward walk of the tree.
void add(AnnotationEntry<T> entry) => _entries.add(entry);
/// An unmodifiable list of [AnnotationEntry] objects recorded.
///
/// The first entry is the most specific, typically the one at the leaf of
/// tree.
Iterable<AnnotationEntry<T>> get entries => _entries;
/// An unmodifiable list of annotations recorded.
///
/// The first entry is the most specific, typically the one at the leaf of
/// tree.
///
/// It is similar to [entries] but does not contain other information.
Iterable<T> get annotations {
return _entries.map((AnnotationEntry<T> entry) => entry.annotation);
}
}
const String _flutterRenderingLibrary = 'package:flutter/rendering.dart';
/// A composited layer.
///
/// During painting, the render tree generates a tree of composited layers that
/// are uploaded into the engine and displayed by the compositor. This class is
/// the base class for all composited layers.
///
/// Most layers can have their properties mutated, and layers can be moved to
/// different parents. The scene must be explicitly recomposited after such
/// changes are made; the layer tree does not maintain its own dirty state.
///
/// To composite the tree, create a [SceneBuilder] object, pass it to the
/// root [Layer] object's [addToScene] method, and then call
/// [SceneBuilder.build] to obtain a [Scene]. A [Scene] can then be painted
/// using [dart:ui.FlutterView.render].
///
/// ## Memory
///
/// Layers retain resources between frames to speed up rendering. A layer will
/// retain these resources until all [LayerHandle]s referring to the layer have
/// nulled out their references.
///
/// Layers must not be used after disposal. If a RenderObject needs to maintain
/// a layer for later usage, it must create a handle to that layer. This is
/// handled automatically for the [RenderObject.layer] property, but additional
/// layers must use their own [LayerHandle].
///
/// {@tool snippet}
///
/// This [RenderObject] is a repaint boundary that pushes an additional
/// [ClipRectLayer].
///
/// ```dart
/// class ClippingRenderObject extends RenderBox {
/// final LayerHandle<ClipRectLayer> _clipRectLayer = LayerHandle<ClipRectLayer>();
///
/// @override
/// bool get isRepaintBoundary => true; // The [layer] property will be used.
///
/// @override
/// void paint(PaintingContext context, Offset offset) {
/// _clipRectLayer.layer = context.pushClipRect(
/// needsCompositing,
/// offset,
/// Offset.zero & size,
/// super.paint,
/// oldLayer: _clipRectLayer.layer,
/// );
/// }
///
/// @override
/// void dispose() {
/// _clipRectLayer.layer = null;
/// super.dispose();
/// }
/// }
/// ```
/// {@end-tool}
/// See also:
///
/// * [RenderView.compositeFrame], which implements this recomposition protocol
/// for painting [RenderObject] trees on the display.
abstract class Layer with DiagnosticableTreeMixin {
/// Creates an instance of Layer.
Layer() {
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectCreated(
library: _flutterRenderingLibrary,
className: '$Layer',
object: this,
);
}
}
final Map<int, VoidCallback> _callbacks = <int, VoidCallback>{};
static int _nextCallbackId = 0;
/// Whether the subtree rooted at this layer has any composition callback
/// observers.
///
/// This only evaluates to true if the subtree rooted at this node has
/// observers. For example, it may evaluate to true on a parent node but false
/// on a child if the parent has observers but the child does not.
///
/// See also:
///
/// * [Layer.addCompositionCallback].
bool get subtreeHasCompositionCallbacks => _compositionCallbackCount > 0;
int _compositionCallbackCount = 0;
void _updateSubtreeCompositionObserverCount(int delta) {
assert(delta != 0);
_compositionCallbackCount += delta;
assert(_compositionCallbackCount >= 0);
parent?._updateSubtreeCompositionObserverCount(delta);
}
void _fireCompositionCallbacks({required bool includeChildren}) {
if (_callbacks.isEmpty) {
return;
}
for (final VoidCallback callback in List<VoidCallback>.of(_callbacks.values)) {
callback();
}
}
bool _debugMutationsLocked = false;
/// Whether or not this layer, or any child layers, can be rasterized with
/// [Scene.toImage] or [Scene.toImageSync].
///
/// If `false`, calling the above methods may yield an image which is
/// incomplete.
///
/// This value may change throughout the lifetime of the object, as the
/// child layers themselves are added or removed.
bool supportsRasterization() {
return true;
}
/// Describes the clip that would be applied to contents of this layer,
/// if any.
Rect? describeClipBounds() => null;
/// Adds a callback for when the layer tree that this layer is part of gets
/// composited, or when it is detached and will not be rendered again.
///
/// This callback will fire even if an ancestor layer is added with retained
/// rendering, meaning that it will fire even if this layer gets added to the
/// scene via some call to [ui.SceneBuilder.addRetained] on one of its
/// ancestor layers.
///
/// The callback receives a reference to this layer. The recipient must not
/// mutate the layer during the scope of the callback, but may traverse the
/// tree to find information about the current transform or clip. The layer
/// may not be [attached] anymore in this state, but even if it is detached it
/// may still have an also detached parent it can visit.
///
/// If new callbacks are added or removed within the [callback], the new
/// callbacks will fire (or stop firing) on the _next_ compositing event.
///
/// {@template flutter.rendering.Layer.compositionCallbacks}
/// Composition callbacks are useful in place of pushing a layer that would
/// otherwise try to observe the layer tree without actually affecting
/// compositing. For example, a composition callback may be used to observe
/// the total transform and clip of the current container layer to determine
/// whether a render object drawn into it is visible or not.
///
/// Calling the returned callback will remove [callback] from the composition
/// callbacks.
/// {@endtemplate}
VoidCallback addCompositionCallback(CompositionCallback callback) {
_updateSubtreeCompositionObserverCount(1);
final int callbackId = _nextCallbackId += 1;
_callbacks[callbackId] = () {
assert(() {
_debugMutationsLocked = true;
return true;
}());
callback(this);
assert(() {
_debugMutationsLocked = false;
return true;
}());
};
return () {
assert(debugDisposed || _callbacks.containsKey(callbackId));
_callbacks.remove(callbackId);
_updateSubtreeCompositionObserverCount(-1);
};
}
/// If asserts are enabled, returns whether [dispose] has
/// been called since the last time any retained resources were created.
///
/// Throws an exception if asserts are disabled.
bool get debugDisposed {
late bool disposed;
assert(() {
disposed = _debugDisposed;
return true;
}());
return disposed;
}
bool _debugDisposed = false;
/// Set when this layer is appended to a [ContainerLayer], and
/// unset when it is removed.
///
/// This cannot be set from [attach] or [detach] which is called when an
/// entire subtree is attached to or detached from an owner. Layers may be
/// appended to or removed from a [ContainerLayer] regardless of whether they
/// are attached or detached, and detaching a layer from an owner does not
/// imply that it has been removed from its parent.
final LayerHandle<Layer> _parentHandle = LayerHandle<Layer>();
/// Incremented by [LayerHandle].
int _refCount = 0;
/// Called by [LayerHandle].
void _unref() {
assert(!_debugMutationsLocked);
assert(_refCount > 0);
_refCount -= 1;
if (_refCount == 0) {
dispose();
}
}
/// Returns the number of objects holding a [LayerHandle] to this layer.
///
/// This method throws if asserts are disabled.
int get debugHandleCount {
late int count;
assert(() {
count = _refCount;
return true;
}());
return count;
}
/// Clears any retained resources that this layer holds.
///
/// This method must dispose resources such as [EngineLayer] and [Picture]
/// objects. The layer is still usable after this call, but any graphics
/// related resources it holds will need to be recreated.
///
/// This method _only_ disposes resources for this layer. For example, if it
/// is a [ContainerLayer], it does not dispose resources of any children.
/// However, [ContainerLayer]s do remove any children they have when
/// this method is called, and if this layer was the last holder of a removed
/// child handle, the child may recursively clean up its resources.
///
/// This method automatically gets called when all outstanding [LayerHandle]s
/// are disposed. [LayerHandle] objects are typically held by the [parent]
/// layer of this layer and any [RenderObject]s that participated in creating
/// it.
///
/// After calling this method, the object is unusable.
@mustCallSuper
@protected
@visibleForTesting
void dispose() {
assert(!_debugMutationsLocked);
assert(
!_debugDisposed,
'Layers must only be disposed once. This is typically handled by '
'LayerHandle and createHandle. Subclasses should not directly call '
'dispose, except to call super.dispose() in an overridden dispose '
'method. Tests must only call dispose once.',
);
assert(() {
assert(
_refCount == 0,
'Do not directly call dispose on a $runtimeType. Instead, '
'use createHandle and LayerHandle.dispose.',
);
_debugDisposed = true;
return true;
}());
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this);
}
_engineLayer?.dispose();
_engineLayer = null;
}
/// This layer's parent in the layer tree.
///
/// The [parent] of the root node in the layer tree is null.
///
/// Only subclasses of [ContainerLayer] can have children in the layer tree.
/// All other layer classes are used for leaves in the layer tree.
ContainerLayer? get parent => _parent;
ContainerLayer? _parent;
// Whether this layer has any changes since its last call to [addToScene].
//
// Initialized to true as a new layer has never called [addToScene], and is
// set to false after calling [addToScene]. The value can become true again
// if [markNeedsAddToScene] is called, or when [updateSubtreeNeedsAddToScene]
// is called on this layer or on an ancestor layer.
//
// The values of [_needsAddToScene] in a tree of layers are said to be
// _consistent_ if every layer in the tree satisfies the following:
//
// - If [alwaysNeedsAddToScene] is true, then [_needsAddToScene] is also true.
// - If [_needsAddToScene] is true and [parent] is not null, then
// `parent._needsAddToScene` is true.
//
// Typically, this value is set during the paint phase and during compositing.
// During the paint phase render objects create new layers and call
// [markNeedsAddToScene] on existing layers, causing this value to become
// true. After the paint phase the tree may be in an inconsistent state.
// During compositing [ContainerLayer.buildScene] first calls
// [updateSubtreeNeedsAddToScene] to bring this tree to a consistent state,
// then it calls [addToScene], and finally sets this field to false.
bool _needsAddToScene = true;
/// Mark that this layer has changed and [addToScene] needs to be called.
@protected
@visibleForTesting
void markNeedsAddToScene() {
assert(!_debugMutationsLocked);
assert(
!alwaysNeedsAddToScene,
'$runtimeType with alwaysNeedsAddToScene set called markNeedsAddToScene.\n'
"The layer's alwaysNeedsAddToScene is set to true, and therefore it should not call markNeedsAddToScene.",
);
assert(!_debugDisposed);
// Already marked. Short-circuit.
if (_needsAddToScene) {
return;
}
_needsAddToScene = true;
}
/// Mark that this layer is in sync with engine.
///
/// This is for debugging and testing purposes only. In release builds
/// this method has no effect.
@visibleForTesting
void debugMarkClean() {
assert(!_debugMutationsLocked);
assert(() {
_needsAddToScene = false;
return true;
}());
}
/// Subclasses may override this to true to disable retained rendering.
@protected
bool get alwaysNeedsAddToScene => false;
/// Whether this or any descendant layer in the subtree needs [addToScene].
///
/// This is for debug and test purpose only. It only becomes valid after
/// calling [updateSubtreeNeedsAddToScene].
@visibleForTesting
bool? get debugSubtreeNeedsAddToScene {
bool? result;
assert(() {
result = _needsAddToScene;
return true;
}());
return result;
}
/// Stores the engine layer created for this layer in order to reuse engine
/// resources across frames for better app performance.
///
/// This value may be passed to [ui.SceneBuilder.addRetained] to communicate
/// to the engine that nothing in this layer or any of its descendants
/// changed. The native engine could, for example, reuse the texture rendered
/// in a previous frame. The web engine could, for example, reuse the HTML
/// DOM nodes created for a previous frame.
///
/// This value may be passed as `oldLayer` argument to a "push" method to
/// communicate to the engine that a layer is updating a previously rendered
/// layer. The web engine could, for example, update the properties of
/// previously rendered HTML DOM nodes rather than creating new nodes.
@protected
@visibleForTesting
ui.EngineLayer? get engineLayer => _engineLayer;
/// Sets the engine layer used to render this layer.
///
/// Typically this field is set to the value returned by [addToScene], which
/// in turn returns the engine layer produced by one of [ui.SceneBuilder]'s
/// "push" methods, such as [ui.SceneBuilder.pushOpacity].
@protected
@visibleForTesting
set engineLayer(ui.EngineLayer? value) {
assert(!_debugMutationsLocked);
assert(!_debugDisposed);
_engineLayer?.dispose();
_engineLayer = value;
if (!alwaysNeedsAddToScene) {
// The parent must construct a new engine layer to add this layer to, and
// so we mark it as needing [addToScene].
//
// This is designed to handle two situations:
//
// 1. When rendering the complete layer tree as normal. In this case we
// call child `addToScene` methods first, then we call `set engineLayer`
// for the parent. The children will call `markNeedsAddToScene` on the
// parent to signal that they produced new engine layers and therefore
// the parent needs to update. In this case, the parent is already adding
// itself to the scene via [addToScene], and so after it's done, its
// `set engineLayer` is called and it clears the `_needsAddToScene` flag.
//
// 2. When rendering an interior layer (e.g. `OffsetLayer.toImage`). In
// this case we call `addToScene` for one of the children but not the
// parent, i.e. we produce new engine layers for children but not for the
// parent. Here the children will mark the parent as needing
// `addToScene`, but the parent does not clear the flag until some future
// frame decides to render it, at which point the parent knows that it
// cannot retain its engine layer and will call `addToScene` again.
if (parent != null && !parent!.alwaysNeedsAddToScene) {
parent!.markNeedsAddToScene();
}
}
}
ui.EngineLayer? _engineLayer;
/// Traverses the layer subtree starting from this layer and determines whether it needs [addToScene].
///
/// A layer needs [addToScene] if any of the following is true:
///
/// - [alwaysNeedsAddToScene] is true.
/// - [markNeedsAddToScene] has been called.
/// - Any of its descendants need [addToScene].
///
/// [ContainerLayer] overrides this method to recursively call it on its children.
@protected
@visibleForTesting
void updateSubtreeNeedsAddToScene() {
assert(!_debugMutationsLocked);
_needsAddToScene = _needsAddToScene || alwaysNeedsAddToScene;
}
/// The owner for this layer (null if unattached).
///
/// The entire layer tree that this layer belongs to will have the same owner.
///
/// Typically the owner is a [RenderView].
Object? get owner => _owner;
Object? _owner;
/// Whether the layer tree containing this layer is attached to an owner.
///
/// This becomes true during the call to [attach].
///
/// This becomes false during the call to [detach].
bool get attached => _owner != null;
/// Mark this layer as attached to the given owner.
///
/// Typically called only from the [parent]'s [attach] method, and by the
/// [owner] to mark the root of a tree as attached.
///
/// Subclasses with children should override this method to
/// [attach] all their children to the same [owner]
/// after calling the inherited method, as in `super.attach(owner)`.
@mustCallSuper
void attach(covariant Object owner) {
assert(_owner == null);
_owner = owner;
}
/// Mark this layer as detached from its owner.
///
/// Typically called only from the [parent]'s [detach], and by the [owner] to
/// mark the root of a tree as detached.
///
/// Subclasses with children should override this method to
/// [detach] all their children after calling the inherited method,
/// as in `super.detach()`.
@mustCallSuper
void detach() {
assert(_owner != null);
_owner = null;
assert(parent == null || attached == parent!.attached);
}
/// The depth of this layer in the layer tree.
///
/// The depth of nodes in a tree monotonically increases as you traverse down
/// the tree. There's no guarantee regarding depth between siblings.
///
/// The depth is used to ensure that nodes are processed in depth order.
int get depth => _depth;
int _depth = 0;
/// Adjust the [depth] of this node's children, if any.
///
/// Override this method in subclasses with child nodes to call
/// [ContainerLayer.redepthChild] for each child. Do not call this method
/// directly.
@protected
void redepthChildren() {
// ContainerLayer provides an implementation since its the only one that
// can actually have children.
}
/// This layer's next sibling in the parent layer's child list.
Layer? get nextSibling => _nextSibling;
Layer? _nextSibling;
/// This layer's previous sibling in the parent layer's child list.
Layer? get previousSibling => _previousSibling;
Layer? _previousSibling;
/// Removes this layer from its parent layer's child list.
///
/// This has no effect if the layer's parent is already null.
@mustCallSuper
void remove() {
assert(!_debugMutationsLocked);
parent?._removeChild(this);
}
/// Search this layer and its subtree for annotations of type `S` at the
/// location described by `localPosition`.
///
/// This method is called by the default implementation of [find] and
/// [findAllAnnotations]. Override this method to customize how the layer
/// should search for annotations, or if the layer has its own annotations to
/// add.
///
/// The default implementation always returns `false`, which means neither
/// the layer nor its children has annotations, and the annotation search
/// is not absorbed either (see below for explanation).
///
/// ## About layer annotations
///
/// {@template flutter.rendering.Layer.findAnnotations.aboutAnnotations}
/// An annotation is an optional object of any type that can be carried with a
/// layer. An annotation can be found at a location as long as the owner layer
/// contains the location and is walked to.
///
/// The annotations are searched by first visiting each child recursively,
/// then this layer, resulting in an order from visually front to back.
/// Annotations must meet the given restrictions, such as type and position.
///
/// The common way for a value to be found here is by pushing an
/// [AnnotatedRegionLayer] into the layer tree, or by adding the desired
/// annotation by overriding [findAnnotations].
/// {@endtemplate}
///
/// ## Parameters and return value
///
/// The [result] parameter is where the method outputs the resulting
/// annotations. New annotations found during the walk are added to the tail.
///
/// The [onlyFirst] parameter indicates that, if true, the search will stop
/// when it finds the first qualified annotation; otherwise, it will walk the
/// entire subtree.
///
/// The return value indicates the opacity of this layer and its subtree at
/// this position. If it returns true, then this layer's parent should skip
/// the children behind this layer. In other words, it is opaque to this type
/// of annotation and has absorbed the search so that its siblings behind it
/// are not aware of the search. If the return value is false, then the parent
/// might continue with other siblings.
///
/// The return value does not affect whether the parent adds its own
/// annotations; in other words, if a layer is supposed to add an annotation,
/// it will always add it even if its children are opaque to this type of
/// annotation. However, the opacity that the parents return might be affected
/// by their children, hence making all of its ancestors opaque to this type
/// of annotation.
@protected
bool findAnnotations<S extends Object>(
AnnotationResult<S> result,
Offset localPosition, {
required bool onlyFirst,
}) {
return false;
}
/// Search this layer and its subtree for the first annotation of type `S`
/// under the point described by `localPosition`.
///
/// Returns null if no matching annotations are found.
///
/// By default this method calls [findAnnotations] with `onlyFirst:
/// true` and returns the annotation of the first result. Prefer overriding
/// [findAnnotations] instead of this method, because during an annotation
/// search, only [findAnnotations] is recursively called, while custom
/// behavior in this method is ignored.
///
/// ## About layer annotations
///
/// {@macro flutter.rendering.Layer.findAnnotations.aboutAnnotations}
///
/// See also:
///
/// * [findAllAnnotations], which is similar but returns all annotations found
/// at the given position.
/// * [AnnotatedRegionLayer], for placing values in the layer tree.
S? find<S extends Object>(Offset localPosition) {
final AnnotationResult<S> result = AnnotationResult<S>();
findAnnotations<S>(result, localPosition, onlyFirst: true);
return result.entries.isEmpty ? null : result.entries.first.annotation;
}
/// Search this layer and its subtree for all annotations of type `S` under
/// the point described by `localPosition`.
///
/// Returns a result with empty entries if no matching annotations are found.
///
/// By default this method calls [findAnnotations] with `onlyFirst:
/// false` and returns the annotations of its result. Prefer overriding
/// [findAnnotations] instead of this method, because during an annotation
/// search, only [findAnnotations] is recursively called, while custom
/// behavior in this method is ignored.
///
/// ## About layer annotations
///
/// {@macro flutter.rendering.Layer.findAnnotations.aboutAnnotations}
///
/// See also:
///
/// * [find], which is similar but returns the first annotation found at the
/// given position.
/// * [AnnotatedRegionLayer], for placing values in the layer tree.
AnnotationResult<S> findAllAnnotations<S extends Object>(Offset localPosition) {
final AnnotationResult<S> result = AnnotationResult<S>();
findAnnotations<S>(result, localPosition, onlyFirst: false);
return result;
}
/// Override this method to upload this layer to the engine.
@protected
void addToScene(ui.SceneBuilder builder);
void _addToSceneWithRetainedRendering(ui.SceneBuilder builder) {
assert(!_debugMutationsLocked);
// There can't be a loop by adding a retained layer subtree whose
// _needsAddToScene is false.
//
// Proof by contradiction:
//
// If we introduce a loop, this retained layer must be appended to one of
// its descendant layers, say A. That means the child structure of A has
// changed so A's _needsAddToScene is true. This contradicts
// _needsAddToScene being false.
if (!_needsAddToScene && _engineLayer != null) {
builder.addRetained(_engineLayer!);
return;
}
addToScene(builder);
// Clearing the flag _after_ calling `addToScene`, not _before_. This is
// because `addToScene` calls children's `addToScene` methods, which may
// mark this layer as dirty.
_needsAddToScene = false;
}
/// The object responsible for creating this layer.
///
/// Defaults to the value of [RenderObject.debugCreator] for the render object
/// that created this layer. Used in debug messages.
Object? debugCreator;
@override
String toStringShort() => '${super.toStringShort()}${ owner == null ? " DETACHED" : ""}';
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Object>('owner', owner, level: parent != null ? DiagnosticLevel.hidden : DiagnosticLevel.info, defaultValue: null));
properties.add(DiagnosticsProperty<Object?>('creator', debugCreator, defaultValue: null, level: DiagnosticLevel.debug));
if (_engineLayer != null) {
properties.add(DiagnosticsProperty<String>('engine layer', describeIdentity(_engineLayer)));
}
properties.add(DiagnosticsProperty<int>('handles', debugHandleCount));
}
}
/// A handle to prevent a [Layer]'s platform graphics resources from being
/// disposed.
///
/// [Layer] objects retain native resources such as [EngineLayer]s and [Picture]
/// objects. These objects may in turn retain large chunks of texture memory,
/// either directly or indirectly.
///
/// The layer's native resources must be retained as long as there is some
/// object that can add it to a scene. Typically, this is either its
/// [Layer.parent] or an undisposed [RenderObject] that will append it to a
/// [ContainerLayer]. Layers automatically hold a handle to their children, and
/// RenderObjects automatically hold a handle to their [RenderObject.layer] as
/// well as any [PictureLayer]s that they paint into using the
/// [PaintingContext.canvas]. A layer automatically releases its resources once
/// at least one handle has been acquired and all handles have been disposed.
/// [RenderObject]s that create additional layer objects must manually manage
/// the handles for that layer similarly to the implementation of
/// [RenderObject.layer].
///
/// A handle is automatically managed for [RenderObject.layer].
///
/// If a [RenderObject] creates layers in addition to its [RenderObject.layer]
/// and it intends to reuse those layers separately from [RenderObject.layer],
/// it must create a handle to that layer and dispose of it when the layer is
/// no longer needed. For example, if it re-creates or nulls out an existing
/// layer in [RenderObject.paint], it should dispose of the handle to the
/// old layer. It should also dispose of any layer handles it holds in
/// [RenderObject.dispose].
class LayerHandle<T extends Layer> {
/// Create a new layer handle, optionally referencing a [Layer].
LayerHandle([this._layer]) {
if (_layer != null) {
_layer!._refCount += 1;
}
}
T? _layer;
/// The [Layer] whose resources this object keeps alive.
///
/// Setting a new value or null will dispose the previously held layer if
/// there are no other open handles to that layer.
T? get layer => _layer;
set layer(T? layer) {
assert(
layer?.debugDisposed != true,
'Attempted to create a handle to an already disposed layer: $layer.',
);
if (identical(layer, _layer)) {
return;
}
_layer?._unref();
_layer = layer;
if (_layer != null) {
_layer!._refCount += 1;
}
}
@override
String toString() => 'LayerHandle(${_layer != null ? _layer.toString() : 'DISPOSED'})';
}
/// A composited layer containing a [Picture].
///
/// Picture layers are always leaves in the layer tree. They are also
/// responsible for disposing of the [Picture] object they hold. This is
/// typically done when their parent and all [RenderObject]s that participated
/// in painting the picture have been disposed.
class PictureLayer extends Layer {
/// Creates a leaf layer for the layer tree.
PictureLayer(this.canvasBounds);
/// The bounds that were used for the canvas that drew this layer's [picture].
///
/// This is purely advisory. It is included in the information dumped with
/// [debugDumpLayerTree] (which can be triggered by pressing "L" when using
/// "flutter run" at the console), which can help debug why certain drawing
/// commands are being culled.
final Rect canvasBounds;
/// The picture recorded for this layer.
///
/// The picture's coordinate system matches this layer's coordinate system.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
ui.Picture? get picture => _picture;
ui.Picture? _picture;
set picture(ui.Picture? picture) {
assert(!_debugDisposed);
markNeedsAddToScene();
_picture?.dispose();
_picture = picture;
}
/// Hints that the painting in this layer is complex and would benefit from
/// caching.
///
/// If this hint is not set, the compositor will apply its own heuristics to
/// decide whether the this layer is complex enough to benefit from caching.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
bool get isComplexHint => _isComplexHint;
bool _isComplexHint = false;
set isComplexHint(bool value) {
if (value != _isComplexHint) {
_isComplexHint = value;
markNeedsAddToScene();
}
}
/// Hints that the painting in this layer is likely to change next frame.
///
/// This hint tells the compositor not to cache this layer because the cache
/// will not be used in the future. If this hint is not set, the compositor
/// will apply its own heuristics to decide whether this layer is likely to be
/// reused in the future.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
bool get willChangeHint => _willChangeHint;
bool _willChangeHint = false;
set willChangeHint(bool value) {
if (value != _willChangeHint) {
_willChangeHint = value;
markNeedsAddToScene();
}
}
@override
void dispose() {
picture = null; // Will dispose _picture.
super.dispose();
}
@override
void addToScene(ui.SceneBuilder builder) {
assert(picture != null);
builder.addPicture(Offset.zero, picture!, isComplexHint: isComplexHint, willChangeHint: willChangeHint);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Rect>('paint bounds', canvasBounds));
properties.add(DiagnosticsProperty<String>('picture', describeIdentity(_picture)));
properties.add(DiagnosticsProperty<String>(
'raster cache hints',
'isComplex = $isComplexHint, willChange = $willChangeHint',
));
}
@override
bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
return false;
}
}
/// A composited layer that maps a backend texture to a rectangle.
///
/// Backend textures are images that can be applied (mapped) to an area of the
/// Flutter view. They are created, managed, and updated using a
/// platform-specific texture registry. This is typically done by a plugin
/// that integrates with host platform video player, camera, or OpenGL APIs,
/// or similar image sources.
///
/// A texture layer refers to its backend texture using an integer ID. Texture
/// IDs are obtained from the texture registry and are scoped to the Flutter
/// view. Texture IDs may be reused after deregistration, at the discretion
/// of the registry. The use of texture IDs currently unknown to the registry
/// will silently result in a blank rectangle.
///
/// Once inserted into the layer tree, texture layers are repainted autonomously
/// as dictated by the backend (e.g. on arrival of a video frame). Such
/// repainting generally does not involve executing Dart code.
///
/// Texture layers are always leaves in the layer tree.
///
/// See also:
///
/// * [TextureRegistry](/javadoc/io/flutter/view/TextureRegistry.html)
/// for how to create and manage backend textures on Android.
/// * [TextureRegistry Protocol](/ios-embedder/protocol_flutter_texture_registry-p.html)
/// for how to create and manage backend textures on iOS.
class TextureLayer extends Layer {
/// Creates a texture layer bounded by [rect] and with backend texture
/// identified by [textureId], if [freeze] is true new texture frames will not be
/// populated to the texture, and use [filterQuality] to set layer's [FilterQuality].
TextureLayer({
required this.rect,
required this.textureId,
this.freeze = false,
this.filterQuality = ui.FilterQuality.low,
});
/// Bounding rectangle of this layer.
final Rect rect;
/// The identity of the backend texture.
final int textureId;
/// When true the texture will not be updated with new frames.
///
/// This is used for resizing embedded Android views: when resizing there
/// is a short period during which the framework cannot tell if the newest
/// texture frame has the previous or new size; to work around this, the
/// framework "freezes" the texture just before resizing the Android view and
/// un-freezes it when it is certain that a frame with the new size is ready.
final bool freeze;
/// {@macro flutter.widgets.Texture.filterQuality}
final ui.FilterQuality filterQuality;
@override
void addToScene(ui.SceneBuilder builder) {
builder.addTexture(
textureId,
offset: rect.topLeft,
width: rect.width,
height: rect.height,
freeze: freeze,
filterQuality: filterQuality,
);
}
@override
bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
return false;
}
}
/// A layer that shows an embedded [UIView](https://developer.apple.com/documentation/uikit/uiview)
/// on iOS.
class PlatformViewLayer extends Layer {
/// Creates a platform view layer.
PlatformViewLayer({
required this.rect,
required this.viewId,
});
/// Bounding rectangle of this layer in the global coordinate space.
final Rect rect;
/// The unique identifier of the UIView displayed on this layer.
///
/// A UIView with this identifier must have been created by [PlatformViewsService.initUiKitView].
final int viewId;
@override
bool supportsRasterization() {
return false;
}
@override
void addToScene(ui.SceneBuilder builder) {
builder.addPlatformView(
viewId,
offset: rect.topLeft,
width: rect.width,
height: rect.height,
);
}
}
/// A layer that indicates to the compositor that it should display
/// certain performance statistics within it.
///
/// Performance overlay layers are always leaves in the layer tree.
class PerformanceOverlayLayer extends Layer {
/// Creates a layer that displays a performance overlay.
PerformanceOverlayLayer({
required Rect overlayRect,
required this.optionsMask,
required this.rasterizerThreshold,
required this.checkerboardRasterCacheImages,
required this.checkerboardOffscreenLayers,
}) : _overlayRect = overlayRect;
/// The rectangle in this layer's coordinate system that the overlay should occupy.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
Rect get overlayRect => _overlayRect;
Rect _overlayRect;
set overlayRect(Rect value) {
if (value != _overlayRect) {
_overlayRect = value;
markNeedsAddToScene();
}
}
/// The mask is created by shifting 1 by the index of the specific
/// [PerformanceOverlayOption] to enable.
final int optionsMask;
/// The rasterizer threshold is an integer specifying the number of frame
/// intervals that the rasterizer must miss before it decides that the frame
/// is suitable for capturing an SkPicture trace for further analysis.
final int rasterizerThreshold;
/// Whether the raster cache should checkerboard cached entries.
///
/// The compositor can sometimes decide to cache certain portions of the
/// widget hierarchy. Such portions typically don't change often from frame to
/// frame and are expensive to render. This can speed up overall rendering. However,
/// there is certain upfront cost to constructing these cache entries. And, if
/// the cache entries are not used very often, this cost may not be worth the
/// speedup in rendering of subsequent frames. If the developer wants to be certain
/// that populating the raster cache is not causing stutters, this option can be
/// set. Depending on the observations made, hints can be provided to the compositor
/// that aid it in making better decisions about caching.
final bool checkerboardRasterCacheImages;
/// Whether the compositor should checkerboard layers that are rendered to offscreen
/// bitmaps. This can be useful for debugging rendering performance.
///
/// Render target switches are caused by using opacity layers (via a [FadeTransition] or
/// [Opacity] widget), clips, shader mask layers, etc. Selecting a new render target
/// and merging it with the rest of the scene has a performance cost. This can sometimes
/// be avoided by using equivalent widgets that do not require these layers (for example,
/// replacing an [Opacity] widget with an [widgets.Image] using a [BlendMode]).
final bool checkerboardOffscreenLayers;
@override
void addToScene(ui.SceneBuilder builder) {
builder.addPerformanceOverlay(optionsMask, overlayRect);
builder.setRasterizerTracingThreshold(rasterizerThreshold);
builder.setCheckerboardRasterCacheImages(checkerboardRasterCacheImages);
builder.setCheckerboardOffscreenLayers(checkerboardOffscreenLayers);
}
@override
bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
return false;
}
}
/// The signature of the callback added in [Layer.addCompositionCallback].
typedef CompositionCallback = void Function(Layer layer);
/// A composited layer that has a list of children.
///
/// A [ContainerLayer] instance merely takes a list of children and inserts them
/// into the composited rendering in order. There are subclasses of
/// [ContainerLayer] which apply more elaborate effects in the process.
class ContainerLayer extends Layer {
@override
void _fireCompositionCallbacks({required bool includeChildren}) {
super._fireCompositionCallbacks(includeChildren: includeChildren);
if (!includeChildren) {
return;
}
Layer? child = firstChild;
while (child != null) {
child._fireCompositionCallbacks(includeChildren: includeChildren);
child = child.nextSibling;
}
}
/// The first composited layer in this layer's child list.
Layer? get firstChild => _firstChild;
Layer? _firstChild;
/// The last composited layer in this layer's child list.
Layer? get lastChild => _lastChild;
Layer? _lastChild;
/// Returns whether this layer has at least one child layer.
bool get hasChildren => _firstChild != null;
@override
bool supportsRasterization() {
for (Layer? child = lastChild; child != null; child = child.previousSibling) {
if (!child.supportsRasterization()) {
return false;
}
}
return true;
}
/// Consider this layer as the root and build a scene (a tree of layers)
/// in the engine.
// The reason this method is in the `ContainerLayer` class rather than
// `PipelineOwner` or other singleton level is because this method can be used
// both to render the whole layer tree (e.g. a normal application frame) and
// to render a subtree (e.g. `OffsetLayer.toImage`).
ui.Scene buildScene(ui.SceneBuilder builder) {
updateSubtreeNeedsAddToScene();
addToScene(builder);
if (subtreeHasCompositionCallbacks) {
_fireCompositionCallbacks(includeChildren: true);
}
// Clearing the flag _after_ calling `addToScene`, not _before_. This is
// because `addToScene` calls children's `addToScene` methods, which may
// mark this layer as dirty.
_needsAddToScene = false;
final ui.Scene scene = builder.build();
return scene;
}
bool _debugUltimatePreviousSiblingOf(Layer child, { Layer? equals }) {
assert(child.attached == attached);
while (child.previousSibling != null) {
assert(child.previousSibling != child);
child = child.previousSibling!;
assert(child.attached == attached);
}
return child == equals;
}
bool _debugUltimateNextSiblingOf(Layer child, { Layer? equals }) {
assert(child.attached == attached);
while (child._nextSibling != null) {
assert(child._nextSibling != child);
child = child._nextSibling!;
assert(child.attached == attached);
}
return child == equals;
}
@override
void dispose() {
removeAllChildren();
_callbacks.clear();
super.dispose();
}
@override
void updateSubtreeNeedsAddToScene() {
super.updateSubtreeNeedsAddToScene();
Layer? child = firstChild;
while (child != null) {
child.updateSubtreeNeedsAddToScene();
_needsAddToScene = _needsAddToScene || child._needsAddToScene;
child = child.nextSibling;
}
}
@override
bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
for (Layer? child = lastChild; child != null; child = child.previousSibling) {
final bool isAbsorbed = child.findAnnotations<S>(result, localPosition, onlyFirst: onlyFirst);
if (isAbsorbed) {
return true;
}
if (onlyFirst && result.entries.isNotEmpty) {
return isAbsorbed;
}
}
return false;
}
@override
void attach(Object owner) {
assert(!_debugMutationsLocked);
super.attach(owner);
Layer? child = firstChild;
while (child != null) {
child.attach(owner);
child = child.nextSibling;
}
}
@override
void detach() {
assert(!_debugMutationsLocked);
super.detach();
Layer? child = firstChild;
while (child != null) {
child.detach();
child = child.nextSibling;
}
// Detach indicates that we may never be composited again. Clients
// interested in observing composition need to get an update here because
// they might otherwise never get another one even though the layer is no
// longer visible.
//
// Children fired them already in child.detach().
_fireCompositionCallbacks(includeChildren: false);
}
/// Adds the given layer to the end of this layer's child list.
void append(Layer child) {
assert(!_debugMutationsLocked);
assert(child != this);
assert(child != firstChild);
assert(child != lastChild);
assert(child.parent == null);
assert(!child.attached);
assert(child.nextSibling == null);
assert(child.previousSibling == null);
assert(child._parentHandle.layer == null);
assert(() {
Layer node = this;
while (node.parent != null) {
node = node.parent!;
}
assert(node != child); // indicates we are about to create a cycle
return true;
}());
_adoptChild(child);
child._previousSibling = lastChild;
if (lastChild != null) {
lastChild!._nextSibling = child;
}
_lastChild = child;
_firstChild ??= child;
child._parentHandle.layer = child;
assert(child.attached == attached);
}
void _adoptChild(Layer child) {
assert(!_debugMutationsLocked);
if (!alwaysNeedsAddToScene) {
markNeedsAddToScene();
}
if (child._compositionCallbackCount != 0) {
_updateSubtreeCompositionObserverCount(child._compositionCallbackCount);
}
assert(child._parent == null);
assert(() {
Layer node = this;
while (node.parent != null) {
node = node.parent!;
}
assert(node != child); // indicates we are about to create a cycle
return true;
}());
child._parent = this;
if (attached) {
child.attach(_owner!);
}
redepthChild(child);
}
@override
void redepthChildren() {
Layer? child = firstChild;
while (child != null) {
redepthChild(child);
child = child.nextSibling;
}
}
/// Adjust the [depth] of the given [child] to be greater than this node's own
/// [depth].
///
/// Only call this method from overrides of [redepthChildren].
@protected
void redepthChild(Layer child) {
assert(child.owner == owner);
if (child._depth <= _depth) {
child._depth = _depth + 1;
child.redepthChildren();
}
}
// Implementation of [Layer.remove].
void _removeChild(Layer child) {
assert(child.parent == this);
assert(child.attached == attached);
assert(_debugUltimatePreviousSiblingOf(child, equals: firstChild));
assert(_debugUltimateNextSiblingOf(child, equals: lastChild));
assert(child._parentHandle.layer != null);
if (child._previousSibling == null) {
assert(_firstChild == child);
_firstChild = child._nextSibling;
} else {
child._previousSibling!._nextSibling = child.nextSibling;
}
if (child._nextSibling == null) {
assert(lastChild == child);
_lastChild = child.previousSibling;
} else {
child.nextSibling!._previousSibling = child.previousSibling;
}
assert((firstChild == null) == (lastChild == null));
assert(firstChild == null || firstChild!.attached == attached);
assert(lastChild == null || lastChild!.attached == attached);
assert(firstChild == null || _debugUltimateNextSiblingOf(firstChild!, equals: lastChild));
assert(lastChild == null || _debugUltimatePreviousSiblingOf(lastChild!, equals: firstChild));
child._previousSibling = null;
child._nextSibling = null;
_dropChild(child);
child._parentHandle.layer = null;
assert(!child.attached);
}
void _dropChild(Layer child) {
assert(!_debugMutationsLocked);
if (!alwaysNeedsAddToScene) {
markNeedsAddToScene();
}
if (child._compositionCallbackCount != 0) {
_updateSubtreeCompositionObserverCount(-child._compositionCallbackCount);
}
assert(child._parent == this);
assert(child.attached == attached);
child._parent = null;
if (attached) {
child.detach();
}
}
/// Removes all of this layer's children from its child list.
void removeAllChildren() {
assert(!_debugMutationsLocked);
Layer? child = firstChild;
while (child != null) {
final Layer? next = child.nextSibling;
child._previousSibling = null;
child._nextSibling = null;
assert(child.attached == attached);
_dropChild(child);
child._parentHandle.layer = null;
child = next;
}
_firstChild = null;
_lastChild = null;
}
@override
void addToScene(ui.SceneBuilder builder) {
addChildrenToScene(builder);
}
/// Uploads all of this layer's children to the engine.
///
/// This method is typically used by [addToScene] to insert the children into
/// the scene. Subclasses of [ContainerLayer] typically override [addToScene]
/// to apply effects to the scene using the [SceneBuilder] API, then insert
/// their children using [addChildrenToScene], then reverse the aforementioned
/// effects before returning from [addToScene].
void addChildrenToScene(ui.SceneBuilder builder) {
Layer? child = firstChild;
while (child != null) {
child._addToSceneWithRetainedRendering(builder);
child = child.nextSibling;
}
}
/// Applies the transform that would be applied when compositing the given
/// child to the given matrix.
///
/// Specifically, this should apply the transform that is applied to child's
/// _origin_. When using [applyTransform] with a chain of layers, results will
/// be unreliable unless the deepest layer in the chain collapses the
/// `layerOffset` in [addToScene] to zero, meaning that it passes
/// [Offset.zero] to its children, and bakes any incoming `layerOffset` into
/// the [SceneBuilder] as (for instance) a transform (which is then also
/// included in the transformation applied by [applyTransform]).
///
/// For example, if [addToScene] applies the `layerOffset` and then
/// passes [Offset.zero] to the children, then it should be included in the
/// transform applied here, whereas if [addToScene] just passes the
/// `layerOffset` to the child, then it should not be included in the
/// transform applied here.
///
/// This method is only valid immediately after [addToScene] has been called,
/// before any of the properties have been changed.
///
/// The default implementation does nothing, since [ContainerLayer], by
/// default, composites its children at the origin of the [ContainerLayer]
/// itself.
///
/// The `child` argument should generally not be null, since in principle a
/// layer could transform each child independently. However, certain layers
/// may explicitly allow null as a value, for example if they know that they
/// transform all their children identically.
///
/// Used by [FollowerLayer] to transform its child to a [LeaderLayer]'s
/// position.
void applyTransform(Layer? child, Matrix4 transform) {
assert(child != null);
}
/// Returns the descendants of this layer in depth first order.
@visibleForTesting
List<Layer> depthFirstIterateChildren() {
if (firstChild == null) {
return <Layer>[];
}
final List<Layer> children = <Layer>[];
Layer? child = firstChild;
while (child != null) {
children.add(child);
if (child is ContainerLayer) {
children.addAll(child.depthFirstIterateChildren());
}
child = child.nextSibling;
}
return children;
}
@override
List<DiagnosticsNode> debugDescribeChildren() {
final List<DiagnosticsNode> children = <DiagnosticsNode>[];
if (firstChild == null) {
return children;
}
Layer? child = firstChild;
int count = 1;
while (true) {
children.add(child!.toDiagnosticsNode(name: 'child $count'));
if (child == lastChild) {
break;
}
count += 1;
child = child.nextSibling;
}
return children;
}
}
/// A layer that is displayed at an offset from its parent layer.
///
/// Offset layers are key to efficient repainting because they are created by
/// repaint boundaries in the [RenderObject] tree (see
/// [RenderObject.isRepaintBoundary]). When a render object that is a repaint
/// boundary is asked to paint at given offset in a [PaintingContext], the
/// render object first checks whether it needs to repaint itself. If not, it
/// reuses its existing [OffsetLayer] (and its entire subtree) by mutating its
/// [offset] property, cutting off the paint walk.
class OffsetLayer extends ContainerLayer {
/// Creates an offset layer.
///
/// By default, [offset] is zero. It must be non-null before the compositing
/// phase of the pipeline.
OffsetLayer({ Offset offset = Offset.zero }) : _offset = offset;
/// Offset from parent in the parent's coordinate system.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
///
/// The [offset] property must be non-null before the compositing phase of the
/// pipeline.
Offset get offset => _offset;
Offset _offset;
set offset(Offset value) {
if (value != _offset) {
markNeedsAddToScene();
}
_offset = value;
}
@override
bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
return super.findAnnotations<S>(result, localPosition - offset, onlyFirst: onlyFirst);
}
@override
void applyTransform(Layer? child, Matrix4 transform) {
assert(child != null);
transform.translate(offset.dx, offset.dy);
}
@override
void addToScene(ui.SceneBuilder builder) {
// Skia has a fast path for concatenating scale/translation only matrices.
// Hence pushing a translation-only transform layer should be fast. For
// retained rendering, we don't want to push the offset down to each leaf
// node. Otherwise, changing an offset layer on the very high level could
// cascade the change to too many leaves.
engineLayer = builder.pushOffset(
offset.dx,
offset.dy,
oldLayer: _engineLayer as ui.OffsetEngineLayer?,
);
addChildrenToScene(builder);
builder.pop();
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Offset>('offset', offset));
}
ui.Scene _createSceneForImage(Rect bounds, { double pixelRatio = 1.0 }) {
final ui.SceneBuilder builder = ui.SceneBuilder();
final Matrix4 transform = Matrix4.diagonal3Values(pixelRatio, pixelRatio, 1);
transform.translate(-(bounds.left + offset.dx), -(bounds.top + offset.dy));
builder.pushTransform(transform.storage);
return buildScene(builder);
}
/// Capture an image of the current state of this layer and its children.
///
/// The returned [ui.Image] has uncompressed raw RGBA bytes, will be offset
/// by the top-left corner of [bounds], and have dimensions equal to the size
/// of [bounds] multiplied by [pixelRatio].
///
/// The [pixelRatio] describes the scale between the logical pixels and the
/// size of the output image. It is independent of the
/// [dart:ui.FlutterView.devicePixelRatio] for the device, so specifying 1.0
/// (the default) will give you a 1:1 mapping between logical pixels and the
/// output pixels in the image.
///
/// This API functions like [toImageSync], except that it only returns after
/// rasterization is complete.
///
/// See also:
///
/// * [RenderRepaintBoundary.toImage] for a similar API at the render object level.
/// * [dart:ui.Scene.toImage] for more information about the image returned.
Future<ui.Image> toImage(Rect bounds, { double pixelRatio = 1.0 }) async {
final ui.Scene scene = _createSceneForImage(bounds, pixelRatio: pixelRatio);
try {
// Size is rounded up to the next pixel to make sure we don't clip off
// anything.
return await scene.toImage(
(pixelRatio * bounds.width).ceil(),
(pixelRatio * bounds.height).ceil(),
);
} finally {
scene.dispose();
}
}
/// Capture an image of the current state of this layer and its children.
///
/// The returned [ui.Image] has uncompressed raw RGBA bytes, will be offset
/// by the top-left corner of [bounds], and have dimensions equal to the size
/// of [bounds] multiplied by [pixelRatio].
///
/// The [pixelRatio] describes the scale between the logical pixels and the
/// size of the output image. It is independent of the
/// [dart:ui.FlutterView.devicePixelRatio] for the device, so specifying 1.0
/// (the default) will give you a 1:1 mapping between logical pixels and the
/// output pixels in the image.
///
/// This API functions like [toImage], except that rasterization begins eagerly
/// on the raster thread and the image is returned before this is completed.
///
/// See also:
///
/// * [RenderRepaintBoundary.toImage] for a similar API at the render object level.
/// * [dart:ui.Scene.toImage] for more information about the image returned.
ui.Image toImageSync(Rect bounds, { double pixelRatio = 1.0 }) {
final ui.Scene scene = _createSceneForImage(bounds, pixelRatio: pixelRatio);
try {
// Size is rounded up to the next pixel to make sure we don't clip off
// anything.
return scene.toImageSync(
(pixelRatio * bounds.width).ceil(),
(pixelRatio * bounds.height).ceil(),
);
} finally {
scene.dispose();
}
}
}
/// A composite layer that clips its children using a rectangle.
///
/// When debugging, setting [debugDisableClipLayers] to true will cause this
/// layer to be skipped (directly replaced by its children). This can be helpful
/// to track down the cause of performance problems.
class ClipRectLayer extends ContainerLayer {
/// Creates a layer with a rectangular clip.
///
/// The [clipRect] argument must not be null before the compositing phase of
/// the pipeline.
///
/// The [clipBehavior] argument must not be [Clip.none].
ClipRectLayer({
Rect? clipRect,
Clip clipBehavior = Clip.hardEdge,
}) : _clipRect = clipRect,
_clipBehavior = clipBehavior,
assert(clipBehavior != Clip.none);
/// The rectangle to clip in the parent's coordinate system.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
Rect? get clipRect => _clipRect;
Rect? _clipRect;
set clipRect(Rect? value) {
if (value != _clipRect) {
_clipRect = value;
markNeedsAddToScene();
}
}
@override
Rect? describeClipBounds() => clipRect;
/// {@template flutter.rendering.ClipRectLayer.clipBehavior}
/// Controls how to clip.
///
/// Must not be set to null or [Clip.none].
/// {@endtemplate}
///
/// Defaults to [Clip.hardEdge].
Clip get clipBehavior => _clipBehavior;
Clip _clipBehavior;
set clipBehavior(Clip value) {
assert(value != Clip.none);
if (value != _clipBehavior) {
_clipBehavior = value;
markNeedsAddToScene();
}
}
@override
bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
if (!clipRect!.contains(localPosition)) {
return false;
}
return super.findAnnotations<S>(result, localPosition, onlyFirst: onlyFirst);
}
@override
void addToScene(ui.SceneBuilder builder) {
assert(clipRect != null);
bool enabled = true;
assert(() {
enabled = !debugDisableClipLayers;
return true;
}());
if (enabled) {
engineLayer = builder.pushClipRect(
clipRect!,
clipBehavior: clipBehavior,
oldLayer: _engineLayer as ui.ClipRectEngineLayer?,
);
} else {
engineLayer = null;
}
addChildrenToScene(builder);
if (enabled) {
builder.pop();
}
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Rect>('clipRect', clipRect));
properties.add(DiagnosticsProperty<Clip>('clipBehavior', clipBehavior));
}
}
/// A composite layer that clips its children using a rounded rectangle.
///
/// When debugging, setting [debugDisableClipLayers] to true will cause this
/// layer to be skipped (directly replaced by its children). This can be helpful
/// to track down the cause of performance problems.
class ClipRRectLayer extends ContainerLayer {
/// Creates a layer with a rounded-rectangular clip.
///
/// The [clipRRect] and [clipBehavior] properties must be non-null before the
/// compositing phase of the pipeline.
ClipRRectLayer({
RRect? clipRRect,
Clip clipBehavior = Clip.antiAlias,
}) : _clipRRect = clipRRect,
_clipBehavior = clipBehavior,
assert(clipBehavior != Clip.none);
/// The rounded-rect to clip in the parent's coordinate system.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
RRect? get clipRRect => _clipRRect;
RRect? _clipRRect;
set clipRRect(RRect? value) {
if (value != _clipRRect) {
_clipRRect = value;
markNeedsAddToScene();
}
}
@override
Rect? describeClipBounds() => clipRRect?.outerRect;
/// {@macro flutter.rendering.ClipRectLayer.clipBehavior}
///
/// Defaults to [Clip.antiAlias].
Clip get clipBehavior => _clipBehavior;
Clip _clipBehavior;
set clipBehavior(Clip value) {
assert(value != Clip.none);
if (value != _clipBehavior) {
_clipBehavior = value;
markNeedsAddToScene();
}
}
@override
bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
if (!clipRRect!.contains(localPosition)) {
return false;
}
return super.findAnnotations<S>(result, localPosition, onlyFirst: onlyFirst);
}
@override
void addToScene(ui.SceneBuilder builder) {
assert(clipRRect != null);
bool enabled = true;
assert(() {
enabled = !debugDisableClipLayers;
return true;
}());
if (enabled) {
engineLayer = builder.pushClipRRect(
clipRRect!,
clipBehavior: clipBehavior,
oldLayer: _engineLayer as ui.ClipRRectEngineLayer?,
);
} else {
engineLayer = null;
}
addChildrenToScene(builder);
if (enabled) {
builder.pop();
}
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<RRect>('clipRRect', clipRRect));
properties.add(DiagnosticsProperty<Clip>('clipBehavior', clipBehavior));
}
}
/// A composite layer that clips its children using a path.
///
/// When debugging, setting [debugDisableClipLayers] to true will cause this
/// layer to be skipped (directly replaced by its children). This can be helpful
/// to track down the cause of performance problems.
class ClipPathLayer extends ContainerLayer {
/// Creates a layer with a path-based clip.
///
/// The [clipPath] and [clipBehavior] properties must be non-null before the
/// compositing phase of the pipeline.
ClipPathLayer({
Path? clipPath,
Clip clipBehavior = Clip.antiAlias,
}) : _clipPath = clipPath,
_clipBehavior = clipBehavior,
assert(clipBehavior != Clip.none);
/// The path to clip in the parent's coordinate system.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
Path? get clipPath => _clipPath;
Path? _clipPath;
set clipPath(Path? value) {
if (value != _clipPath) {
_clipPath = value;
markNeedsAddToScene();
}
}
@override
Rect? describeClipBounds() => clipPath?.getBounds();
/// {@macro flutter.rendering.ClipRectLayer.clipBehavior}
///
/// Defaults to [Clip.antiAlias].
Clip get clipBehavior => _clipBehavior;
Clip _clipBehavior;
set clipBehavior(Clip value) {
assert(value != Clip.none);
if (value != _clipBehavior) {
_clipBehavior = value;
markNeedsAddToScene();
}
}
@override
bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
if (!clipPath!.contains(localPosition)) {
return false;
}
return super.findAnnotations<S>(result, localPosition, onlyFirst: onlyFirst);
}
@override
void addToScene(ui.SceneBuilder builder) {
assert(clipPath != null);
bool enabled = true;
assert(() {
enabled = !debugDisableClipLayers;
return true;
}());
if (enabled) {
engineLayer = builder.pushClipPath(
clipPath!,
clipBehavior: clipBehavior,
oldLayer: _engineLayer as ui.ClipPathEngineLayer?,
);
} else {
engineLayer = null;
}
addChildrenToScene(builder);
if (enabled) {
builder.pop();
}
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Clip>('clipBehavior', clipBehavior));
}
}
/// A composite layer that applies a [ColorFilter] to its children.
class ColorFilterLayer extends ContainerLayer {
/// Creates a layer that applies a [ColorFilter] to its children.
///
/// The [colorFilter] property must be non-null before the compositing phase
/// of the pipeline.
ColorFilterLayer({
ColorFilter? colorFilter,
}) : _colorFilter = colorFilter;
/// The color filter to apply to children.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
ColorFilter? get colorFilter => _colorFilter;
ColorFilter? _colorFilter;
set colorFilter(ColorFilter? value) {
assert(value != null);
if (value != _colorFilter) {
_colorFilter = value;
markNeedsAddToScene();
}
}
@override
void addToScene(ui.SceneBuilder builder) {
assert(colorFilter != null);
engineLayer = builder.pushColorFilter(
colorFilter!,
oldLayer: _engineLayer as ui.ColorFilterEngineLayer?,
);
addChildrenToScene(builder);
builder.pop();
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<ColorFilter>('colorFilter', colorFilter));
}
}
/// A composite layer that applies an [ImageFilter] to its children.
class ImageFilterLayer extends OffsetLayer {
/// Creates a layer that applies an [ImageFilter] to its children.
///
/// The [imageFilter] property must be non-null before the compositing phase
/// of the pipeline.
ImageFilterLayer({
ui.ImageFilter? imageFilter,
super.offset,
}) : _imageFilter = imageFilter;
/// The image filter to apply to children.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
ui.ImageFilter? get imageFilter => _imageFilter;
ui.ImageFilter? _imageFilter;
set imageFilter(ui.ImageFilter? value) {
assert(value != null);
if (value != _imageFilter) {
_imageFilter = value;
markNeedsAddToScene();
}
}
@override
void addToScene(ui.SceneBuilder builder) {
assert(imageFilter != null);
engineLayer = builder.pushImageFilter(
imageFilter!,
offset: offset,
oldLayer: _engineLayer as ui.ImageFilterEngineLayer?,
);
addChildrenToScene(builder);
builder.pop();
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<ui.ImageFilter>('imageFilter', imageFilter));
}
}
/// A composited layer that applies a given transformation matrix to its
/// children.
///
/// This class inherits from [OffsetLayer] to make it one of the layers that
/// can be used at the root of a [RenderObject] hierarchy.
class TransformLayer extends OffsetLayer {
/// Creates a transform layer.
///
/// The [transform] and [offset] properties must be non-null before the
/// compositing phase of the pipeline.
TransformLayer({ Matrix4? transform, super.offset })
: _transform = transform;
/// The matrix to apply.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
///
/// This transform is applied before [offset], if both are set.
///
/// The [transform] property must be non-null before the compositing phase of
/// the pipeline.
Matrix4? get transform => _transform;
Matrix4? _transform;
set transform(Matrix4? value) {
assert(value != null);
assert(value!.storage.every((double component) => component.isFinite));
if (value == _transform) {
return;
}
_transform = value;
_inverseDirty = true;
markNeedsAddToScene();
}
Matrix4? _lastEffectiveTransform;
Matrix4? _invertedTransform;
bool _inverseDirty = true;
@override
void addToScene(ui.SceneBuilder builder) {
assert(transform != null);
_lastEffectiveTransform = transform;
if (offset != Offset.zero) {
_lastEffectiveTransform = Matrix4.translationValues(offset.dx, offset.dy, 0.0)
..multiply(_lastEffectiveTransform!);
}
engineLayer = builder.pushTransform(
_lastEffectiveTransform!.storage,
oldLayer: _engineLayer as ui.TransformEngineLayer?,
);
addChildrenToScene(builder);
builder.pop();
}
Offset? _transformOffset(Offset localPosition) {
if (_inverseDirty) {
_invertedTransform = Matrix4.tryInvert(
PointerEvent.removePerspectiveTransform(transform!),
);
_inverseDirty = false;
}
if (_invertedTransform == null) {
return null;
}
return MatrixUtils.transformPoint(_invertedTransform!, localPosition);
}
@override
bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
final Offset? transformedOffset = _transformOffset(localPosition);
if (transformedOffset == null) {
return false;
}
return super.findAnnotations<S>(result, transformedOffset, onlyFirst: onlyFirst);
}
@override
void applyTransform(Layer? child, Matrix4 transform) {
assert(child != null);
assert(_lastEffectiveTransform != null || this.transform != null);
if (_lastEffectiveTransform == null) {
transform.multiply(this.transform!);
} else {
transform.multiply(_lastEffectiveTransform!);
}
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(TransformProperty('transform', transform));
}
}
/// A composited layer that makes its children partially transparent.
///
/// When debugging, setting [debugDisableOpacityLayers] to true will cause this
/// layer to be skipped (directly replaced by its children). This can be helpful
/// to track down the cause of performance problems.
///
/// Try to avoid an [OpacityLayer] with no children. Remove that layer if
/// possible to save some tree walks.
class OpacityLayer extends OffsetLayer {
/// Creates an opacity layer.
///
/// The [alpha] property must be non-null before the compositing phase of
/// the pipeline.
OpacityLayer({
int? alpha,
super.offset,
}) : _alpha = alpha;
/// The amount to multiply into the alpha channel.
///
/// The opacity is expressed as an integer from 0 to 255, where 0 is fully
/// transparent and 255 is fully opaque.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
int? get alpha => _alpha;
int? _alpha;
set alpha(int? value) {
assert(value != null);
if (value != _alpha) {
if (value == 255 || _alpha == 255) {
engineLayer = null;
}
_alpha = value;
markNeedsAddToScene();
}
}
@override
void addToScene(ui.SceneBuilder builder) {
assert(alpha != null);
// Don't add this layer if there's no child.
bool enabled = firstChild != null;
if (!enabled) {
// Ensure the engineLayer is disposed.
engineLayer = null;
// TODO(dnfield): Remove this if/when we can fix https://github.com/flutter/flutter/issues/90004
return;
}
assert(() {
enabled = enabled && !debugDisableOpacityLayers;
return true;
}());
final int realizedAlpha = alpha!;
// The type assertions work because the [alpha] setter nulls out the
// engineLayer if it would have changed type (i.e. changed to or from 255).
if (enabled && realizedAlpha < 255) {
assert(_engineLayer is ui.OpacityEngineLayer?);
engineLayer = builder.pushOpacity(
realizedAlpha,
offset: offset,
oldLayer: _engineLayer as ui.OpacityEngineLayer?,
);
} else {
assert(_engineLayer is ui.OffsetEngineLayer?);
engineLayer = builder.pushOffset(
offset.dx,
offset.dy,
oldLayer: _engineLayer as ui.OffsetEngineLayer?,
);
}
addChildrenToScene(builder);
builder.pop();
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(IntProperty('alpha', alpha));
}
}
/// A composited layer that applies a shader to its children.
///
/// The shader is only applied inside the given [maskRect]. The shader itself
/// uses the top left of the [maskRect] as its origin.
///
/// The [maskRect] does not affect the positions of any child layers.
class ShaderMaskLayer extends ContainerLayer {
/// Creates a shader mask layer.
///
/// The [shader], [maskRect], and [blendMode] properties must be non-null
/// before the compositing phase of the pipeline.
ShaderMaskLayer({
Shader? shader,
Rect? maskRect,
BlendMode? blendMode,
}) : _shader = shader,
_maskRect = maskRect,
_blendMode = blendMode;
/// The shader to apply to the children.
///
/// The origin of the shader (e.g. of the coordinate system used by the `from`
/// and `to` arguments to [ui.Gradient.linear]) is at the top left of the
/// [maskRect].
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
///
/// See also:
///
/// * [ui.Gradient] and [ui.ImageShader], two shader types that can be used.
Shader? get shader => _shader;
Shader? _shader;
set shader(Shader? value) {
if (value != _shader) {
_shader = value;
markNeedsAddToScene();
}
}
/// The position and size of the shader.
///
/// The [shader] is only rendered inside this rectangle, using the top left of
/// the rectangle as its origin.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
Rect? get maskRect => _maskRect;
Rect? _maskRect;
set maskRect(Rect? value) {
if (value != _maskRect) {
_maskRect = value;
markNeedsAddToScene();
}
}
/// The blend mode to apply when blending the shader with the children.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
BlendMode? get blendMode => _blendMode;
BlendMode? _blendMode;
set blendMode(BlendMode? value) {
if (value != _blendMode) {
_blendMode = value;
markNeedsAddToScene();
}
}
@override
void addToScene(ui.SceneBuilder builder) {
assert(shader != null);
assert(maskRect != null);
assert(blendMode != null);
engineLayer = builder.pushShaderMask(
shader!,
maskRect! ,
blendMode!,
oldLayer: _engineLayer as ui.ShaderMaskEngineLayer?,
);
addChildrenToScene(builder);
builder.pop();
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Shader>('shader', shader));
properties.add(DiagnosticsProperty<Rect>('maskRect', maskRect));
properties.add(EnumProperty<BlendMode>('blendMode', blendMode));
}
}
/// A composited layer that applies a filter to the existing contents of the scene.
class BackdropFilterLayer extends ContainerLayer {
/// Creates a backdrop filter layer.
///
/// The [filter] property must be non-null before the compositing phase of the
/// pipeline.
///
/// The [blendMode] property defaults to [BlendMode.srcOver].
BackdropFilterLayer({
ui.ImageFilter? filter,
BlendMode blendMode = BlendMode.srcOver,
}) : _filter = filter,
_blendMode = blendMode;
/// The filter to apply to the existing contents of the scene.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
ui.ImageFilter? get filter => _filter;
ui.ImageFilter? _filter;
set filter(ui.ImageFilter? value) {
if (value != _filter) {
_filter = value;
markNeedsAddToScene();
}
}
/// The blend mode to use to apply the filtered background content onto the background
/// surface.
///
/// The default value of this property is [BlendMode.srcOver].
/// {@macro flutter.widgets.BackdropFilter.blendMode}
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
BlendMode get blendMode => _blendMode;
BlendMode _blendMode;
set blendMode(BlendMode value) {
if (value != _blendMode) {
_blendMode = value;
markNeedsAddToScene();
}
}
@override
void addToScene(ui.SceneBuilder builder) {
assert(filter != null);
engineLayer = builder.pushBackdropFilter(
filter!,
blendMode: blendMode,
oldLayer: _engineLayer as ui.BackdropFilterEngineLayer?,
);
addChildrenToScene(builder);
builder.pop();
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<ui.ImageFilter>('filter', filter));
properties.add(EnumProperty<BlendMode>('blendMode', blendMode));
}
}
/// An object that a [LeaderLayer] can register with.
///
/// An instance of this class should be provided as the [LeaderLayer.link] and
/// the [FollowerLayer.link] properties to cause the [FollowerLayer] to follow
/// the [LeaderLayer].
///
/// See also:
///
/// * [CompositedTransformTarget], the widget that creates a [LeaderLayer].
/// * [CompositedTransformFollower], the widget that creates a [FollowerLayer].
/// * [RenderLeaderLayer] and [RenderFollowerLayer], the corresponding
/// render objects.
class LayerLink {
/// The [LeaderLayer] connected to this link.
LeaderLayer? get leader => _leader;
LeaderLayer? _leader;
void _registerLeader(LeaderLayer leader) {
assert(_leader != leader);
assert((){
if (_leader != null) {
_debugPreviousLeaders ??= <LeaderLayer>{};
_debugScheduleLeadersCleanUpCheck();
return _debugPreviousLeaders!.add(_leader!);
}
return true;
}());
_leader = leader;
}
void _unregisterLeader(LeaderLayer leader) {
if (_leader == leader) {
_leader = null;
} else {
assert(_debugPreviousLeaders!.remove(leader));
}
}
/// Stores the previous leaders that were replaced by the current [_leader]
/// in the current frame.
///
/// These leaders need to give up their leaderships of this link by the end of
/// the current frame.
Set<LeaderLayer>? _debugPreviousLeaders;
bool _debugLeaderCheckScheduled = false;
/// Schedules the check as post frame callback to make sure the
/// [_debugPreviousLeaders] is empty.
void _debugScheduleLeadersCleanUpCheck() {
assert(_debugPreviousLeaders != null);
assert(() {
if (_debugLeaderCheckScheduled) {
return true;
}
_debugLeaderCheckScheduled = true;
SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) {
_debugLeaderCheckScheduled = false;
assert(_debugPreviousLeaders!.isEmpty);
}, debugLabel: 'LayerLink.leadersCleanUpCheck');
return true;
}());
}
/// The total size of the content of the connected [LeaderLayer].
///
/// Generally this should be set by the [RenderObject] that paints on the
/// registered [LeaderLayer] (for instance a [RenderLeaderLayer] that shares
/// this link with its followers). This size may be outdated before and during
/// layout.
Size? leaderSize;
@override
String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) {
return '${describeIdentity(this)}(${ _leader != null ? "<linked>" : "<dangling>" })';
}
}
/// A composited layer that can be followed by a [FollowerLayer].
///
/// This layer collapses the accumulated offset into a transform and passes
/// [Offset.zero] to its child layers in the [addToScene]/[addChildrenToScene]
/// methods, so that [applyTransform] will work reliably.
class LeaderLayer extends ContainerLayer {
/// Creates a leader layer.
///
/// The [link] property must not have been provided to any other [LeaderLayer]
/// layers that are [attached] to the layer tree at the same time.
///
/// The [offset] property must be non-null before the compositing phase of the
/// pipeline.
LeaderLayer({ required LayerLink link, Offset offset = Offset.zero }) : _link = link, _offset = offset;
/// The object with which this layer should register.
///
/// The link will be established when this layer is [attach]ed, and will be
/// cleared when this layer is [detach]ed.
LayerLink get link => _link;
LayerLink _link;
set link(LayerLink value) {
if (_link == value) {
return;
}
if (attached) {
_link._unregisterLeader(this);
value._registerLeader(this);
}
_link = value;
}
/// Offset from parent in the parent's coordinate system.
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
///
/// The [offset] property must be non-null before the compositing phase of the
/// pipeline.
Offset get offset => _offset;
Offset _offset;
set offset(Offset value) {
if (value == _offset) {
return;
}
_offset = value;
if (!alwaysNeedsAddToScene) {
markNeedsAddToScene();
}
}
@override
void attach(Object owner) {
super.attach(owner);
_link._registerLeader(this);
}
@override
void detach() {
_link._unregisterLeader(this);
super.detach();
}
@override
bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
return super.findAnnotations<S>(result, localPosition - offset, onlyFirst: onlyFirst);
}
@override
void addToScene(ui.SceneBuilder builder) {
if (offset != Offset.zero) {
engineLayer = builder.pushTransform(
Matrix4.translationValues(offset.dx, offset.dy, 0.0).storage,
oldLayer: _engineLayer as ui.TransformEngineLayer?,
);
} else {
engineLayer = null;
}
addChildrenToScene(builder);
if (offset != Offset.zero) {
builder.pop();
}
}
/// Applies the transform that would be applied when compositing the given
/// child to the given matrix.
///
/// See [ContainerLayer.applyTransform] for details.
///
/// The `child` argument may be null, as the same transform is applied to all
/// children.
@override
void applyTransform(Layer? child, Matrix4 transform) {
if (offset != Offset.zero) {
transform.translate(offset.dx, offset.dy);
}
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Offset>('offset', offset));
properties.add(DiagnosticsProperty<LayerLink>('link', link));
}
}
/// A composited layer that applies a transformation matrix to its children such
/// that they are positioned to match a [LeaderLayer].
///
/// If any of the ancestors of this layer have a degenerate matrix (e.g. scaling
/// by zero), then the [FollowerLayer] will not be able to transform its child
/// to the coordinate space of the [LeaderLayer].
///
/// A [linkedOffset] property can be provided to further offset the child layer
/// from the leader layer, for example if the child is to follow the linked
/// layer at a distance rather than directly overlapping it.
class FollowerLayer extends ContainerLayer {
/// Creates a follower layer.
///
/// The [unlinkedOffset], [linkedOffset], and [showWhenUnlinked] properties
/// must be non-null before the compositing phase of the pipeline.
FollowerLayer({
required this.link,
this.showWhenUnlinked = true,
this.unlinkedOffset = Offset.zero,
this.linkedOffset = Offset.zero,
});
/// The link to the [LeaderLayer].
///
/// The same object should be provided to a [LeaderLayer] that is earlier in
/// the layer tree. When this layer is composited, it will apply a transform
/// that moves its children to match the position of the [LeaderLayer].
LayerLink link;
/// Whether to show the layer's contents when the [link] does not point to a
/// [LeaderLayer].
///
/// When the layer is linked, children layers are positioned such that they
/// have the same global position as the linked [LeaderLayer].
///
/// When the layer is not linked, then: if [showWhenUnlinked] is true,
/// children are positioned as if the [FollowerLayer] was a [ContainerLayer];
/// if it is false, then children are hidden.
///
/// The [showWhenUnlinked] property must be non-null before the compositing
/// phase of the pipeline.
bool? showWhenUnlinked;
/// Offset from parent in the parent's coordinate system, used when the layer
/// is not linked to a [LeaderLayer].
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
///
/// The [unlinkedOffset] property must be non-null before the compositing
/// phase of the pipeline.
///
/// See also:
///
/// * [linkedOffset], for when the layers are linked.
Offset? unlinkedOffset;
/// Offset from the origin of the leader layer to the origin of the child
/// layers, used when the layer is linked to a [LeaderLayer].
///
/// The scene must be explicitly recomposited after this property is changed
/// (as described at [Layer]).
///
/// The [linkedOffset] property must be non-null before the compositing phase
/// of the pipeline.
///
/// See also:
///
/// * [unlinkedOffset], for when the layer is not linked.
Offset? linkedOffset;
Offset? _lastOffset;
Matrix4? _lastTransform;
Matrix4? _invertedTransform;
bool _inverseDirty = true;
Offset? _transformOffset(Offset localPosition) {
if (_inverseDirty) {
_invertedTransform = Matrix4.tryInvert(getLastTransform()!);
_inverseDirty = false;
}
if (_invertedTransform == null) {
return null;
}
final Vector4 vector = Vector4(localPosition.dx, localPosition.dy, 0.0, 1.0);
final Vector4 result = _invertedTransform!.transform(vector);
return Offset(result[0] - linkedOffset!.dx, result[1] - linkedOffset!.dy);
}
@override
bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
if (link.leader == null) {
if (showWhenUnlinked!) {
return super.findAnnotations(result, localPosition - unlinkedOffset!, onlyFirst: onlyFirst);
}
return false;
}
final Offset? transformedOffset = _transformOffset(localPosition);
if (transformedOffset == null) {
return false;
}
return super.findAnnotations<S>(result, transformedOffset, onlyFirst: onlyFirst);
}
/// The transform that was used during the last composition phase.
///
/// If the [link] was not linked to a [LeaderLayer], or if this layer has
/// a degenerate matrix applied, then this will be null.
///
/// This method returns a new [Matrix4] instance each time it is invoked.
Matrix4? getLastTransform() {
if (_lastTransform == null) {
return null;
}
final Matrix4 result = Matrix4.translationValues(-_lastOffset!.dx, -_lastOffset!.dy, 0.0);
result.multiply(_lastTransform!);
return result;
}
/// Call [applyTransform] for each layer in the provided list.
///
/// The list is in reverse order (deepest first). The first layer will be
/// treated as the child of the second, and so forth. The first layer in the
/// list won't have [applyTransform] called on it. The first layer may be
/// null.
static Matrix4 _collectTransformForLayerChain(List<ContainerLayer?> layers) {
// Initialize our result matrix.
final Matrix4 result = Matrix4.identity();
// Apply each layer to the matrix in turn, starting from the last layer,
// and providing the previous layer as the child.
for (int index = layers.length - 1; index > 0; index -= 1) {
layers[index]?.applyTransform(layers[index - 1], result);
}
return result;
}
/// Find the common ancestor of two layers [a] and [b] by searching towards
/// the root of the tree, and append each ancestor of [a] or [b] visited along
/// the path to [ancestorsA] and [ancestorsB] respectively.
///
/// Returns null if [a] [b] do not share a common ancestor, in which case the
/// results in [ancestorsA] and [ancestorsB] are undefined.
static Layer? _pathsToCommonAncestor(
Layer? a,
Layer? b,
List<ContainerLayer?> ancestorsA,
List<ContainerLayer?> ancestorsB,
) {
// No common ancestor found.
if (a == null || b == null) {
return null;
}
if (identical(a, b)) {
return a;
}
if (a.depth < b.depth) {
ancestorsB.add(b.parent);
return _pathsToCommonAncestor(a, b.parent, ancestorsA, ancestorsB);
} else if (a.depth > b.depth) {
ancestorsA.add(a.parent);
return _pathsToCommonAncestor(a.parent, b, ancestorsA, ancestorsB);
}
ancestorsA.add(a.parent);
ancestorsB.add(b.parent);
return _pathsToCommonAncestor(a.parent, b.parent, ancestorsA, ancestorsB);
}
bool _debugCheckLeaderBeforeFollower(
List<ContainerLayer> leaderToCommonAncestor,
List<ContainerLayer> followerToCommonAncestor,
) {
if (followerToCommonAncestor.length <= 1) {
// Follower is the common ancestor, ergo the leader must come AFTER the follower.
return false;
}
if (leaderToCommonAncestor.length <= 1) {
// Leader is the common ancestor, ergo the leader must come BEFORE the follower.
return true;
}
// Common ancestor is neither the leader nor the follower.
final ContainerLayer leaderSubtreeBelowAncestor = leaderToCommonAncestor[leaderToCommonAncestor.length - 2];
final ContainerLayer followerSubtreeBelowAncestor = followerToCommonAncestor[followerToCommonAncestor.length - 2];
Layer? sibling = leaderSubtreeBelowAncestor;
while (sibling != null) {
if (sibling == followerSubtreeBelowAncestor) {
return true;
}
sibling = sibling.nextSibling;
}
// The follower subtree didn't come after the leader subtree.
return false;
}
/// Populate [_lastTransform] given the current state of the tree.
void _establishTransform() {
_lastTransform = null;
final LeaderLayer? leader = link.leader;
// Check to see if we are linked.
if (leader == null) {
return;
}
// If we're linked, check the link is valid.
assert(
leader.owner == owner,
'Linked LeaderLayer anchor is not in the same layer tree as the FollowerLayer.',
);
// Stores [leader, ..., commonAncestor] after calling _pathsToCommonAncestor.
final List<ContainerLayer> forwardLayers = <ContainerLayer>[leader];
// Stores [this (follower), ..., commonAncestor] after calling
// _pathsToCommonAncestor.
final List<ContainerLayer> inverseLayers = <ContainerLayer>[this];
final Layer? ancestor = _pathsToCommonAncestor(
leader, this,
forwardLayers, inverseLayers,
);
assert(
ancestor != null,
'LeaderLayer and FollowerLayer do not have a common ancestor.',
);
assert(
_debugCheckLeaderBeforeFollower(forwardLayers, inverseLayers),
'LeaderLayer anchor must come before FollowerLayer in paint order, but the reverse was true.',
);
final Matrix4 forwardTransform = _collectTransformForLayerChain(forwardLayers);
// Further transforms the coordinate system to a hypothetical child (null)
// of the leader layer, to account for the leader's additional paint offset
// and layer offset (LeaderLayer.offset).
leader.applyTransform(null, forwardTransform);
forwardTransform.translate(linkedOffset!.dx, linkedOffset!.dy);
final Matrix4 inverseTransform = _collectTransformForLayerChain(inverseLayers);
if (inverseTransform.invert() == 0.0) {
// We are in a degenerate transform, so there's not much we can do.
return;
}
// Combine the matrices and store the result.
inverseTransform.multiply(forwardTransform);
_lastTransform = inverseTransform;
_inverseDirty = true;
}
/// {@template flutter.rendering.FollowerLayer.alwaysNeedsAddToScene}
/// This disables retained rendering.
///
/// A [FollowerLayer] copies changes from a [LeaderLayer] that could be anywhere
/// in the Layer tree, and that leader layer could change without notifying the
/// follower layer. Therefore we have to always call a follower layer's
/// [addToScene]. In order to call follower layer's [addToScene], leader layer's
/// [addToScene] must be called first so leader layer must also be considered
/// as [alwaysNeedsAddToScene].
/// {@endtemplate}
@override
bool get alwaysNeedsAddToScene => true;
@override
void addToScene(ui.SceneBuilder builder) {
assert(showWhenUnlinked != null);
if (link.leader == null && !showWhenUnlinked!) {
_lastTransform = null;
_lastOffset = null;
_inverseDirty = true;
engineLayer = null;
return;
}
_establishTransform();
if (_lastTransform != null) {
_lastOffset = unlinkedOffset;
engineLayer = builder.pushTransform(
_lastTransform!.storage,
oldLayer: _engineLayer as ui.TransformEngineLayer?,
);
addChildrenToScene(builder);
builder.pop();
} else {
_lastOffset = null;
final Matrix4 matrix = Matrix4.translationValues(unlinkedOffset!.dx, unlinkedOffset!.dy, .0);
engineLayer = builder.pushTransform(
matrix.storage,
oldLayer: _engineLayer as ui.TransformEngineLayer?,
);
addChildrenToScene(builder);
builder.pop();
}
_inverseDirty = true;
}
@override
void applyTransform(Layer? child, Matrix4 transform) {
assert(child != null);
if (_lastTransform != null) {
transform.multiply(_lastTransform!);
} else {
transform.multiply(Matrix4.translationValues(unlinkedOffset!.dx, unlinkedOffset!.dy, 0));
}
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<LayerLink>('link', link));
properties.add(TransformProperty('transform', getLastTransform(), defaultValue: null));
}
}
/// A composited layer which annotates its children with a value. Pushing this
/// layer to the tree is the common way of adding an annotation.
///
/// An annotation is an optional object of any type that, when attached with a
/// layer, can be retrieved using [Layer.find] or [Layer.findAllAnnotations]
/// with a position. The search process is done recursively, controlled by a
/// concept of being opaque to a type of annotation, explained in the document
/// of [Layer.findAnnotations].
///
/// When an annotation search arrives, this layer defers the same search to each
/// of this layer's children, respecting their opacity. Then it adds this
/// layer's annotation if all of the following restrictions are met:
///
/// {@template flutter.rendering.AnnotatedRegionLayer.restrictions}
/// * The target type must be identical to the annotated type `T`.
/// * If [size] is provided, the target position must be contained within the
/// rectangle formed by [size] and [offset].
/// {@endtemplate}
///
/// This layer is opaque to a type of annotation if any child is also opaque, or
/// if [opaque] is true and the layer's annotation is added.
class AnnotatedRegionLayer<T extends Object> extends ContainerLayer {
/// Creates a new layer that annotates its children with [value].
AnnotatedRegionLayer(
this.value, {
this.size,
Offset? offset,
this.opaque = false,
}) : offset = offset ?? Offset.zero;
/// The annotated object, which is added to the result if all restrictions are
/// met.
final T value;
/// The size of the annotated object.
///
/// If [size] is provided, then the annotation is found only if the target
/// position is contained by the rectangle formed by [size] and [offset].
/// Otherwise no such restriction is applied, and clipping can only be done by
/// the ancestor layers.
final Size? size;
/// The position of the annotated object.
///
/// The [offset] defaults to [Offset.zero] if not provided, and is ignored if
/// [size] is not set.
///
/// The [offset] only offsets the clipping rectangle, and does not affect
/// how the painting or annotation search is propagated to its children.
final Offset offset;
/// Whether the annotation of this layer should be opaque during an annotation
/// search of type `T`, preventing siblings visually behind it from being
/// searched.
///
/// If [opaque] is true, and this layer does add its annotation [value],
/// then the layer will always be opaque during the search.
///
/// If [opaque] is false, or if this layer does not add its annotation,
/// then the opacity of this layer will be the one returned by the children,
/// meaning that it will be opaque if any child is opaque.
///
/// The [opaque] defaults to false.
///
/// The [opaque] is effectively useless during [Layer.find] (more
/// specifically, [Layer.findAnnotations] with `onlyFirst: true`), since the
/// search process then skips the remaining tree after finding the first
/// annotation.
///
/// See also:
///
/// * [Layer.findAnnotations], which explains the concept of being opaque
/// to a type of annotation as the return value.
/// * [HitTestBehavior], which controls similar logic when hit-testing in the
/// render tree.
final bool opaque;
/// Searches the subtree for annotations of type `S` at the location
/// `localPosition`, then adds the annotation [value] if applicable.
///
/// This method always searches its children, and if any child returns `true`,
/// the remaining children are skipped. Regardless of what the children
/// return, this method then adds this layer's annotation if all of the
/// following restrictions are met:
///
/// {@macro flutter.rendering.AnnotatedRegionLayer.restrictions}
///
/// This search process respects `onlyFirst`, meaning that when `onlyFirst` is
/// true, the search will stop when it finds the first annotation from the
/// children, and the layer's own annotation is checked only when none is
/// given by the children.
///
/// The return value is true if any child returns `true`, or if [opaque] is
/// true and the layer's annotation is added.
///
/// For explanation of layer annotations, parameters and return value, refer
/// to [Layer.findAnnotations].
@override
bool findAnnotations<S extends Object>(AnnotationResult<S> result, Offset localPosition, { required bool onlyFirst }) {
bool isAbsorbed = super.findAnnotations(result, localPosition, onlyFirst: onlyFirst);
if (result.entries.isNotEmpty && onlyFirst) {
return isAbsorbed;
}
if (size != null && !(offset & size!).contains(localPosition)) {
return isAbsorbed;
}
if (T == S) {
isAbsorbed = isAbsorbed || opaque;
final Object untypedValue = value;
final S typedValue = untypedValue as S;
result.add(AnnotationEntry<S>(
annotation: typedValue,
localPosition: localPosition - offset,
));
}
return isAbsorbed;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<T>('value', value));
properties.add(DiagnosticsProperty<Size>('size', size, defaultValue: null));
properties.add(DiagnosticsProperty<Offset>('offset', offset, defaultValue: null));
properties.add(DiagnosticsProperty<bool>('opaque', opaque, defaultValue: false));
}
}
| flutter/packages/flutter/lib/src/rendering/layer.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/rendering/layer.dart",
"repo_id": "flutter",
"token_count": 31639
} | 811 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'box.dart';
import 'object.dart';
import 'sliver.dart';
import 'sliver_fixed_extent_list.dart';
/// A sliver that contains multiple box children that each fill the viewport.
///
/// [RenderSliverFillViewport] places its children in a linear array along the
/// main axis. Each child is sized to fill the viewport, both in the main and
/// cross axis. A [viewportFraction] factor can be provided to size the children
/// to a multiple of the viewport's main axis dimension (typically a fraction
/// less than 1.0).
///
/// See also:
///
/// * [RenderSliverFillRemaining], which sizes the children based on the
/// remaining space rather than the viewport itself.
/// * [RenderSliverFixedExtentList], which has a configurable [itemExtent].
/// * [RenderSliverList], which does not require its children to have the same
/// extent in the main axis.
class RenderSliverFillViewport extends RenderSliverFixedExtentBoxAdaptor {
/// Creates a sliver that contains multiple box children that each fill the
/// viewport.
RenderSliverFillViewport({
required super.childManager,
double viewportFraction = 1.0,
}) : assert(viewportFraction > 0.0),
_viewportFraction = viewportFraction;
@override
double get itemExtent => constraints.viewportMainAxisExtent * viewportFraction;
/// The fraction of the viewport that each child should fill in the main axis.
///
/// If this fraction is less than 1.0, more than one child will be visible at
/// once. If this fraction is greater than 1.0, each child will be larger than
/// the viewport in the main axis.
double get viewportFraction => _viewportFraction;
double _viewportFraction;
set viewportFraction(double value) {
if (_viewportFraction == value) {
return;
}
_viewportFraction = value;
markNeedsLayout();
}
}
/// A sliver that contains a single box child that contains a scrollable and
/// fills the viewport.
///
/// [RenderSliverFillRemainingWithScrollable] sizes its child to fill the
/// viewport in the cross axis and to fill the remaining space in the viewport
/// in the main axis.
///
/// Typically this will be the last sliver in a viewport, since (by definition)
/// there is never any room for anything beyond this sliver.
///
/// See also:
///
/// * [NestedScrollView], which uses this sliver for the inner scrollable.
/// * [RenderSliverFillRemaining], which lays out its
/// non-scrollable child slightly different than this widget.
/// * [RenderSliverFillRemainingAndOverscroll], which incorporates the
/// overscroll into the remaining space to fill.
/// * [RenderSliverFillViewport], which sizes its children based on the
/// size of the viewport, regardless of what else is in the scroll view.
/// * [RenderSliverList], which shows a list of variable-sized children in a
/// viewport.
class RenderSliverFillRemainingWithScrollable extends RenderSliverSingleBoxAdapter {
/// Creates a [RenderSliver] that wraps a scrollable [RenderBox] which is
/// sized to fit the remaining space in the viewport.
RenderSliverFillRemainingWithScrollable({ super.child });
@override
void performLayout() {
final SliverConstraints constraints = this.constraints;
final double extent = constraints.remainingPaintExtent - math.min(constraints.overlap, 0.0);
final double cacheExtent = calculateCacheOffset(
constraints,
from: 0.0,
to: constraints.viewportMainAxisExtent,
);
if (child != null) {
double maxExtent = extent;
// If sliver has no extent, but is within viewport's cacheExtent, use the
// sliver's cacheExtent as the maxExtent so that it does not get dropped
// from the semantic tree.
if (extent == 0 && cacheExtent > 0) {
maxExtent = cacheExtent;
}
child!.layout(constraints.asBoxConstraints(
minExtent: extent,
maxExtent: maxExtent,
));
}
final double paintedChildSize = calculatePaintOffset(constraints, from: 0.0, to: extent);
assert(paintedChildSize.isFinite);
assert(paintedChildSize >= 0.0);
geometry = SliverGeometry(
scrollExtent: constraints.viewportMainAxisExtent,
paintExtent: paintedChildSize,
maxPaintExtent: paintedChildSize,
hasVisualOverflow: extent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0,
cacheExtent: cacheExtent,
);
if (child != null) {
setChildParentData(child!, constraints, geometry!);
}
}
}
/// A sliver that contains a single box child that is non-scrollable and fills
/// the remaining space in the viewport.
///
/// [RenderSliverFillRemaining] sizes its child to fill the
/// viewport in the cross axis and to fill the remaining space in the viewport
/// in the main axis.
///
/// Typically this will be the last sliver in a viewport, since (by definition)
/// there is never any room for anything beyond this sliver.
///
/// See also:
///
/// * [RenderSliverFillRemainingWithScrollable], which lays out its scrollable
/// child slightly different than this widget.
/// * [RenderSliverFillRemainingAndOverscroll], which incorporates the
/// overscroll into the remaining space to fill.
/// * [RenderSliverFillViewport], which sizes its children based on the
/// size of the viewport, regardless of what else is in the scroll view.
/// * [RenderSliverList], which shows a list of variable-sized children in a
/// viewport.
class RenderSliverFillRemaining extends RenderSliverSingleBoxAdapter {
/// Creates a [RenderSliver] that wraps a non-scrollable [RenderBox] which is
/// sized to fit the remaining space in the viewport.
RenderSliverFillRemaining({ super.child });
@override
void performLayout() {
final SliverConstraints constraints = this.constraints;
// The remaining space in the viewportMainAxisExtent. Can be <= 0 if we have
// scrolled beyond the extent of the screen.
double extent = constraints.viewportMainAxisExtent - constraints.precedingScrollExtent;
if (child != null) {
final double childExtent = switch (constraints.axis) {
Axis.horizontal => child!.getMaxIntrinsicWidth(constraints.crossAxisExtent),
Axis.vertical => child!.getMaxIntrinsicHeight(constraints.crossAxisExtent),
};
// If the childExtent is greater than the computed extent, we want to use
// that instead of potentially cutting off the child. This allows us to
// safely specify a maxExtent.
extent = math.max(extent, childExtent);
child!.layout(constraints.asBoxConstraints(
minExtent: extent,
maxExtent: extent,
));
}
assert(extent.isFinite,
'The calculated extent for the child of SliverFillRemaining is not finite. '
'This can happen if the child is a scrollable, in which case, the '
'hasScrollBody property of SliverFillRemaining should not be set to '
'false.',
);
final double paintedChildSize = calculatePaintOffset(constraints, from: 0.0, to: extent);
assert(paintedChildSize.isFinite);
assert(paintedChildSize >= 0.0);
final double cacheExtent = calculateCacheOffset(constraints, from: 0.0, to: extent);
geometry = SliverGeometry(
scrollExtent: extent,
paintExtent: paintedChildSize,
maxPaintExtent: paintedChildSize,
hasVisualOverflow: extent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0,
cacheExtent: cacheExtent,
);
if (child != null) {
setChildParentData(child!, constraints, geometry!);
}
}
}
/// A sliver that contains a single box child that is non-scrollable and fills
/// the remaining space in the viewport including any overscrolled area.
///
/// [RenderSliverFillRemainingAndOverscroll] sizes its child to fill the
/// viewport in the cross axis and to fill the remaining space in the viewport
/// in the main axis with the overscroll area included.
///
/// Typically this will be the last sliver in a viewport, since (by definition)
/// there is never any room for anything beyond this sliver.
///
/// See also:
///
/// * [RenderSliverFillRemainingWithScrollable], which lays out its scrollable
/// child without overscroll.
/// * [RenderSliverFillRemaining], which lays out its
/// non-scrollable child without overscroll.
/// * [RenderSliverFillViewport], which sizes its children based on the
/// size of the viewport, regardless of what else is in the scroll view.
/// * [RenderSliverList], which shows a list of variable-sized children in a
/// viewport.
class RenderSliverFillRemainingAndOverscroll extends RenderSliverSingleBoxAdapter {
/// Creates a [RenderSliver] that wraps a non-scrollable [RenderBox] which is
/// sized to fit the remaining space plus any overscroll in the viewport.
RenderSliverFillRemainingAndOverscroll({ super.child });
@override
void performLayout() {
final SliverConstraints constraints = this.constraints;
// The remaining space in the viewportMainAxisExtent. Can be <= 0 if we have
// scrolled beyond the extent of the screen.
double extent = constraints.viewportMainAxisExtent - constraints.precedingScrollExtent;
// The maxExtent includes any overscrolled area. Can be < 0 if we have
// overscroll in the opposite direction, away from the end of the list.
double maxExtent = constraints.remainingPaintExtent - math.min(constraints.overlap, 0.0);
if (child != null) {
final double childExtent = switch (constraints.axis) {
Axis.horizontal => child!.getMaxIntrinsicWidth(constraints.crossAxisExtent),
Axis.vertical => child!.getMaxIntrinsicHeight(constraints.crossAxisExtent),
};
// If the childExtent is greater than the computed extent, we want to use
// that instead of potentially cutting off the child. This allows us to
// safely specify a maxExtent.
extent = math.max(extent, childExtent);
// The extent could be larger than the maxExtent due to a larger child
// size or overscrolling at the top of the scrollable (rather than at the
// end where this sliver is).
maxExtent = math.max(extent, maxExtent);
child!.layout(constraints.asBoxConstraints(minExtent: extent, maxExtent: maxExtent));
}
assert(extent.isFinite,
'The calculated extent for the child of SliverFillRemaining is not finite. '
'This can happen if the child is a scrollable, in which case, the '
'hasScrollBody property of SliverFillRemaining should not be set to '
'false.',
);
final double paintedChildSize = calculatePaintOffset(constraints, from: 0.0, to: extent);
assert(paintedChildSize.isFinite);
assert(paintedChildSize >= 0.0);
final double cacheExtent = calculateCacheOffset(constraints, from: 0.0, to: extent);
geometry = SliverGeometry(
scrollExtent: extent,
paintExtent: math.min(maxExtent, constraints.remainingPaintExtent),
maxPaintExtent: maxExtent,
hasVisualOverflow: extent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0,
cacheExtent: cacheExtent,
);
if (child != null) {
setChildParentData(child!, constraints, geometry!);
}
}
}
| flutter/packages/flutter/lib/src/rendering/sliver_fill.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/rendering/sliver_fill.dart",
"repo_id": "flutter",
"token_count": 3598
} | 812 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'box.dart';
import 'layer.dart';
import 'layout_helper.dart';
import 'object.dart';
/// How [Wrap] should align objects.
///
/// Used both to align children within a run in the main axis as well as to
/// align the runs themselves in the cross axis.
enum WrapAlignment {
/// Place the objects as close to the start of the axis as possible.
///
/// If this value is used in a horizontal direction, a [TextDirection] must be
/// available to determine if the start is the left or the right.
///
/// If this value is used in a vertical direction, a [VerticalDirection] must be
/// available to determine if the start is the top or the bottom.
start,
/// Place the objects as close to the end of the axis as possible.
///
/// If this value is used in a horizontal direction, a [TextDirection] must be
/// available to determine if the end is the left or the right.
///
/// If this value is used in a vertical direction, a [VerticalDirection] must be
/// available to determine if the end is the top or the bottom.
end,
/// Place the objects as close to the middle of the axis as possible.
center,
/// Place the free space evenly between the objects.
spaceBetween,
/// Place the free space evenly between the objects as well as half of that
/// space before and after the first and last objects.
spaceAround,
/// Place the free space evenly between the objects as well as before and
/// after the first and last objects.
spaceEvenly,
}
/// Who [Wrap] should align children within a run in the cross axis.
enum WrapCrossAlignment {
/// Place the children as close to the start of the run in the cross axis as
/// possible.
///
/// If this value is used in a horizontal direction, a [TextDirection] must be
/// available to determine if the start is the left or the right.
///
/// If this value is used in a vertical direction, a [VerticalDirection] must be
/// available to determine if the start is the top or the bottom.
start,
/// Place the children as close to the end of the run in the cross axis as
/// possible.
///
/// If this value is used in a horizontal direction, a [TextDirection] must be
/// available to determine if the end is the left or the right.
///
/// If this value is used in a vertical direction, a [VerticalDirection] must be
/// available to determine if the end is the top or the bottom.
end,
/// Place the children as close to the middle of the run in the cross axis as
/// possible.
center,
// TODO(ianh): baseline.
}
class _RunMetrics {
_RunMetrics(this.mainAxisExtent, this.crossAxisExtent, this.childCount);
final double mainAxisExtent;
final double crossAxisExtent;
final int childCount;
}
/// Parent data for use with [RenderWrap].
class WrapParentData extends ContainerBoxParentData<RenderBox> {
int _runIndex = 0;
}
/// Displays its children in multiple horizontal or vertical runs.
///
/// A [RenderWrap] lays out each child and attempts to place the child adjacent
/// to the previous child in the main axis, given by [direction], leaving
/// [spacing] space in between. If there is not enough space to fit the child,
/// [RenderWrap] creates a new _run_ adjacent to the existing children in the
/// cross axis.
///
/// After all the children have been allocated to runs, the children within the
/// runs are positioned according to the [alignment] in the main axis and
/// according to the [crossAxisAlignment] in the cross axis.
///
/// The runs themselves are then positioned in the cross axis according to the
/// [runSpacing] and [runAlignment].
class RenderWrap extends RenderBox
with ContainerRenderObjectMixin<RenderBox, WrapParentData>,
RenderBoxContainerDefaultsMixin<RenderBox, WrapParentData> {
/// Creates a wrap render object.
///
/// By default, the wrap layout is horizontal and both the children and the
/// runs are aligned to the start.
RenderWrap({
List<RenderBox>? children,
Axis direction = Axis.horizontal,
WrapAlignment alignment = WrapAlignment.start,
double spacing = 0.0,
WrapAlignment runAlignment = WrapAlignment.start,
double runSpacing = 0.0,
WrapCrossAlignment crossAxisAlignment = WrapCrossAlignment.start,
TextDirection? textDirection,
VerticalDirection verticalDirection = VerticalDirection.down,
Clip clipBehavior = Clip.none,
}) : _direction = direction,
_alignment = alignment,
_spacing = spacing,
_runAlignment = runAlignment,
_runSpacing = runSpacing,
_crossAxisAlignment = crossAxisAlignment,
_textDirection = textDirection,
_verticalDirection = verticalDirection,
_clipBehavior = clipBehavior {
addAll(children);
}
/// The direction to use as the main axis.
///
/// For example, if [direction] is [Axis.horizontal], the default, the
/// children are placed adjacent to one another in a horizontal run until the
/// available horizontal space is consumed, at which point a subsequent
/// children are placed in a new run vertically adjacent to the previous run.
Axis get direction => _direction;
Axis _direction;
set direction (Axis value) {
if (_direction == value) {
return;
}
_direction = value;
markNeedsLayout();
}
/// How the children within a run should be placed in the main axis.
///
/// For example, if [alignment] is [WrapAlignment.center], the children in
/// each run are grouped together in the center of their run in the main axis.
///
/// Defaults to [WrapAlignment.start].
///
/// See also:
///
/// * [runAlignment], which controls how the runs are placed relative to each
/// other in the cross axis.
/// * [crossAxisAlignment], which controls how the children within each run
/// are placed relative to each other in the cross axis.
WrapAlignment get alignment => _alignment;
WrapAlignment _alignment;
set alignment (WrapAlignment value) {
if (_alignment == value) {
return;
}
_alignment = value;
markNeedsLayout();
}
/// How much space to place between children in a run in the main axis.
///
/// For example, if [spacing] is 10.0, the children will be spaced at least
/// 10.0 logical pixels apart in the main axis.
///
/// If there is additional free space in a run (e.g., because the wrap has a
/// minimum size that is not filled or because some runs are longer than
/// others), the additional free space will be allocated according to the
/// [alignment].
///
/// Defaults to 0.0.
double get spacing => _spacing;
double _spacing;
set spacing (double value) {
if (_spacing == value) {
return;
}
_spacing = value;
markNeedsLayout();
}
/// How the runs themselves should be placed in the cross axis.
///
/// For example, if [runAlignment] is [WrapAlignment.center], the runs are
/// grouped together in the center of the overall [RenderWrap] in the cross
/// axis.
///
/// Defaults to [WrapAlignment.start].
///
/// See also:
///
/// * [alignment], which controls how the children within each run are placed
/// relative to each other in the main axis.
/// * [crossAxisAlignment], which controls how the children within each run
/// are placed relative to each other in the cross axis.
WrapAlignment get runAlignment => _runAlignment;
WrapAlignment _runAlignment;
set runAlignment (WrapAlignment value) {
if (_runAlignment == value) {
return;
}
_runAlignment = value;
markNeedsLayout();
}
/// How much space to place between the runs themselves in the cross axis.
///
/// For example, if [runSpacing] is 10.0, the runs will be spaced at least
/// 10.0 logical pixels apart in the cross axis.
///
/// If there is additional free space in the overall [RenderWrap] (e.g.,
/// because the wrap has a minimum size that is not filled), the additional
/// free space will be allocated according to the [runAlignment].
///
/// Defaults to 0.0.
double get runSpacing => _runSpacing;
double _runSpacing;
set runSpacing (double value) {
if (_runSpacing == value) {
return;
}
_runSpacing = value;
markNeedsLayout();
}
/// How the children within a run should be aligned relative to each other in
/// the cross axis.
///
/// For example, if this is set to [WrapCrossAlignment.end], and the
/// [direction] is [Axis.horizontal], then the children within each
/// run will have their bottom edges aligned to the bottom edge of the run.
///
/// Defaults to [WrapCrossAlignment.start].
///
/// See also:
///
/// * [alignment], which controls how the children within each run are placed
/// relative to each other in the main axis.
/// * [runAlignment], which controls how the runs are placed relative to each
/// other in the cross axis.
WrapCrossAlignment get crossAxisAlignment => _crossAxisAlignment;
WrapCrossAlignment _crossAxisAlignment;
set crossAxisAlignment (WrapCrossAlignment value) {
if (_crossAxisAlignment == value) {
return;
}
_crossAxisAlignment = value;
markNeedsLayout();
}
/// Determines the order to lay children out horizontally and how to interpret
/// `start` and `end` in the horizontal direction.
///
/// If the [direction] is [Axis.horizontal], this controls the order in which
/// children are positioned (left-to-right or right-to-left), and the meaning
/// of the [alignment] property's [WrapAlignment.start] and
/// [WrapAlignment.end] values.
///
/// If the [direction] is [Axis.horizontal], and either the
/// [alignment] is either [WrapAlignment.start] or [WrapAlignment.end], or
/// there's more than one child, then the [textDirection] must not be null.
///
/// If the [direction] is [Axis.vertical], this controls the order in
/// which runs are positioned, the meaning of the [runAlignment] property's
/// [WrapAlignment.start] and [WrapAlignment.end] values, as well as the
/// [crossAxisAlignment] property's [WrapCrossAlignment.start] and
/// [WrapCrossAlignment.end] values.
///
/// If the [direction] is [Axis.vertical], and either the
/// [runAlignment] is either [WrapAlignment.start] or [WrapAlignment.end], the
/// [crossAxisAlignment] is either [WrapCrossAlignment.start] or
/// [WrapCrossAlignment.end], or there's more than one child, then the
/// [textDirection] must not be null.
TextDirection? get textDirection => _textDirection;
TextDirection? _textDirection;
set textDirection(TextDirection? value) {
if (_textDirection != value) {
_textDirection = value;
markNeedsLayout();
}
}
/// Determines the order to lay children out vertically and how to interpret
/// `start` and `end` in the vertical direction.
///
/// If the [direction] is [Axis.vertical], this controls which order children
/// are painted in (down or up), the meaning of the [alignment] property's
/// [WrapAlignment.start] and [WrapAlignment.end] values.
///
/// If the [direction] is [Axis.vertical], and either the [alignment]
/// is either [WrapAlignment.start] or [WrapAlignment.end], or there's
/// more than one child, then the [verticalDirection] must not be null.
///
/// If the [direction] is [Axis.horizontal], this controls the order in which
/// runs are positioned, the meaning of the [runAlignment] property's
/// [WrapAlignment.start] and [WrapAlignment.end] values, as well as the
/// [crossAxisAlignment] property's [WrapCrossAlignment.start] and
/// [WrapCrossAlignment.end] values.
///
/// If the [direction] is [Axis.horizontal], and either the
/// [runAlignment] is either [WrapAlignment.start] or [WrapAlignment.end], the
/// [crossAxisAlignment] is either [WrapCrossAlignment.start] or
/// [WrapCrossAlignment.end], or there's more than one child, then the
/// [verticalDirection] must not be null.
VerticalDirection get verticalDirection => _verticalDirection;
VerticalDirection _verticalDirection;
set verticalDirection(VerticalDirection value) {
if (_verticalDirection != value) {
_verticalDirection = value;
markNeedsLayout();
}
}
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.none].
Clip get clipBehavior => _clipBehavior;
Clip _clipBehavior = Clip.none;
set clipBehavior(Clip value) {
if (value != _clipBehavior) {
_clipBehavior = value;
markNeedsPaint();
markNeedsSemanticsUpdate();
}
}
bool get _debugHasNecessaryDirections {
if (firstChild != null && lastChild != firstChild) {
// i.e. there's more than one child
switch (direction) {
case Axis.horizontal:
assert(textDirection != null, 'Horizontal $runtimeType with multiple children has a null textDirection, so the layout order is undefined.');
case Axis.vertical:
break;
}
}
if (alignment == WrapAlignment.start || alignment == WrapAlignment.end) {
switch (direction) {
case Axis.horizontal:
assert(textDirection != null, 'Horizontal $runtimeType with alignment $alignment has a null textDirection, so the alignment cannot be resolved.');
case Axis.vertical:
break;
}
}
if (runAlignment == WrapAlignment.start || runAlignment == WrapAlignment.end) {
switch (direction) {
case Axis.horizontal:
break;
case Axis.vertical:
assert(textDirection != null, 'Vertical $runtimeType with runAlignment $runAlignment has a null textDirection, so the alignment cannot be resolved.');
}
}
if (crossAxisAlignment == WrapCrossAlignment.start || crossAxisAlignment == WrapCrossAlignment.end) {
switch (direction) {
case Axis.horizontal:
break;
case Axis.vertical:
assert(textDirection != null, 'Vertical $runtimeType with crossAxisAlignment $crossAxisAlignment has a null textDirection, so the alignment cannot be resolved.');
}
}
return true;
}
@override
void setupParentData(RenderBox child) {
if (child.parentData is! WrapParentData) {
child.parentData = WrapParentData();
}
}
@override
double computeMinIntrinsicWidth(double height) {
switch (direction) {
case Axis.horizontal:
double width = 0.0;
RenderBox? child = firstChild;
while (child != null) {
width = math.max(width, child.getMinIntrinsicWidth(double.infinity));
child = childAfter(child);
}
return width;
case Axis.vertical:
return computeDryLayout(BoxConstraints(maxHeight: height)).width;
}
}
@override
double computeMaxIntrinsicWidth(double height) {
switch (direction) {
case Axis.horizontal:
double width = 0.0;
RenderBox? child = firstChild;
while (child != null) {
width += child.getMaxIntrinsicWidth(double.infinity);
child = childAfter(child);
}
return width;
case Axis.vertical:
return computeDryLayout(BoxConstraints(maxHeight: height)).width;
}
}
@override
double computeMinIntrinsicHeight(double width) {
switch (direction) {
case Axis.horizontal:
return computeDryLayout(BoxConstraints(maxWidth: width)).height;
case Axis.vertical:
double height = 0.0;
RenderBox? child = firstChild;
while (child != null) {
height = math.max(height, child.getMinIntrinsicHeight(double.infinity));
child = childAfter(child);
}
return height;
}
}
@override
double computeMaxIntrinsicHeight(double width) {
switch (direction) {
case Axis.horizontal:
return computeDryLayout(BoxConstraints(maxWidth: width)).height;
case Axis.vertical:
double height = 0.0;
RenderBox? child = firstChild;
while (child != null) {
height += child.getMaxIntrinsicHeight(double.infinity);
child = childAfter(child);
}
return height;
}
}
@override
double? computeDistanceToActualBaseline(TextBaseline baseline) {
return defaultComputeDistanceToHighestActualBaseline(baseline);
}
double _getMainAxisExtent(Size childSize) {
return switch (direction) {
Axis.horizontal => childSize.width,
Axis.vertical => childSize.height,
};
}
double _getCrossAxisExtent(Size childSize) {
return switch (direction) {
Axis.horizontal => childSize.height,
Axis.vertical => childSize.width,
};
}
Offset _getOffset(double mainAxisOffset, double crossAxisOffset) {
return switch (direction) {
Axis.horizontal => Offset(mainAxisOffset, crossAxisOffset),
Axis.vertical => Offset(crossAxisOffset, mainAxisOffset),
};
}
double _getChildCrossAxisOffset(bool flipCrossAxis, double runCrossAxisExtent, double childCrossAxisExtent) {
final double freeSpace = runCrossAxisExtent - childCrossAxisExtent;
return switch (crossAxisAlignment) {
WrapCrossAlignment.start => flipCrossAxis ? freeSpace : 0.0,
WrapCrossAlignment.end => flipCrossAxis ? 0.0 : freeSpace,
WrapCrossAlignment.center => freeSpace / 2.0,
};
}
bool _hasVisualOverflow = false;
@override
@protected
Size computeDryLayout(covariant BoxConstraints constraints) {
return _computeDryLayout(constraints);
}
Size _computeDryLayout(BoxConstraints constraints, [ChildLayouter layoutChild = ChildLayoutHelper.dryLayoutChild]) {
final (BoxConstraints childConstraints, double mainAxisLimit) = switch (direction) {
Axis.horizontal => (BoxConstraints(maxWidth: constraints.maxWidth), constraints.maxWidth),
Axis.vertical => (BoxConstraints(maxHeight: constraints.maxHeight), constraints.maxHeight),
};
double mainAxisExtent = 0.0;
double crossAxisExtent = 0.0;
double runMainAxisExtent = 0.0;
double runCrossAxisExtent = 0.0;
int childCount = 0;
RenderBox? child = firstChild;
while (child != null) {
final Size childSize = layoutChild(child, childConstraints);
final double childMainAxisExtent = _getMainAxisExtent(childSize);
final double childCrossAxisExtent = _getCrossAxisExtent(childSize);
// There must be at least one child before we move on to the next run.
if (childCount > 0 && runMainAxisExtent + childMainAxisExtent + spacing > mainAxisLimit) {
mainAxisExtent = math.max(mainAxisExtent, runMainAxisExtent);
crossAxisExtent += runCrossAxisExtent + runSpacing;
runMainAxisExtent = 0.0;
runCrossAxisExtent = 0.0;
childCount = 0;
}
runMainAxisExtent += childMainAxisExtent;
runCrossAxisExtent = math.max(runCrossAxisExtent, childCrossAxisExtent);
if (childCount > 0) {
runMainAxisExtent += spacing;
}
childCount += 1;
child = childAfter(child);
}
crossAxisExtent += runCrossAxisExtent;
mainAxisExtent = math.max(mainAxisExtent, runMainAxisExtent);
return constraints.constrain(switch (direction) {
Axis.horizontal => Size(mainAxisExtent, crossAxisExtent),
Axis.vertical => Size(crossAxisExtent, mainAxisExtent),
});
}
@override
void performLayout() {
final BoxConstraints constraints = this.constraints;
assert(_debugHasNecessaryDirections);
_hasVisualOverflow = false;
RenderBox? child = firstChild;
if (child == null) {
size = constraints.smallest;
return;
}
final BoxConstraints childConstraints;
double mainAxisLimit = 0.0;
bool flipMainAxis = false;
bool flipCrossAxis = false;
switch (direction) {
case Axis.horizontal:
childConstraints = BoxConstraints(maxWidth: constraints.maxWidth);
mainAxisLimit = constraints.maxWidth;
if (textDirection == TextDirection.rtl) {
flipMainAxis = true;
}
if (verticalDirection == VerticalDirection.up) {
flipCrossAxis = true;
}
case Axis.vertical:
childConstraints = BoxConstraints(maxHeight: constraints.maxHeight);
mainAxisLimit = constraints.maxHeight;
if (verticalDirection == VerticalDirection.up) {
flipMainAxis = true;
}
if (textDirection == TextDirection.rtl) {
flipCrossAxis = true;
}
}
final double spacing = this.spacing;
final double runSpacing = this.runSpacing;
final List<_RunMetrics> runMetrics = <_RunMetrics>[];
double mainAxisExtent = 0.0;
double crossAxisExtent = 0.0;
double runMainAxisExtent = 0.0;
double runCrossAxisExtent = 0.0;
int childCount = 0;
while (child != null) {
child.layout(childConstraints, parentUsesSize: true);
final double childMainAxisExtent = _getMainAxisExtent(child.size);
final double childCrossAxisExtent = _getCrossAxisExtent(child.size);
if (childCount > 0 && runMainAxisExtent + spacing + childMainAxisExtent > mainAxisLimit) {
mainAxisExtent = math.max(mainAxisExtent, runMainAxisExtent);
crossAxisExtent += runCrossAxisExtent;
if (runMetrics.isNotEmpty) {
crossAxisExtent += runSpacing;
}
runMetrics.add(_RunMetrics(runMainAxisExtent, runCrossAxisExtent, childCount));
runMainAxisExtent = 0.0;
runCrossAxisExtent = 0.0;
childCount = 0;
}
runMainAxisExtent += childMainAxisExtent;
if (childCount > 0) {
runMainAxisExtent += spacing;
}
runCrossAxisExtent = math.max(runCrossAxisExtent, childCrossAxisExtent);
childCount += 1;
final WrapParentData childParentData = child.parentData! as WrapParentData;
childParentData._runIndex = runMetrics.length;
child = childParentData.nextSibling;
}
if (childCount > 0) {
mainAxisExtent = math.max(mainAxisExtent, runMainAxisExtent);
crossAxisExtent += runCrossAxisExtent;
if (runMetrics.isNotEmpty) {
crossAxisExtent += runSpacing;
}
runMetrics.add(_RunMetrics(runMainAxisExtent, runCrossAxisExtent, childCount));
}
final int runCount = runMetrics.length;
assert(runCount > 0);
double containerMainAxisExtent = 0.0;
double containerCrossAxisExtent = 0.0;
switch (direction) {
case Axis.horizontal:
size = constraints.constrain(Size(mainAxisExtent, crossAxisExtent));
containerMainAxisExtent = size.width;
containerCrossAxisExtent = size.height;
case Axis.vertical:
size = constraints.constrain(Size(crossAxisExtent, mainAxisExtent));
containerMainAxisExtent = size.height;
containerCrossAxisExtent = size.width;
}
_hasVisualOverflow = containerMainAxisExtent < mainAxisExtent || containerCrossAxisExtent < crossAxisExtent;
final double crossAxisFreeSpace = math.max(0.0, containerCrossAxisExtent - crossAxisExtent);
double runLeadingSpace = 0.0;
double runBetweenSpace = 0.0;
switch (runAlignment) {
case WrapAlignment.start:
break;
case WrapAlignment.end:
runLeadingSpace = crossAxisFreeSpace;
case WrapAlignment.center:
runLeadingSpace = crossAxisFreeSpace / 2.0;
case WrapAlignment.spaceBetween:
runBetweenSpace = runCount > 1 ? crossAxisFreeSpace / (runCount - 1) : 0.0;
case WrapAlignment.spaceAround:
runBetweenSpace = crossAxisFreeSpace / runCount;
runLeadingSpace = runBetweenSpace / 2.0;
case WrapAlignment.spaceEvenly:
runBetweenSpace = crossAxisFreeSpace / (runCount + 1);
runLeadingSpace = runBetweenSpace;
}
runBetweenSpace += runSpacing;
double crossAxisOffset = flipCrossAxis ? containerCrossAxisExtent - runLeadingSpace : runLeadingSpace;
child = firstChild;
for (int i = 0; i < runCount; ++i) {
final _RunMetrics metrics = runMetrics[i];
final double runMainAxisExtent = metrics.mainAxisExtent;
final double runCrossAxisExtent = metrics.crossAxisExtent;
final int childCount = metrics.childCount;
final double mainAxisFreeSpace = math.max(0.0, containerMainAxisExtent - runMainAxisExtent);
double childLeadingSpace = 0.0;
double childBetweenSpace = 0.0;
switch (alignment) {
case WrapAlignment.start:
break;
case WrapAlignment.end:
childLeadingSpace = mainAxisFreeSpace;
case WrapAlignment.center:
childLeadingSpace = mainAxisFreeSpace / 2.0;
case WrapAlignment.spaceBetween:
childBetweenSpace = childCount > 1 ? mainAxisFreeSpace / (childCount - 1) : 0.0;
case WrapAlignment.spaceAround:
childBetweenSpace = mainAxisFreeSpace / childCount;
childLeadingSpace = childBetweenSpace / 2.0;
case WrapAlignment.spaceEvenly:
childBetweenSpace = mainAxisFreeSpace / (childCount + 1);
childLeadingSpace = childBetweenSpace;
}
childBetweenSpace += spacing;
double childMainPosition = flipMainAxis ? containerMainAxisExtent - childLeadingSpace : childLeadingSpace;
if (flipCrossAxis) {
crossAxisOffset -= runCrossAxisExtent;
}
while (child != null) {
final WrapParentData childParentData = child.parentData! as WrapParentData;
if (childParentData._runIndex != i) {
break;
}
final double childMainAxisExtent = _getMainAxisExtent(child.size);
final double childCrossAxisExtent = _getCrossAxisExtent(child.size);
final double childCrossAxisOffset = _getChildCrossAxisOffset(flipCrossAxis, runCrossAxisExtent, childCrossAxisExtent);
if (flipMainAxis) {
childMainPosition -= childMainAxisExtent;
}
childParentData.offset = _getOffset(childMainPosition, crossAxisOffset + childCrossAxisOffset);
if (flipMainAxis) {
childMainPosition -= childBetweenSpace;
} else {
childMainPosition += childMainAxisExtent + childBetweenSpace;
}
child = childParentData.nextSibling;
}
if (flipCrossAxis) {
crossAxisOffset -= runBetweenSpace;
} else {
crossAxisOffset += runCrossAxisExtent + runBetweenSpace;
}
}
}
@override
bool hitTestChildren(BoxHitTestResult result, { required Offset position }) {
return defaultHitTestChildren(result, position: position);
}
@override
void paint(PaintingContext context, Offset offset) {
// TODO(ianh): move the debug flex overflow paint logic somewhere common so
// it can be reused here
if (_hasVisualOverflow && clipBehavior != Clip.none) {
_clipRectLayer.layer = context.pushClipRect(
needsCompositing,
offset,
Offset.zero & size,
defaultPaint,
clipBehavior: clipBehavior,
oldLayer: _clipRectLayer.layer,
);
} else {
_clipRectLayer.layer = null;
defaultPaint(context, offset);
}
}
final LayerHandle<ClipRectLayer> _clipRectLayer = LayerHandle<ClipRectLayer>();
@override
void dispose() {
_clipRectLayer.layer = null;
super.dispose();
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(EnumProperty<Axis>('direction', direction));
properties.add(EnumProperty<WrapAlignment>('alignment', alignment));
properties.add(DoubleProperty('spacing', spacing));
properties.add(EnumProperty<WrapAlignment>('runAlignment', runAlignment));
properties.add(DoubleProperty('runSpacing', runSpacing));
properties.add(DoubleProperty('crossAxisAlignment', runSpacing));
properties.add(EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null));
properties.add(EnumProperty<VerticalDirection>('verticalDirection', verticalDirection, defaultValue: VerticalDirection.down));
}
}
| flutter/packages/flutter/lib/src/rendering/wrap.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/rendering/wrap.dart",
"repo_id": "flutter",
"token_count": 9901
} | 813 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'dart:ui' as ui;
export 'dart:typed_data' show ByteData;
export 'dart:ui' show PlatformMessageResponseCallback;
/// A function which takes a platform message and asynchronously returns an encoded response.
typedef MessageHandler = Future<ByteData?>? Function(ByteData? message);
/// A messenger which sends binary data across the Flutter platform barrier.
///
/// This class also registers handlers for incoming messages.
abstract class BinaryMessenger {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const BinaryMessenger();
/// Queues a message.
///
/// The returned future completes immediately.
///
/// This method adds the provided message to the given channel (named by the
/// `channel` argument) of the [ChannelBuffers] object. This simulates what
/// happens when a plugin on the platform thread (e.g. Kotlin or Swift code)
/// sends a message to the plugin package on the Dart thread.
///
/// The `data` argument contains the message as encoded bytes. (The format
/// used for the message depends on the channel.)
///
/// The `callback` argument, if non-null, is eventually invoked with the
/// response that would have been sent to the platform thread.
///
/// In production code, it is more efficient to call
/// `ServicesBinding.instance.channelBuffers.push` directly.
///
/// In tests, consider using
/// `tester.binding.defaultBinaryMessenger.handlePlatformMessage` (see
/// [WidgetTester], [TestWidgetsFlutterBinding], [TestDefaultBinaryMessenger],
/// and [TestDefaultBinaryMessenger.handlePlatformMessage] respectively).
///
/// To register a handler for a given message channel, see [setMessageHandler].
///
/// To send a message _to_ a plugin on the platform thread, see [send].
@Deprecated(
'Instead of calling this method, use ServicesBinding.instance.channelBuffers.push. '
'In tests, consider using tester.binding.defaultBinaryMessenger.handlePlatformMessage '
'or TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage. '
'This feature was deprecated after v3.9.0-19.0.pre.'
)
Future<void> handlePlatformMessage(String channel, ByteData? data, ui.PlatformMessageResponseCallback? callback);
/// Send a binary message to the platform plugins on the given channel.
///
/// Returns a [Future] which completes to the received response, undecoded,
/// in binary form.
Future<ByteData?>? send(String channel, ByteData? message);
/// Set a callback for receiving messages from the platform plugins on the
/// given channel, without decoding them.
///
/// The given callback will replace the currently registered callback for that
/// channel, if any. To remove the handler, pass null as the [handler]
/// argument.
///
/// The handler's return value, if non-null, is sent as a response, unencoded.
void setMessageHandler(String channel, MessageHandler? handler);
// Looking for setMockMessageHandler or checkMockMessageHandler?
// See this shim package: packages/flutter_test/lib/src/deprecated.dart
}
| flutter/packages/flutter/lib/src/services/binary_messenger.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/services/binary_messenger.dart",
"repo_id": "flutter",
"token_count": 887
} | 814 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'system_channels.dart';
export 'package:flutter/foundation.dart' show DiagnosticLevel, DiagnosticPropertiesBuilder;
export 'package:flutter/gestures.dart' show PointerEvent;
/// Maintains the state of mouse cursors and manages how cursors are searched
/// for.
///
/// This is typically created as a global singleton and owned by [MouseTracker].
class MouseCursorManager {
/// Create a [MouseCursorManager] by specifying the fallback cursor.
///
/// The `fallbackMouseCursor` must not be [MouseCursor.defer] (typically
/// [SystemMouseCursors.basic]).
MouseCursorManager(this.fallbackMouseCursor)
: assert(fallbackMouseCursor != MouseCursor.defer);
/// The mouse cursor to use if all cursor candidates choose to defer.
///
/// See also:
///
/// * [MouseCursor.defer], the mouse cursor object to use to defer.
final MouseCursor fallbackMouseCursor;
/// Returns the active mouse cursor of a device.
///
/// The return value is the last [MouseCursor] activated onto this
/// device, even if the activation failed.
///
/// Only valid when asserts are enabled. In release builds, always returns
/// null.
MouseCursor? debugDeviceActiveCursor(int device) {
MouseCursor? result;
assert(() {
result = _lastSession[device]?.cursor;
return true;
}());
return result;
}
final Map<int, MouseCursorSession> _lastSession = <int, MouseCursorSession>{};
/// Handles the changes that cause a pointer device to have a new list of mouse
/// cursor candidates.
///
/// This change can be caused by a pointer event, in which case
/// `triggeringEvent` should not be null, or by other changes, such as when a
/// widget has moved under a still mouse, which is detected after the current
/// frame is complete. In either case, `cursorCandidates` should be the list of
/// cursors at the location of the mouse in hit-test order.
void handleDeviceCursorUpdate(
int device,
PointerEvent? triggeringEvent,
Iterable<MouseCursor> cursorCandidates,
) {
if (triggeringEvent is PointerRemovedEvent) {
_lastSession.remove(device);
return;
}
final MouseCursorSession? lastSession = _lastSession[device];
final MouseCursor nextCursor = _DeferringMouseCursor.firstNonDeferred(cursorCandidates)
?? fallbackMouseCursor;
assert(nextCursor is! _DeferringMouseCursor);
if (lastSession?.cursor == nextCursor) {
return;
}
final MouseCursorSession nextSession = nextCursor.createSession(device);
_lastSession[device] = nextSession;
lastSession?.dispose();
nextSession.activate();
}
}
/// Manages the duration that a pointing device should display a specific mouse
/// cursor.
///
/// While [MouseCursor] classes describe the kind of cursors, [MouseCursorSession]
/// classes represents a continuous use of the cursor on a pointing device. The
/// [MouseCursorSession] classes can be stateful. For example, a cursor that
/// needs to load resources might want to set a temporary cursor first, then
/// switch to the correct cursor after the load is completed.
///
/// A [MouseCursorSession] has the following lifecycle:
///
/// * When a pointing device should start displaying a cursor, [MouseTracker]
/// creates a session by calling [MouseCursor.createSession] on the target
/// cursor, and stores it in a table associated with the device.
/// * [MouseTracker] then immediately calls the session's [activate], where the
/// session should fetch resources and make system calls.
/// * When the pointing device should start displaying a different cursor,
/// [MouseTracker] calls [dispose] on this session. After [dispose], this session
/// will no longer be used in the future.
abstract class MouseCursorSession {
/// Create a session.
MouseCursorSession(this.cursor, this.device);
/// The cursor that created this session.
final MouseCursor cursor;
/// The device ID of the pointing device.
final int device;
/// Override this method to do the work of changing the cursor of the device.
///
/// Called right after this session is created.
///
/// This method has full control over the cursor until the [dispose] call, and
/// can make system calls to change the pointer cursor as many times as
/// necessary (usually through [SystemChannels.mouseCursor]). It can also
/// collect resources, and store the result in this object.
@protected
Future<void> activate();
/// Called when device stops displaying the cursor.
///
/// After this call, this session instance will no longer be used in the
/// future.
///
/// When implementing this method in subclasses, you should release resources
/// and prevent [activate] from causing side effects after disposal.
@protected
void dispose();
}
/// An interface for mouse cursor definitions.
///
/// A mouse cursor is a graphical image on the screen that echoes the movement
/// of a pointing device, such as a mouse or a stylus. A [MouseCursor] object
/// defines a kind of mouse cursor, such as an arrow, a pointing hand, or an
/// I-beam.
///
/// During the painting phase, [MouseCursor] objects are assigned to regions on
/// the screen via annotations. Later during a device update (e.g. when a mouse
/// moves), [MouseTracker] finds the _active cursor_ of each mouse device, which
/// is the front-most region associated with the position of each mouse cursor,
/// or defaults to [SystemMouseCursors.basic] if no cursors are associated with
/// the position. [MouseTracker] changes the cursor of the pointer if the new
/// active cursor is different from the previous active cursor, whose effect is
/// defined by the session created by [createSession].
///
/// ## Cursor classes
///
/// A [SystemMouseCursor] is a cursor that is natively supported by the
/// platform that the program is running on. All supported system mouse cursors
/// are enumerated in [SystemMouseCursors].
///
/// ## Using cursors
///
/// A [MouseCursor] object is used by being assigned to a [MouseRegion] or
/// another widget that exposes the [MouseRegion] API, such as
/// [InkResponse.mouseCursor].
///
/// {@tool dartpad}
/// This sample creates a rectangular region that is wrapped by a [MouseRegion]
/// with a system mouse cursor. The mouse pointer becomes an I-beam when
/// hovering over the region.
///
/// ** See code in examples/api/lib/services/mouse_cursor/mouse_cursor.0.dart **
/// {@end-tool}
///
/// Assigning regions with mouse cursors on platforms that do not support mouse
/// cursors, or when there are no mice connected, will have no effect.
///
/// ## Related classes
///
/// [MouseCursorSession] represents the duration when a pointing device displays
/// a cursor, and defines the states and behaviors of the cursor. Every mouse
/// cursor class usually has a corresponding [MouseCursorSession] class.
///
/// [MouseCursorManager] is a class that adds the feature of changing
/// cursors to [MouseTracker], which tracks the relationship between mouse
/// devices and annotations. [MouseCursorManager] is usually used as a part
/// of [MouseTracker].
@immutable
abstract class MouseCursor with Diagnosticable {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const MouseCursor();
/// Associate a pointing device to this cursor.
///
/// A mouse cursor class usually has a corresponding [MouseCursorSession]
/// class, and instantiates such class in this method.
///
/// This method is called each time a pointing device starts displaying this
/// cursor. A given cursor can be displayed by multiple devices at the same
/// time, in which case this method will be called separately for each device.
@protected
@factory
MouseCursorSession createSession(int device);
/// A very short description of the mouse cursor.
///
/// The [debugDescription] should be a few words that can describe this cursor
/// to make debug information more readable. It is returned as the [toString]
/// when the diagnostic level is at or above [DiagnosticLevel.info].
///
/// The [debugDescription] must not be empty.
String get debugDescription;
@override
String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) {
final String debugDescription = this.debugDescription;
if (minLevel.index >= DiagnosticLevel.info.index) {
return debugDescription;
}
return super.toString(minLevel: minLevel);
}
/// A special class that indicates that the region with this cursor defers the
/// choice of cursor to the next region behind it.
///
/// When an event occurs, [MouseTracker] will update each pointer's cursor by
/// finding the list of regions that contain the pointer's location, from front
/// to back in hit-test order. The pointer's cursor will be the first cursor in
/// the list that is not a [MouseCursor.defer].
static const MouseCursor defer = _DeferringMouseCursor._();
/// A special value that doesn't change cursor by itself, but make a region
/// that blocks other regions behind it from changing the cursor.
///
/// When a pointer enters a region with a cursor of [uncontrolled], the pointer
/// retains its previous cursor and keeps so until it moves out of the region.
/// Technically, this region absorb the mouse cursor hit test without changing
/// the pointer's cursor.
///
/// This is useful in a region that displays a platform view, which let the
/// operating system handle pointer events and change cursors accordingly. To
/// achieve this, the region's cursor must not be any Flutter cursor, since
/// that might overwrite the system request upon pointer entering; the cursor
/// must not be null either, since that allows the widgets behind the region to
/// change cursors.
static const MouseCursor uncontrolled = _NoopMouseCursor._();
}
class _DeferringMouseCursor extends MouseCursor {
const _DeferringMouseCursor._();
@override
MouseCursorSession createSession(int device) {
assert(false, '_DeferringMouseCursor can not create a session');
throw UnimplementedError();
}
@override
String get debugDescription => 'defer';
/// Returns the first cursor that is not a [MouseCursor.defer].
static MouseCursor? firstNonDeferred(Iterable<MouseCursor> cursors) {
for (final MouseCursor cursor in cursors) {
if (cursor != MouseCursor.defer) {
return cursor;
}
}
return null;
}
}
class _NoopMouseCursorSession extends MouseCursorSession {
_NoopMouseCursorSession(_NoopMouseCursor super.cursor, super.device);
@override
Future<void> activate() async { /* Nothing */ }
@override
void dispose() { /* Nothing */ }
}
/// A mouse cursor that doesn't change the cursor when activated.
///
/// Although setting a region's cursor to [NoopMouseCursor] doesn't change the
/// cursor, it blocks regions behind it from changing the cursor, in contrast to
/// setting the cursor to null. More information about the usage of this class
/// can be found at [MouseCursors.uncontrolled].
///
/// To use this class, use [MouseCursors.uncontrolled]. Directly
/// instantiating this class is not allowed.
class _NoopMouseCursor extends MouseCursor {
// Application code shouldn't directly instantiate this class, since its only
// instance is accessible at [SystemMouseCursors.releaseControl].
const _NoopMouseCursor._();
@override
@protected
_NoopMouseCursorSession createSession(int device) => _NoopMouseCursorSession(this, device);
@override
String get debugDescription => 'uncontrolled';
}
class _SystemMouseCursorSession extends MouseCursorSession {
_SystemMouseCursorSession(SystemMouseCursor super.cursor, super.device);
@override
SystemMouseCursor get cursor => super.cursor as SystemMouseCursor;
@override
Future<void> activate() {
return SystemChannels.mouseCursor.invokeMethod<void>(
'activateSystemCursor',
<String, dynamic>{
'device': device,
'kind': cursor.kind,
},
);
}
@override
void dispose() { /* Nothing */ }
}
/// A mouse cursor that is natively supported on the platform that the
/// application is running on.
///
/// System cursors can be used without external resources, and their appearances
/// match the experience of native apps. Examples of system cursors are a
/// pointing arrow, a pointing hand, a double arrow for resizing, or a text
/// I-beam, etc.
///
/// An instance of [SystemMouseCursor] refers to one cursor from each platform
/// that represents the same concept, such as being text, being clickable,
/// or being a forbidden operation. Since the set of system cursors supported by
/// each platform varies, multiple instances can correspond to the same system
/// cursor.
///
/// Each cursor is noted with its corresponding native cursors on each platform:
///
/// * Android: API name in Java
/// * Web: CSS cursor
/// * Windows: Win32 API
/// * Windows UWP: WinRT API, `winrt::Windows::UI::Core::CoreCursorType`
/// * Linux: GDK, `gdk_cursor_new_from_name`
/// * macOS: API name in Objective C
///
/// If the platform that the application is running on is not listed for a cursor,
/// using this cursor falls back to [SystemMouseCursors.basic].
///
/// [SystemMouseCursors] enumerates the complete set of system cursors supported
/// by Flutter, which are hard-coded in the engine. Therefore, manually
/// instantiating this class is not supported.
class SystemMouseCursor extends MouseCursor {
// Application code shouldn't directly instantiate system mouse cursors, since
// the supported system cursors are enumerated in [SystemMouseCursors].
const SystemMouseCursor._({
required this.kind,
});
/// A string that identifies the kind of the cursor.
///
/// The interpretation of [kind] is platform-dependent.
final String kind;
@override
String get debugDescription => '${objectRuntimeType(this, 'SystemMouseCursor')}($kind)';
@override
@protected
MouseCursorSession createSession(int device) => _SystemMouseCursorSession(this, device);
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is SystemMouseCursor
&& other.kind == kind;
}
@override
int get hashCode => kind.hashCode;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<String>('kind', kind, level: DiagnosticLevel.debug));
}
}
/// A collection of system [MouseCursor]s.
///
/// System cursors are standard mouse cursors that are provided by the current
/// platform. They don't require external resources.
///
/// [SystemMouseCursors] is a superset of the system cursors of every platform
/// that Flutter supports, therefore some of these objects might map to the same
/// result, or fallback to the [basic] arrow. This mapping is defined by the
/// Flutter engine.
///
/// The cursors should be named based on the cursors' use cases instead of their
/// appearance, because different platforms might (although not commonly) use
/// different shapes for the same use case.
abstract final class SystemMouseCursors {
// The mapping in this class must be kept in sync with the following files in
// the engine:
//
// * Android: shell/platform/android/io/flutter/plugin/mouse/MouseCursorPlugin.java
// * Web: lib/web_ui/lib/src/engine/mouse_cursor.dart
// * Windows: shell/platform/windows/win32_flutter_window_win32.cc
// * Windows UWP: shell/platform/windows/win32_flutter_window_winuwp.cc
// * Linux: shell/platform/linux/fl_mouse_cursor_plugin.cc
// * macOS: shell/platform/darwin/macos/framework/Source/FlutterMouseCursorPlugin.mm
/// Hide the cursor.
///
/// Any cursor other than [none] or [MouseCursor.uncontrolled] unhides the
/// cursor.
static const SystemMouseCursor none = SystemMouseCursor._(kind: 'none');
// STATUS
/// The platform-dependent basic cursor.
///
/// Typically the shape of an arrow.
///
/// Corresponds to:
///
/// * Android: TYPE_DEFAULT, TYPE_ARROW
/// * Web: default
/// * Windows: IDC_ARROW
/// * Windows UWP: CoreCursorType::Arrow
/// * Linux: default
/// * macOS: arrowCursor
static const SystemMouseCursor basic = SystemMouseCursor._(kind: 'basic');
/// A cursor that emphasizes an element being clickable, such as a hyperlink.
///
/// Typically the shape of a pointing hand.
///
/// Corresponds to:
///
/// * Android: TYPE_HAND
/// * Web: pointer
/// * Windows: IDC_HAND
/// * Windows UWP: CoreCursorType::Hand
/// * Linux: pointer
/// * macOS: pointingHandCursor
static const SystemMouseCursor click = SystemMouseCursor._(kind: 'click');
/// A cursor indicating an operation that will not be carried out.
///
/// Typically the shape of a circle with a diagonal line. May fall back to
/// [noDrop].
///
/// Corresponds to:
///
/// * Android: TYPE_NO_DROP
/// * Web: not-allowed
/// * Windows: IDC_NO
/// * Windows UWP: CoreCursorType::UniversalNo
/// * Linux: not-allowed
/// * macOS: operationNotAllowedCursor
///
/// See also:
///
/// * [noDrop], which indicates somewhere that the current item may not be
/// dropped.
static const SystemMouseCursor forbidden = SystemMouseCursor._(kind: 'forbidden');
/// A cursor indicating the status that the program is busy and therefore
/// can not be interacted with.
///
/// Typically the shape of an hourglass or a watch.
///
/// This cursor is not available as a system cursor on macOS. Although macOS
/// displays a "spinning ball" cursor when busy, it's handled by the OS and not
/// exposed for applications to choose.
///
/// Corresponds to:
///
/// * Android: TYPE_WAIT
/// * Windows: IDC_WAIT
/// * Web: wait
/// * Linux: wait
///
/// See also:
///
/// * [progress], which is similar to [wait] but the program can still be
/// interacted with.
static const SystemMouseCursor wait = SystemMouseCursor._(kind: 'wait');
/// A cursor indicating the status that the program is busy but can still be
/// interacted with.
///
/// Typically the shape of an arrow with an hourglass or a watch at the corner.
/// Does *not* fall back to [wait] if unavailable.
///
/// Corresponds to:
///
/// * Web: progress
/// * Windows: IDC_APPSTARTING
/// * Linux: progress
///
/// See also:
///
/// * [wait], which is similar to [progress] but the program can not be
/// interacted with.
static const SystemMouseCursor progress = SystemMouseCursor._(kind: 'progress');
/// A cursor indicating somewhere the user can trigger a context menu.
///
/// Typically the shape of an arrow with a small menu at the corner.
///
/// Corresponds to:
///
/// * Android: TYPE_CONTEXT_MENU
/// * Web: context-menu
/// * Linux: context-menu
/// * macOS: contextualMenuCursor
static const SystemMouseCursor contextMenu = SystemMouseCursor._(kind: 'contextMenu');
/// A cursor indicating help information.
///
/// Typically the shape of a question mark, or an arrow therewith.
///
/// Corresponds to:
///
/// * Android: TYPE_HELP
/// * Windows: IDC_HELP
/// * Windows UWP: CoreCursorType::Help
/// * Web: help
/// * Linux: help
static const SystemMouseCursor help = SystemMouseCursor._(kind: 'help');
// SELECTION
/// A cursor indicating selectable text.
///
/// Typically the shape of a capital I.
///
/// Corresponds to:
///
/// * Android: TYPE_TEXT
/// * Web: text
/// * Windows: IDC_IBEAM
/// * Windows UWP: CoreCursorType::IBeam
/// * Linux: text
/// * macOS: IBeamCursor
static const SystemMouseCursor text = SystemMouseCursor._(kind: 'text');
/// A cursor indicating selectable vertical text.
///
/// Typically the shape of a capital I rotated to be horizontal. May fall back
/// to [text].
///
/// Corresponds to:
///
/// * Android: TYPE_VERTICAL_TEXT
/// * Web: vertical-text
/// * Linux: vertical-text
/// * macOS: IBeamCursorForVerticalLayout
static const SystemMouseCursor verticalText = SystemMouseCursor._(kind: 'verticalText');
/// A cursor indicating selectable table cells.
///
/// Typically the shape of a hollow plus sign.
///
/// Corresponds to:
///
/// * Android: TYPE_CELL
/// * Web: cell
/// * Linux: cell
static const SystemMouseCursor cell = SystemMouseCursor._(kind: 'cell');
/// A cursor indicating precise selection, such as selecting a pixel in a
/// bitmap.
///
/// Typically the shape of a crosshair.
///
/// Corresponds to:
///
/// * Android: TYPE_CROSSHAIR
/// * Web: crosshair
/// * Windows: IDC_CROSS
/// * Windows UWP: CoreCursorType::Cross
/// * Linux: crosshair
/// * macOS: crosshairCursor
static const SystemMouseCursor precise = SystemMouseCursor._(kind: 'precise');
// DRAG-AND-DROP
/// A cursor indicating moving something.
///
/// Typically the shape of four-way arrow. May fall back to [allScroll].
///
/// Corresponds to:
///
/// * Android: TYPE_ALL_SCROLL
/// * Windows: IDC_SIZEALL
/// * Windows UWP: CoreCursorType::SizeAll
/// * Web: move
/// * Linux: move
static const SystemMouseCursor move = SystemMouseCursor._(kind: 'move');
/// A cursor indicating something that can be dragged.
///
/// Typically the shape of an open hand.
///
/// Corresponds to:
///
/// * Android: TYPE_GRAB
/// * Web: grab
/// * Linux: grab
/// * macOS: openHandCursor
static const SystemMouseCursor grab = SystemMouseCursor._(kind: 'grab');
/// A cursor indicating something that is being dragged.
///
/// Typically the shape of a closed hand.
///
/// Corresponds to:
///
/// * Android: TYPE_GRABBING
/// * Web: grabbing
/// * Linux: grabbing
/// * macOS: closedHandCursor
static const SystemMouseCursor grabbing = SystemMouseCursor._(kind: 'grabbing');
/// A cursor indicating somewhere that the current item may not be dropped.
///
/// Typically the shape of a hand with a [forbidden] sign at the corner. May
/// fall back to [forbidden].
///
/// Corresponds to:
///
/// * Android: TYPE_NO_DROP
/// * Web: no-drop
/// * Windows: IDC_NO
/// * Windows UWP: CoreCursorType::UniversalNo
/// * Linux: no-drop
/// * macOS: operationNotAllowedCursor
///
/// See also:
///
/// * [forbidden], which indicates an action that will not be carried out.
static const SystemMouseCursor noDrop = SystemMouseCursor._(kind: 'noDrop');
/// A cursor indicating that the current operation will create an alias of, or
/// a shortcut of the item.
///
/// Typically the shape of an arrow with a shortcut icon at the corner.
///
/// Corresponds to:
///
/// * Android: TYPE_ALIAS
/// * Web: alias
/// * Linux: alias
/// * macOS: dragLinkCursor
static const SystemMouseCursor alias = SystemMouseCursor._(kind: 'alias');
/// A cursor indicating that the current operation will copy the item.
///
/// Typically the shape of an arrow with a boxed plus sign at the corner.
///
/// Corresponds to:
///
/// * Android: TYPE_COPY
/// * Web: copy
/// * Linux: copy
/// * macOS: dragCopyCursor
static const SystemMouseCursor copy = SystemMouseCursor._(kind: 'copy');
/// A cursor indicating that the current operation will result in the
/// disappearance of the item.
///
/// Typically the shape of an arrow with a cloud of smoke at the corner.
///
/// Corresponds to:
///
/// * macOS: disappearingItemCursor
static const SystemMouseCursor disappearing = SystemMouseCursor._(kind: 'disappearing');
// RESIZING AND SCROLLING
/// A cursor indicating scrolling in any direction.
///
/// Typically the shape of a dot surrounded by 4 arrows.
///
/// Corresponds to:
///
/// * Android: TYPE_ALL_SCROLL
/// * Windows: IDC_SIZEALL
/// * Windows UWP: CoreCursorType::SizeAll
/// * Web: all-scroll
/// * Linux: all-scroll
///
/// See also:
///
/// * [move], which indicates moving in any direction.
static const SystemMouseCursor allScroll = SystemMouseCursor._(kind: 'allScroll');
/// A cursor indicating resizing an object bidirectionally from its left or
/// right edge.
///
/// Typically the shape of a bidirectional arrow pointing left and right.
///
/// Corresponds to:
///
/// * Android: TYPE_HORIZONTAL_DOUBLE_ARROW
/// * Web: ew-resize
/// * Windows: IDC_SIZEWE
/// * Windows UWP: CoreCursorType::SizeWestEast
/// * Linux: ew-resize
/// * macOS: resizeLeftRightCursor
static const SystemMouseCursor resizeLeftRight = SystemMouseCursor._(kind: 'resizeLeftRight');
/// A cursor indicating resizing an object bidirectionally from its top or
/// bottom edge.
///
/// Typically the shape of a bidirectional arrow pointing up and down.
///
/// Corresponds to:
///
/// * Android: TYPE_VERTICAL_DOUBLE_ARROW
/// * Web: ns-resize
/// * Windows: IDC_SIZENS
/// * Windows UWP: CoreCursorType::SizeNorthSouth
/// * Linux: ns-resize
/// * macOS: resizeUpDownCursor
static const SystemMouseCursor resizeUpDown = SystemMouseCursor._(kind: 'resizeUpDown');
/// A cursor indicating resizing an object bidirectionally from its top left or
/// bottom right corner.
///
/// Typically the shape of a bidirectional arrow pointing upper left and lower right.
///
/// Corresponds to:
///
/// * Android: TYPE_TOP_LEFT_DIAGONAL_DOUBLE_ARROW
/// * Web: nwse-resize
/// * Windows: IDC_SIZENWSE
/// * Windows UWP: CoreCursorType::SizeNorthwestSoutheast
/// * Linux: nwse-resize
static const SystemMouseCursor resizeUpLeftDownRight = SystemMouseCursor._(kind: 'resizeUpLeftDownRight');
/// A cursor indicating resizing an object bidirectionally from its top right or
/// bottom left corner.
///
/// Typically the shape of a bidirectional arrow pointing upper right and lower left.
///
/// Corresponds to:
///
/// * Android: TYPE_TOP_RIGHT_DIAGONAL_DOUBLE_ARROW
/// * Windows: IDC_SIZENESW
/// * Windows UWP: CoreCursorType::SizeNortheastSouthwest
/// * Web: nesw-resize
/// * Linux: nesw-resize
static const SystemMouseCursor resizeUpRightDownLeft = SystemMouseCursor._(kind: 'resizeUpRightDownLeft');
/// A cursor indicating resizing an object from its top edge.
///
/// Typically the shape of an arrow pointing up. May fallback to [resizeUpDown].
///
/// Corresponds to:
///
/// * Android: TYPE_VERTICAL_DOUBLE_ARROW
/// * Web: n-resize
/// * Windows: IDC_SIZENS
/// * Windows UWP: CoreCursorType::SizeNorthSouth
/// * Linux: n-resize
/// * macOS: resizeUpCursor
static const SystemMouseCursor resizeUp = SystemMouseCursor._(kind: 'resizeUp');
/// A cursor indicating resizing an object from its bottom edge.
///
/// Typically the shape of an arrow pointing down. May fallback to [resizeUpDown].
///
/// Corresponds to:
///
/// * Android: TYPE_VERTICAL_DOUBLE_ARROW
/// * Web: s-resize
/// * Windows: IDC_SIZENS
/// * Windows UWP: CoreCursorType::SizeNorthSouth
/// * Linux: s-resize
/// * macOS: resizeDownCursor
static const SystemMouseCursor resizeDown = SystemMouseCursor._(kind: 'resizeDown');
/// A cursor indicating resizing an object from its left edge.
///
/// Typically the shape of an arrow pointing left. May fallback to [resizeLeftRight].
///
/// Corresponds to:
///
/// * Android: TYPE_HORIZONTAL_DOUBLE_ARROW
/// * Web: w-resize
/// * Windows: IDC_SIZEWE
/// * Windows UWP: CoreCursorType::SizeWestEast
/// * Linux: w-resize
/// * macOS: resizeLeftCursor
static const SystemMouseCursor resizeLeft = SystemMouseCursor._(kind: 'resizeLeft');
/// A cursor indicating resizing an object from its right edge.
///
/// Typically the shape of an arrow pointing right. May fallback to [resizeLeftRight].
///
/// Corresponds to:
///
/// * Android: TYPE_HORIZONTAL_DOUBLE_ARROW
/// * Web: e-resize
/// * Windows: IDC_SIZEWE
/// * Windows UWP: CoreCursorType::SizeWestEast
/// * Linux: e-resize
/// * macOS: resizeRightCursor
static const SystemMouseCursor resizeRight = SystemMouseCursor._(kind: 'resizeRight');
/// A cursor indicating resizing an object from its top-left corner.
///
/// Typically the shape of an arrow pointing upper left. May fallback to [resizeUpLeftDownRight].
///
/// Corresponds to:
///
/// * Android: TYPE_TOP_LEFT_DIAGONAL_DOUBLE_ARROW
/// * Web: nw-resize
/// * Windows: IDC_SIZENWSE
/// * Windows UWP: CoreCursorType::SizeNorthwestSoutheast
/// * Linux: nw-resize
static const SystemMouseCursor resizeUpLeft = SystemMouseCursor._(kind: 'resizeUpLeft');
/// A cursor indicating resizing an object from its top-right corner.
///
/// Typically the shape of an arrow pointing upper right. May fallback to [resizeUpRightDownLeft].
///
/// Corresponds to:
///
/// * Android: TYPE_TOP_RIGHT_DIAGONAL_DOUBLE_ARROW
/// * Web: ne-resize
/// * Windows: IDC_SIZENESW
/// * Windows UWP: CoreCursorType::SizeNortheastSouthwest
/// * Linux: ne-resize
static const SystemMouseCursor resizeUpRight = SystemMouseCursor._(kind: 'resizeUpRight');
/// A cursor indicating resizing an object from its bottom-left corner.
///
/// Typically the shape of an arrow pointing lower left. May fallback to [resizeUpRightDownLeft].
///
/// Corresponds to:
///
/// * Android: TYPE_TOP_RIGHT_DIAGONAL_DOUBLE_ARROW
/// * Web: sw-resize
/// * Windows: IDC_SIZENESW
/// * Windows UWP: CoreCursorType::SizeNortheastSouthwest
/// * Linux: sw-resize
static const SystemMouseCursor resizeDownLeft = SystemMouseCursor._(kind: 'resizeDownLeft');
/// A cursor indicating resizing an object from its bottom-right corner.
///
/// Typically the shape of an arrow pointing lower right. May fallback to [resizeUpLeftDownRight].
///
/// Corresponds to:
///
/// * Android: TYPE_TOP_LEFT_DIAGONAL_DOUBLE_ARROW
/// * Web: se-resize
/// * Windows: IDC_SIZENWSE
/// * Windows UWP: CoreCursorType::SizeNorthwestSoutheast
/// * Linux: se-resize
static const SystemMouseCursor resizeDownRight = SystemMouseCursor._(kind: 'resizeDownRight');
/// A cursor indicating resizing a column, or an item horizontally.
///
/// Typically the shape of arrows pointing left and right with a vertical bar
/// separating them. May fallback to [resizeLeftRight].
///
/// Corresponds to:
///
/// * Android: TYPE_HORIZONTAL_DOUBLE_ARROW
/// * Web: col-resize
/// * Windows: IDC_SIZEWE
/// * Windows UWP: CoreCursorType::SizeWestEast
/// * Linux: col-resize
/// * macOS: resizeLeftRightCursor
static const SystemMouseCursor resizeColumn = SystemMouseCursor._(kind: 'resizeColumn');
/// A cursor indicating resizing a row, or an item vertically.
///
/// Typically the shape of arrows pointing up and down with a horizontal bar
/// separating them. May fallback to [resizeUpDown].
///
/// Corresponds to:
///
/// * Android: TYPE_VERTICAL_DOUBLE_ARROW
/// * Web: row-resize
/// * Windows: IDC_SIZENS
/// * Windows UWP: CoreCursorType::SizeNorthSouth
/// * Linux: row-resize
/// * macOS: resizeUpDownCursor
static const SystemMouseCursor resizeRow = SystemMouseCursor._(kind: 'resizeRow');
// OTHER OPERATIONS
/// A cursor indicating zooming in.
///
/// Typically a magnifying glass with a plus sign.
///
/// Corresponds to:
///
/// * Android: TYPE_ZOOM_IN
/// * Web: zoom-in
/// * Linux: zoom-in
static const SystemMouseCursor zoomIn = SystemMouseCursor._(kind: 'zoomIn');
/// A cursor indicating zooming out.
///
/// Typically a magnifying glass with a minus sign.
///
/// Corresponds to:
///
/// * Android: TYPE_ZOOM_OUT
/// * Web: zoom-out
/// * Linux: zoom-out
static const SystemMouseCursor zoomOut = SystemMouseCursor._(kind: 'zoomOut');
}
| flutter/packages/flutter/lib/src/services/mouse_cursor.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/services/mouse_cursor.dart",
"repo_id": "flutter",
"token_count": 9556
} | 815 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'message_codecs.dart';
import 'platform_channel.dart';
export 'platform_channel.dart' show BasicMessageChannel, MethodChannel;
/// Platform channels used by the Flutter system.
abstract final class SystemChannels {
/// A JSON [MethodChannel] for navigation.
///
/// The following incoming methods are defined for this channel (registered
/// using [MethodChannel.setMethodCallHandler]):
///
/// * `popRoute`, which is called when the system wants the current route to
/// be removed (e.g. if the user hits a system-level back button).
///
/// * `pushRoute`, which is called with a single string argument when the
/// operating system instructs the application to open a particular page.
///
/// * `pushRouteInformation`, which is called with a map, which contains a
/// location string and a state object, when the operating system instructs
/// the application to open a particular page. These parameters are stored
/// under the key `location` and `state` in the map.
///
/// The following methods are used for the opposite direction data flow. The
/// framework notifies the engine about the route changes.
///
/// * `selectSingleEntryHistory`, which enables a single-entry history mode.
///
/// * `selectMultiEntryHistory`, which enables a multiple-entry history mode.
///
/// * `routeInformationUpdated`, which is called when the application
/// navigates to a new location, and which takes two arguments, `location`
/// (a URL) and `state` (an object).
///
/// * `routeUpdated`, a deprecated API which can be called in the same
/// situations as `routeInformationUpdated` but whose arguments are
/// `routeName` (a URL) and `previousRouteName` (which is ignored).
///
/// These APIs are exposed by the [SystemNavigator] class.
///
/// See also:
///
/// * [WidgetsBindingObserver.didPopRoute] and
/// [WidgetsBindingObserver.didPushRoute], which expose this channel's
/// methods.
/// * [Navigator] which manages transitions from one page to another.
/// [Navigator.push], [Navigator.pushReplacement], [Navigator.pop] and
/// [Navigator.replace], utilize this channel's methods to send route
/// change information from framework to engine.
static const MethodChannel navigation = OptionalMethodChannel(
'flutter/navigation',
JSONMethodCodec(),
);
/// A JSON [MethodChannel] for invoking miscellaneous platform methods.
///
/// The following outgoing methods are defined for this channel (invoked using
/// [OptionalMethodChannel.invokeMethod]):
///
/// * `Clipboard.setData`: Places the data from the `text` entry of the
/// argument, which must be a [Map], onto the system clipboard. See
/// [Clipboard.setData].
///
/// * `Clipboard.getData`: Returns the data that has the format specified in
/// the argument, a [String], from the system clipboard. The only format
/// currently supported is `text/plain` ([Clipboard.kTextPlain]). The
/// result is a [Map] with a single key, `text`. See [Clipboard.getData].
///
/// * `HapticFeedback.vibrate`: Triggers a system-default haptic response.
/// See [HapticFeedback.vibrate].
///
/// * `SystemSound.play`: Triggers a system audio effect. The argument must
/// be a [String] describing the desired effect; currently only `click` is
/// supported. See [SystemSound.play].
///
/// * `SystemChrome.setPreferredOrientations`: Informs the operating system
/// of the desired orientation of the display. The argument is a [List] of
/// values which are string representations of values of the
/// [DeviceOrientation] enum. See [SystemChrome.setPreferredOrientations].
///
/// * `SystemChrome.setApplicationSwitcherDescription`: Informs the operating
/// system of the desired label and color to be used to describe the
/// application in any system-level application lists (e.g. application
/// switchers). The argument is a [Map] with two keys, `label` giving a
/// [String] description, and `primaryColor` giving a 32 bit integer value
/// (the lower eight bits being the blue channel, the next eight bits being
/// the green channel, the next eight bits being the red channel, and the
/// high eight bits being set, as from [Color.value] for an opaque color).
/// The `primaryColor` can also be zero to indicate that the system default
/// should be used. See [SystemChrome.setApplicationSwitcherDescription].
///
/// * `SystemChrome.setEnabledSystemUIOverlays`: Specifies the set of system
/// overlays to have visible when the application is running. The argument
/// is a [List] of values which are string representations of values of the
/// [SystemUiOverlay] enum. See [SystemChrome.setEnabledSystemUIMode].
/// [SystemUiOverlay]s can only be configured individually when using
/// [SystemUiMode.manual].
///
/// * `SystemChrome.setEnabledSystemUIMode`: Specifies the [SystemUiMode] for
/// the application. The optional `overlays` argument is a [List] of values
/// which are string representations of values of the [SystemUiOverlay]
/// enum when using [SystemUiMode.manual]. See
/// [SystemChrome.setEnabledSystemUIMode].
///
/// * `SystemChrome.setSystemUIOverlayStyle`: Specifies whether system
/// overlays (e.g. the status bar on Android or iOS) should be `light` or
/// `dark`. The argument is one of those two strings. See
/// [SystemChrome.setSystemUIOverlayStyle].
///
/// * `SystemNavigator.pop`: Tells the operating system to close the
/// application, or the closest equivalent. See [SystemNavigator.pop].
///
/// * `System.exitApplication`: Tells the engine to send a request back to
/// the application to request an application exit (using
/// `System.requestAppExit` below), and if it is not canceled, to terminate
/// the application using the platform UI toolkit's termination API.
///
/// The following incoming methods are defined for this channel (registered
/// using [MethodChannel.setMethodCallHandler]):
///
/// * `SystemChrome.systemUIChange`: The user has changed the visibility of
/// the system overlays. This is relevant when using [SystemUiMode]s
/// through [SystemChrome.setEnabledSystemUIMode]. See
/// [SystemChrome.setSystemUIChangeCallback] to respond to this change in
/// application state.
///
/// * `System.requestAppExit`: The application has requested that it be
/// terminated. See [ServicesBinding.exitApplication].
///
/// * `System.initializationComplete`: Indicate to the engine the
/// initialization of a binding that may, among other tasks, register a
/// handler for application exit attempts.
///
/// Calls to methods that are not implemented on the shell side are ignored
/// (so it is safe to call methods when the relevant plugin might be missing).
static const MethodChannel platform = OptionalMethodChannel(
'flutter/platform',
JSONMethodCodec(),
);
/// A [MethodChannel] for handling text processing actions.
///
/// This channel exposes the text processing feature for supported platforms.
/// Currently supported on Android only.
static const MethodChannel processText = OptionalMethodChannel(
'flutter/processtext',
);
/// A JSON [MethodChannel] for handling text input.
///
/// This channel exposes a system text input control for interacting with IMEs
/// (input method editors, for example on-screen keyboards). There is one
/// control, and at any time it can have one active transaction. Transactions
/// are represented by an integer. New Transactions are started by
/// `TextInput.setClient`. Messages that are sent are assumed to be for the
/// current transaction (the last "client" set by `TextInput.setClient`).
/// Messages received from the shell side specify the transaction to which
/// they apply, so that stale messages referencing past transactions can be
/// ignored.
///
/// In debug builds, messages sent with a client ID of -1 are always accepted.
/// This allows tests to smuggle messages without having to mock the engine's
/// text handling (for example, allowing the engine to still handle the text
/// input messages in an integration test).
///
/// The methods described below are wrapped in a more convenient form by the
/// [TextInput] and [TextInputConnection] class.
///
/// The following outgoing methods are defined for this channel (invoked using
/// [OptionalMethodChannel.invokeMethod]):
///
/// * `TextInput.setClient`: Establishes a new transaction. The arguments is
/// a [List] whose first value is an integer representing a previously
/// unused transaction identifier, and the second is a [String] with a
/// JSON-encoded object with five keys, as obtained from
/// [TextInputConfiguration.toJson]. This method must be invoked before any
/// others (except `TextInput.hide`). See [TextInput.attach].
///
/// * `TextInput.show`: Show the keyboard. See [TextInputConnection.show].
///
/// * `TextInput.setEditingState`: Update the value in the text editing
/// control. The argument is a [String] with a JSON-encoded object with
/// seven keys, as obtained from [TextEditingValue.toJSON]. See
/// [TextInputConnection.setEditingState].
///
/// * `TextInput.clearClient`: End the current transaction. The next method
/// called must be `TextInput.setClient` (or `TextInput.hide`). See
/// [TextInputConnection.close].
///
/// * `TextInput.hide`: Hide the keyboard. Unlike the other methods, this can
/// be called at any time. See [TextInputConnection.close].
///
/// The following incoming methods are defined for this channel (registered
/// using [MethodChannel.setMethodCallHandler]). In each case, the first argument
/// is a transaction identifier. Calls for stale transactions should be ignored.
///
/// * `TextInputClient.updateEditingState`: The user has changed the contents
/// of the text control. The second argument is an object with seven keys,
/// in the form expected by [TextEditingValue.fromJSON].
///
/// * `TextInputClient.updateEditingStateWithTag`: One or more text controls
/// were autofilled by the platform's autofill service. The first argument
/// (the client ID) is ignored, the second argument is a map of tags to
/// objects in the form expected by [TextEditingValue.fromJSON]. See
/// [AutofillScope.getAutofillClient] for details on the interpretation of
/// the tag.
///
/// * `TextInputClient.performAction`: The user has triggered an action. The
/// second argument is a [String] consisting of the stringification of one
/// of the values of the [TextInputAction] enum.
///
/// * `TextInputClient.requestExistingInputState`: The embedding may have
/// lost its internal state about the current editing client, if there is
/// one. The framework should call `TextInput.setClient` and
/// `TextInput.setEditingState` again with its most recent information. If
/// there is no existing state on the framework side, the call should
/// fizzle. (This call is made without a client ID; indeed, without any
/// arguments at all.)
///
/// * `TextInputClient.onConnectionClosed`: The text input connection closed
/// on the platform side. For example the application is moved to
/// background or used closed the virtual keyboard. This method informs
/// [TextInputClient] to clear connection and finalize editing.
/// `TextInput.clearClient` and `TextInput.hide` is not called after
/// clearing the connection since on the platform side the connection is
/// already finalized.
///
/// Calls to methods that are not implemented on the shell side are ignored
/// (so it is safe to call methods when the relevant plugin might be missing).
static const MethodChannel textInput = OptionalMethodChannel(
'flutter/textinput',
JSONMethodCodec(),
);
/// A [MethodChannel] for handling spell check for text input.
///
/// This channel exposes the spell check framework for supported platforms.
/// Currently supported on Android and iOS only.
///
/// Spell check requests are initiated by `SpellCheck.initiateSpellCheck`.
/// These requests may either be completed or canceled. If the request is
/// completed, the shell side will respond with the results of the request.
/// Otherwise, the shell side will respond with null.
///
/// The following outgoing methods are defined for this channel (invoked by
/// [OptionalMethodChannel.invokeMethod]):
///
/// * `SpellCheck.initiateSpellCheck`: Sends request for specified text to be
/// spell checked and returns the result, either a [List<SuggestionSpan>]
/// representing the spell check results of the text or null if the request
/// was canceled. The arguments are the [String] to be spell checked
/// and the [Locale] for the text to be spell checked with.
static const MethodChannel spellCheck = OptionalMethodChannel(
'flutter/spellcheck',
);
/// A JSON [MethodChannel] for handling undo events.
static const MethodChannel undoManager = OptionalMethodChannel(
'flutter/undomanager',
JSONMethodCodec(),
);
/// A JSON [BasicMessageChannel] for keyboard events.
///
/// Each incoming message received on this channel (registered using
/// [BasicMessageChannel.setMessageHandler]) consists of a [Map] with
/// platform-specific data, plus a `type` field which is either `keydown`, or
/// `keyup`.
///
/// On Android, the available fields are those described by
/// [RawKeyEventDataAndroid]'s properties.
///
/// On Fuchsia, the available fields are those described by
/// [RawKeyEventDataFuchsia]'s properties.
///
/// No messages are sent on other platforms currently.
///
/// See also:
///
/// * [RawKeyboard], which uses this channel to expose key data.
/// * [RawKeyEvent.fromMessage], which can decode this data into the [RawKeyEvent]
/// subclasses mentioned above.
static const BasicMessageChannel<Object?> keyEvent = BasicMessageChannel<Object?>(
'flutter/keyevent',
JSONMessageCodec(),
);
/// A string [BasicMessageChannel] for lifecycle events.
///
/// Valid messages are string representations of the values of the
/// [AppLifecycleState] enumeration. A handler can be registered using
/// [BasicMessageChannel.setMessageHandler].
///
/// See also:
///
/// * [WidgetsBindingObserver.didChangeAppLifecycleState], which triggers
/// whenever a message is received on this channel.
static const BasicMessageChannel<String?> lifecycle = BasicMessageChannel<String?>(
'flutter/lifecycle',
StringCodec(),
);
/// A JSON [BasicMessageChannel] for system events.
///
/// Events are exposed as [Map]s with string keys. The `type` key specifies
/// the type of the event; the currently supported system event types are
/// those listed below. A handler can be registered using
/// [BasicMessageChannel.setMessageHandler].
///
/// * `memoryPressure`: Indicates that the operating system would like
/// applications to release caches to free up more memory. See
/// [WidgetsBindingObserver.didHaveMemoryPressure], which triggers whenever
/// a message is received on this channel.
static const BasicMessageChannel<Object?> system = BasicMessageChannel<Object?>(
'flutter/system',
JSONMessageCodec(),
);
/// A [BasicMessageChannel] for accessibility events.
///
/// See also:
///
/// * [SemanticsEvent] and its subclasses for a list of valid accessibility
/// events that can be sent over this channel.
/// * [SemanticsNode.sendEvent], which uses this channel to dispatch events.
static const BasicMessageChannel<Object?> accessibility = BasicMessageChannel<Object?>(
'flutter/accessibility',
StandardMessageCodec(),
);
/// A [MethodChannel] for controlling platform views.
///
/// See also:
///
/// * [PlatformViewsService] for the available operations on this channel.
static const MethodChannel platform_views = MethodChannel(
'flutter/platform_views',
);
/// A [MethodChannel] for configuring the Skia graphics library.
///
/// The following outgoing methods are defined for this channel (invoked using
/// [OptionalMethodChannel.invokeMethod]):
///
/// * `Skia.setResourceCacheMaxBytes`: Set the maximum number of bytes that
/// can be held in the GPU resource cache.
static const MethodChannel skia = MethodChannel(
'flutter/skia',
JSONMethodCodec(),
);
/// A [MethodChannel] for configuring mouse cursors.
///
/// All outgoing methods defined for this channel uses a `Map<String, Object?>`
/// to contain multiple parameters, including the following methods (invoked
/// using [OptionalMethodChannel.invokeMethod]):
///
/// * `activateSystemCursor`: Request to set the cursor of a pointer
/// device to a system cursor. The parameters are
/// integer `device`, and string `kind`.
static const MethodChannel mouseCursor = OptionalMethodChannel(
'flutter/mousecursor',
);
/// A [MethodChannel] for synchronizing restoration data with the engine.
///
/// The following outgoing methods are defined for this channel (invoked using
/// [OptionalMethodChannel.invokeMethod]):
///
/// * `get`: Retrieves the current restoration information (e.g. provided by
/// the operating system) from the engine. The method returns a map
/// containing an `enabled` boolean to indicate whether collecting
/// restoration data is supported by the embedder. If `enabled` is true,
/// the map may also contain restoration data stored under the `data` key
/// from which the state of the framework may be restored. The restoration
/// data is encoded as [Uint8List].
/// * `put`: Sends the current restoration data to the engine. Takes the
/// restoration data encoded as [Uint8List] as argument.
///
/// The following incoming methods are defined for this channel (registered
/// using [MethodChannel.setMethodCallHandler]).
///
/// * `push`: Called by the engine to send newly provided restoration
/// information to the framework. The argument given to this method has
/// the same format as the object that the `get` method returns.
///
/// See also:
///
/// * [RestorationManager], which uses this channel and also describes how
/// restoration data is used in Flutter.
static const MethodChannel restoration = OptionalMethodChannel(
'flutter/restoration',
);
/// A [MethodChannel] for installing and managing deferred components.
///
/// The following outgoing methods are defined for this channel (invoked using
/// [OptionalMethodChannel.invokeMethod]):
///
/// * `installDeferredComponent`: Requests that a deferred component identified by
/// the provided loadingUnitId or componentName be downloaded and installed.
/// Providing a loadingUnitId with null componentName will install a component that
/// includes the desired loading unit. If a componentName is provided, then the
/// deferred component with the componentName will be installed. This method
/// returns a future that will not be completed until the feature is fully installed
/// and ready to use. When an error occurs, the future will complete an error.
/// Calling `loadLibrary()` on a deferred imported library is equivalent to calling
/// this method with a loadingUnitId and null componentName.
/// * `uninstallDeferredComponent`: Requests that a deferred component identified by
/// the provided loadingUnitId or componentName be uninstalled. Since
/// uninstallation typically requires significant disk i/o, this method only
/// signals the intent to uninstall. Actual uninstallation (eg, removal of
/// assets and files) may occur at a later time. However, once uninstallation
/// is requested, the deferred component should not be used anymore until
/// `installDeferredComponent` or `loadLibrary` is called again.
static const MethodChannel deferredComponent = OptionalMethodChannel(
'flutter/deferredcomponent',
);
/// A JSON [MethodChannel] for localization.
///
/// The following outgoing methods are defined for this channel (invoked using
/// [OptionalMethodChannel.invokeMethod]):
///
/// * `Localization.getStringResource`: Obtains the native string resource
/// for a specific locale. The argument is a [Map] with two keys, `key`
/// giving a [String] which the resource is defined with, and an optional
/// `locale` which is a [String] containing the BCP47 locale identifier of
/// the locale requested. See [Locale.toLanguageTag]. When `locale` is not
/// specified, the current system locale is used instead.
static const MethodChannel localization = OptionalMethodChannel(
'flutter/localization',
JSONMethodCodec(),
);
/// A [MethodChannel] for platform menu specification and control.
///
/// The following outgoing method is defined for this channel (invoked using
/// [OptionalMethodChannel.invokeMethod]):
///
/// * `Menu.setMenus`: sends the configuration of the platform menu, including
/// labels, enable/disable information, and unique integer identifiers for
/// each menu item. The configuration is sent as a `Map<String, Object?>`
/// encoding the list of top level menu items in window "0", which each
/// have a hierarchy of `Map<String, Object?>` containing the required
/// data, sent via a [StandardMessageCodec]. It is typically generated from
/// a list of [PlatformMenuItem]s, and ends up looking like this example:
///
/// ```dart
/// Map<String, Object?> menu = <String, Object?>{
/// '0': <Map<String, Object?>>[
/// <String, Object?>{
/// 'id': 1,
/// 'label': 'First Menu Label',
/// 'enabled': true,
/// 'children': <Map<String, Object?>>[
/// <String, Object?>{
/// 'id': 2,
/// 'label': 'Sub Menu Label',
/// 'enabled': true,
/// },
/// ],
/// },
/// ],
/// };
/// ```
///
/// The following incoming methods are defined for this channel (registered
/// using [MethodChannel.setMethodCallHandler]).
///
/// * `Menu.selectedCallback`: Called when a menu item is selected, along
/// with the unique ID of the menu item selected.
///
/// * `Menu.opened`: Called when a submenu is opened, along with the unique
/// ID of the submenu.
///
/// * `Menu.closed`: Called when a submenu is closed, along with the unique
/// ID of the submenu.
///
/// See also:
///
/// * [DefaultPlatformMenuDelegate], which uses this channel.
static const MethodChannel menu = OptionalMethodChannel('flutter/menu');
/// A [MethodChannel] for configuring the browser's context menu on web.
///
/// The following outgoing methods are defined for this channel (invoked using
/// [OptionalMethodChannel.invokeMethod]):
///
/// * `enableContextMenu`: enables the browser's context menu. When a Flutter
/// app starts, the browser's context menu is already enabled.
/// * `disableContextMenu`: disables the browser's context menu.
static const MethodChannel contextMenu = OptionalMethodChannel(
'flutter/contextmenu',
JSONMethodCodec(),
);
/// A [MethodChannel] for retrieving keyboard pressed keys from the engine.
///
/// The following outgoing methods are defined for this channel (invoked using
/// [OptionalMethodChannel.invokeMethod]):
///
/// * `getKeyboardState`: Obtains keyboard pressed keys from the engine.
/// The keyboard state is sent as a `Map<int, int>?` where each entry
/// represents a pressed keyboard key. The entry key is the physical
/// key ID and the entry value is the logical key ID.
///
/// Both the framework and the engine maintain a state of the current
/// pressed keys. There are edge cases, related to startup and restart,
/// where the framework needs to resynchronize its keyboard state.
///
/// See also:
///
/// * [HardwareKeyboard.syncKeyboardState], which uses this channel to synchronize
/// the `HardwareKeyboard` pressed state.
static const MethodChannel keyboard = OptionalMethodChannel(
'flutter/keyboard',
);
}
| flutter/packages/flutter/lib/src/services/system_channels.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/services/system_channels.dart",
"repo_id": "flutter",
"token_count": 6973
} | 816 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'basic.dart';
import 'focus_manager.dart';
import 'focus_scope.dart';
import 'framework.dart';
import 'media_query.dart';
import 'shortcuts.dart';
/// Returns the parent [BuildContext] of a given `context`.
///
/// [BuildContext] (or rather, [Element]) doesn't have a `parent` accessor, but
/// the parent can be obtained using [BuildContext.visitAncestorElements].
///
/// [BuildContext.getElementForInheritedWidgetOfExactType] returns the same
/// [BuildContext] if it happens to be of the correct type. To obtain the
/// previous inherited widget, the search must therefore start from the parent;
/// this is what [_getParent] is used for.
///
/// [_getParent] is O(1), because it always stops at the first ancestor.
BuildContext _getParent(BuildContext context) {
late final BuildContext parent;
context.visitAncestorElements((Element ancestor) {
parent = ancestor;
return false;
});
return parent;
}
/// An abstract class representing a particular configuration of an [Action].
///
/// This class is what the [Shortcuts.shortcuts] map has as values, and is used
/// by an [ActionDispatcher] to look up an action and invoke it, giving it this
/// object to extract configuration information from.
///
/// See also:
///
/// * [Shortcuts], a widget used to bind key combinations to [Intent]s.
/// * [Actions], a widget used to map [Intent]s to [Action]s.
/// * [Actions.invoke], which invokes the action associated with a specified
/// [Intent] using the [Actions] widget that most tightly encloses the given
/// [BuildContext].
@immutable
abstract class Intent with Diagnosticable {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const Intent();
/// An intent that is mapped to a [DoNothingAction], which, as the name
/// implies, does nothing.
///
/// This Intent is mapped to an action in the [WidgetsApp] that does nothing,
/// so that it can be bound to a key in a [Shortcuts] widget in order to
/// disable a key binding made above it in the hierarchy.
static const DoNothingIntent doNothing = DoNothingIntent._();
}
/// The kind of callback that an [Action] uses to notify of changes to the
/// action's state.
///
/// To register an action listener, call [Action.addActionListener].
typedef ActionListenerCallback = void Function(Action<Intent> action);
/// Base class for an action or command to be performed.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=XawP1i314WM}
///
/// [Action]s are typically invoked as a result of a user action. For example,
/// the [Shortcuts] widget will map a keyboard shortcut into an [Intent], which
/// is given to an [ActionDispatcher] to map the [Intent] to an [Action] and
/// invoke it.
///
/// The [ActionDispatcher] can invoke an [Action] on the primary focus, or
/// without regard for focus.
///
/// ### Action Overriding
///
/// When using a leaf widget to build a more specialized widget, it's sometimes
/// desirable to change the default handling of an [Intent] defined in the leaf
/// widget. For instance, [TextField]'s [SelectAllTextIntent] by default selects
/// the text it currently contains, but in a US phone number widget that
/// consists of 3 different [TextField]s (area code, prefix and line number),
/// [SelectAllTextIntent] should instead select the text within all 3
/// [TextField]s.
///
/// An overridable [Action] is a special kind of [Action] created using the
/// [Action.overridable] constructor. It has access to a default [Action], and a
/// nullable override [Action]. It has the same behavior as its override if that
/// exists, and mirrors the behavior of its `defaultAction` otherwise.
///
/// The [Action.overridable] constructor creates overridable [Action]s that use
/// a [BuildContext] to find a suitable override in its ancestor [Actions]
/// widget. This can be used to provide a default implementation when creating a
/// general purpose leaf widget, and later override it when building a more
/// specialized widget using that leaf widget. Using the [TextField] example
/// above, the [TextField] widget uses an overridable [Action] to provide a
/// sensible default for [SelectAllTextIntent], while still allowing app
/// developers to change that if they add an ancestor [Actions] widget that maps
/// [SelectAllTextIntent] to a different [Action].
///
/// See the article on [Using Actions and
/// Shortcuts](https://docs.flutter.dev/development/ui/advanced/actions_and_shortcuts)
/// for a detailed explanation.
///
/// See also:
///
/// * [Shortcuts], which is a widget that contains a key map, in which it looks
/// up key combinations in order to invoke actions.
/// * [Actions], which is a widget that defines a map of [Intent] to [Action]
/// and allows redefining of actions for its descendants.
/// * [ActionDispatcher], a class that takes an [Action] and invokes it, passing
/// a given [Intent].
/// * [Action.overridable] for an example on how to make an [Action]
/// overridable.
abstract class Action<T extends Intent> with Diagnosticable {
/// Creates an [Action].
Action();
/// Creates an [Action] that allows itself to be overridden by the closest
/// ancestor [Action] in the given [context] that handles the same [Intent],
/// if one exists.
///
/// When invoked, the resulting [Action] tries to find the closest [Action] in
/// the given `context` that handles the same type of [Intent] as the
/// `defaultAction`, then calls its [Action.invoke] method. When no override
/// [Action]s can be found, it invokes the `defaultAction`.
///
/// An overridable action delegates everything to its override if one exists,
/// and has the same behavior as its `defaultAction` otherwise. For this
/// reason, the override has full control over whether and how an [Intent]
/// should be handled, or a key event should be consumed. An override
/// [Action]'s [callingAction] property will be set to the [Action] it
/// currently overrides, giving it access to the default behavior. See the
/// [callingAction] property for an example.
///
/// The `context` argument is the [BuildContext] to find the override with. It
/// is typically a [BuildContext] above the [Actions] widget that contains
/// this overridable [Action].
///
/// The `defaultAction` argument is the [Action] to be invoked where there's
/// no ancestor [Action]s can't be found in `context` that handle the same
/// type of [Intent].
///
/// This is useful for providing a set of default [Action]s in a leaf widget
/// to allow further overriding, or to allow the [Intent] to propagate to
/// parent widgets that also support this [Intent].
///
/// {@tool dartpad}
/// This sample shows how to implement a rudimentary `CopyableText` widget
/// that responds to Ctrl-C by copying its own content to the clipboard.
///
/// if `CopyableText` is to be provided in a package, developers using the
/// widget may want to change how copying is handled. As the author of the
/// package, you can enable that by making the corresponding [Action]
/// overridable. In the second part of the code sample, three `CopyableText`
/// widgets are used to build a verification code widget which overrides the
/// "copy" action by copying the combined numbers from all three `CopyableText`
/// widgets.
///
/// ** See code in examples/api/lib/widgets/actions/action.action_overridable.0.dart **
/// {@end-tool}
factory Action.overridable({
required Action<T> defaultAction,
required BuildContext context,
}) {
return defaultAction._makeOverridableAction(context);
}
final ObserverList<ActionListenerCallback> _listeners = ObserverList<ActionListenerCallback>();
Action<T>? _currentCallingAction;
// ignore: use_setters_to_change_properties, (code predates enabling of this lint)
void _updateCallingAction(Action<T>? value) {
_currentCallingAction = value;
}
/// The [Action] overridden by this [Action].
///
/// The [Action.overridable] constructor creates an overridable [Action] that
/// allows itself to be overridden by the closest ancestor [Action], and falls
/// back to its own `defaultAction` when no overrides can be found. When an
/// override is present, an overridable [Action] forwards all incoming
/// method calls to the override, and allows the override to access the
/// `defaultAction` via its [callingAction] property.
///
/// Before forwarding the call to the override, the overridable [Action] is
/// responsible for setting [callingAction] to its `defaultAction`, which is
/// already taken care of by the overridable [Action] created using
/// [Action.overridable].
///
/// This property is only non-null when this [Action] is an override of the
/// [callingAction], and is currently being invoked from [callingAction].
///
/// Invoking [callingAction]'s methods, or accessing its properties, is
/// allowed and does not introduce infinite loops or infinite recursions.
///
/// {@tool snippet}
/// An example `Action` that handles [PasteTextIntent] but has mostly the same
/// behavior as the overridable action. It's OK to call
/// `callingAction?.isActionEnabled` in the implementation of this `Action`.
///
/// ```dart
/// class MyPasteAction extends Action<PasteTextIntent> {
/// @override
/// Object? invoke(PasteTextIntent intent) {
/// print(intent);
/// return callingAction?.invoke(intent);
/// }
///
/// @override
/// bool get isActionEnabled => callingAction?.isActionEnabled ?? false;
///
/// @override
/// bool consumesKey(PasteTextIntent intent) => callingAction?.consumesKey(intent) ?? false;
/// }
/// ```
/// {@end-tool}
@protected
Action<T>? get callingAction => _currentCallingAction;
/// Gets the type of intent this action responds to.
Type get intentType => T;
/// Returns true if the action is enabled and is ready to be invoked.
///
/// This will be called by the [ActionDispatcher] before attempting to invoke
/// the action.
///
/// If the action's enable state depends on a [BuildContext], subclass
/// [ContextAction] instead of [Action].
bool isEnabled(T intent) => isActionEnabled;
bool _isEnabled(T intent, BuildContext? context) {
final Action<T> self = this;
if (self is ContextAction<T>) {
return self.isEnabled(intent, context);
}
return self.isEnabled(intent);
}
/// Whether this [Action] is inherently enabled.
///
/// If [isActionEnabled] is false, then this [Action] is disabled for any
/// given [Intent].
//
/// If the enabled state changes, overriding subclasses must call
/// [notifyActionListeners] to notify any listeners of the change.
///
/// In the case of an overridable `Action`, accessing this property creates
/// an dependency on the overridable `Action`s `lookupContext`.
bool get isActionEnabled => true;
/// Indicates whether this action should treat key events mapped to this
/// action as being "handled" when it is invoked via the key event.
///
/// If the key is handled, then no other key event handlers in the focus chain
/// will receive the event.
///
/// If the key event is not handled, it will be passed back to the engine, and
/// continue to be processed there, allowing text fields and non-Flutter
/// widgets to receive the key event.
///
/// The default implementation returns true.
bool consumesKey(T intent) => true;
/// Converts the result of [invoke] of this action to a [KeyEventResult].
///
/// This is typically used when the action is invoked in response to a keyboard
/// shortcut.
///
/// The [invokeResult] argument is the value returned by the [invoke] method.
///
/// By default, calls [consumesKey] and converts the returned boolean to
/// [KeyEventResult.handled] if it's true, and [KeyEventResult.skipRemainingHandlers]
/// if it's false.
///
/// Concrete implementations may refine the type of [invokeResult], since
/// they know the type returned by [invoke].
KeyEventResult toKeyEventResult(T intent, covariant Object? invokeResult) {
return consumesKey(intent)
? KeyEventResult.handled
: KeyEventResult.skipRemainingHandlers;
}
/// Called when the action is to be performed.
///
/// This is called by the [ActionDispatcher] when an action is invoked via
/// [Actions.invoke], or when an action is invoked using
/// [ActionDispatcher.invokeAction] directly.
///
/// This method is only meant to be invoked by an [ActionDispatcher], or by
/// its subclasses, and only when [isEnabled] is true.
///
/// When overriding this method, the returned value can be any [Object], but
/// changing the return type of the override to match the type of the returned
/// value provides more type safety.
///
/// For instance, if an override of [invoke] returned an `int`, then it might
/// be defined like so:
///
/// ```dart
/// class IncrementIntent extends Intent {
/// const IncrementIntent({required this.index});
///
/// final int index;
/// }
///
/// class MyIncrementAction extends Action<IncrementIntent> {
/// @override
/// int invoke(IncrementIntent intent) {
/// return intent.index + 1;
/// }
/// }
/// ```
///
/// To receive the result of invoking an action, it must be invoked using
/// [Actions.invoke], or by invoking it using an [ActionDispatcher]. An action
/// invoked via a [Shortcuts] widget will have its return value ignored.
///
/// If the action's behavior depends on a [BuildContext], subclass
/// [ContextAction] instead of [Action].
@protected
Object? invoke(T intent);
Object? _invoke(T intent, BuildContext? context) {
final Action<T> self = this;
if (self is ContextAction<T>) {
return self.invoke(intent, context);
}
return self.invoke(intent);
}
/// Register a callback to listen for changes to the state of this action.
///
/// If you call this, you must call [removeActionListener] a matching number
/// of times, or memory leaks will occur. To help manage this and avoid memory
/// leaks, use of the [ActionListener] widget to register and unregister your
/// listener appropriately is highly recommended.
///
/// {@template flutter.widgets.Action.addActionListener}
/// If a listener had been added twice, and is removed once during an
/// iteration (i.e. in response to a notification), it will still be called
/// again. If, on the other hand, it is removed as many times as it was
/// registered, then it will no longer be called. This odd behavior is the
/// result of the [Action] not being able to determine which listener
/// is being removed, since they are identical, and therefore conservatively
/// still calling all the listeners when it knows that any are still
/// registered.
///
/// This surprising behavior can be unexpectedly observed when registering a
/// listener on two separate objects which are both forwarding all
/// registrations to a common upstream object.
/// {@endtemplate}
@mustCallSuper
void addActionListener(ActionListenerCallback listener) => _listeners.add(listener);
/// Remove a previously registered closure from the list of closures that are
/// notified when the object changes.
///
/// If the given listener is not registered, the call is ignored.
///
/// If you call [addActionListener], you must call this method a matching
/// number of times, or memory leaks will occur. To help manage this and avoid
/// memory leaks, use of the [ActionListener] widget to register and
/// unregister your listener appropriately is highly recommended.
///
/// {@macro flutter.widgets.Action.addActionListener}
@mustCallSuper
void removeActionListener(ActionListenerCallback listener) => _listeners.remove(listener);
/// Call all the registered listeners.
///
/// Subclasses should call this method whenever the object changes, to notify
/// any clients the object may have changed. Listeners that are added during this
/// iteration will not be visited. Listeners that are removed during this
/// iteration will not be visited after they are removed.
///
/// Exceptions thrown by listeners will be caught and reported using
/// [FlutterError.reportError].
///
/// Surprising behavior can result when reentrantly removing a listener (i.e.
/// in response to a notification) that has been registered multiple times.
/// See the discussion at [removeActionListener].
@protected
@visibleForTesting
@pragma('vm:notify-debugger-on-exception')
void notifyActionListeners() {
if (_listeners.isEmpty) {
return;
}
// Make a local copy so that a listener can unregister while the list is
// being iterated over.
final List<ActionListenerCallback> localListeners = List<ActionListenerCallback>.of(_listeners);
for (final ActionListenerCallback listener in localListeners) {
InformationCollector? collector;
assert(() {
collector = () => <DiagnosticsNode>[
DiagnosticsProperty<Action<T>>(
'The $runtimeType sending notification was',
this,
style: DiagnosticsTreeStyle.errorProperty,
),
];
return true;
}());
try {
if (_listeners.contains(listener)) {
listener(this);
}
} catch (exception, stack) {
FlutterError.reportError(FlutterErrorDetails(
exception: exception,
stack: stack,
library: 'widgets library',
context: ErrorDescription('while dispatching notifications for $runtimeType'),
informationCollector: collector,
));
}
}
}
Action<T> _makeOverridableAction(BuildContext context) {
return _OverridableAction<T>(defaultAction: this, lookupContext: context);
}
}
/// A helper widget for making sure that listeners on an action are removed properly.
///
/// Listeners on the [Action] class must have their listener callbacks removed
/// with [Action.removeActionListener] when the listener is disposed of. This widget
/// helps with that, by providing a lifetime for the connection between the
/// [listener] and the [Action], and by handling the adding and removing of
/// the [listener] at the right points in the widget lifecycle.
///
/// If you listen to an [Action] widget in a widget hierarchy, you should use
/// this widget. If you are using an [Action] outside of a widget context, then
/// you must call removeListener yourself.
///
/// {@tool dartpad}
/// This example shows how ActionListener handles adding and removing of
/// the [listener] in the widget lifecycle.
///
/// ** See code in examples/api/lib/widgets/actions/action_listener.0.dart **
/// {@end-tool}
///
@immutable
class ActionListener extends StatefulWidget {
/// Create a const [ActionListener].
const ActionListener({
super.key,
required this.listener,
required this.action,
required this.child,
});
/// The [ActionListenerCallback] callback to register with the [action].
final ActionListenerCallback listener;
/// The [Action] that the callback will be registered with.
final Action<Intent> action;
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
@override
State<ActionListener> createState() => _ActionListenerState();
}
class _ActionListenerState extends State<ActionListener> {
@override
void initState() {
super.initState();
widget.action.addActionListener(widget.listener);
}
@override
void didUpdateWidget(ActionListener oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.action == widget.action && oldWidget.listener == widget.listener) {
return;
}
oldWidget.action.removeActionListener(oldWidget.listener);
widget.action.addActionListener(widget.listener);
}
@override
void dispose() {
widget.action.removeActionListener(widget.listener);
super.dispose();
}
@override
Widget build(BuildContext context) => widget.child;
}
/// An abstract [Action] subclass that adds an optional [BuildContext] to the
/// [isEnabled] and [invoke] methods to be able to provide context to actions.
///
/// [ActionDispatcher.invokeAction] checks to see if the action it is invoking
/// is a [ContextAction], and if it is, supplies it with a context.
abstract class ContextAction<T extends Intent> extends Action<T> {
/// Returns true if the action is enabled and is ready to be invoked.
///
/// This will be called by the [ActionDispatcher] before attempting to invoke
/// the action.
///
/// The optional `context` parameter is the context of the invocation of the
/// action, and in the case of an action invoked by a [ShortcutManager], via
/// a [Shortcuts] widget, will be the context of the [Shortcuts] widget.
@override
bool isEnabled(T intent, [BuildContext? context]) => super.isEnabled(intent);
/// Called when the action is to be performed.
///
/// This is called by the [ActionDispatcher] when an action is invoked via
/// [Actions.invoke], or when an action is invoked using
/// [ActionDispatcher.invokeAction] directly.
///
/// This method is only meant to be invoked by an [ActionDispatcher], or by
/// its subclasses, and only when [isEnabled] is true.
///
/// The optional `context` parameter is the context of the invocation of the
/// action, and in the case of an action invoked by a [ShortcutManager], via
/// a [Shortcuts] widget, will be the context of the [Shortcuts] widget.
///
/// When overriding this method, the returned value can be any Object, but
/// changing the return type of the override to match the type of the returned
/// value provides more type safety.
///
/// For instance, if an override of [invoke] returned an `int`, then it might
/// be defined like so:
///
/// ```dart
/// class IncrementIntent extends Intent {
/// const IncrementIntent({required this.index});
///
/// final int index;
/// }
///
/// class MyIncrementAction extends ContextAction<IncrementIntent> {
/// @override
/// int invoke(IncrementIntent intent, [BuildContext? context]) {
/// return intent.index + 1;
/// }
/// }
/// ```
@protected
@override
Object? invoke(T intent, [BuildContext? context]);
@override
ContextAction<T> _makeOverridableAction(BuildContext context) {
return _OverridableContextAction<T>(defaultAction: this, lookupContext: context);
}
}
/// The signature of a callback accepted by [CallbackAction.onInvoke].
///
/// Such callbacks are implementations of [Action.invoke]. The returned value
/// is the return value of [Action.invoke], the argument is the intent passed
/// to [Action.invoke], and so forth.
typedef OnInvokeCallback<T extends Intent> = Object? Function(T intent);
/// An [Action] that takes a callback in order to configure it without having to
/// create an explicit [Action] subclass just to call a callback.
///
/// See also:
///
/// * [Shortcuts], which is a widget that contains a key map, in which it looks
/// up key combinations in order to invoke actions.
/// * [Actions], which is a widget that defines a map of [Intent] to [Action]
/// and allows redefining of actions for its descendants.
/// * [ActionDispatcher], a class that takes an [Action] and invokes it using a
/// [FocusNode] for context.
class CallbackAction<T extends Intent> extends Action<T> {
/// A constructor for a [CallbackAction].
///
/// The given callback is used as the implementation of [invoke].
CallbackAction({required this.onInvoke});
/// The callback to be called when invoked.
///
/// This is effectively the implementation of [invoke].
@protected
final OnInvokeCallback<T> onInvoke;
@override
Object? invoke(T intent) => onInvoke(intent);
}
/// An action dispatcher that invokes the actions given to it.
///
/// The [invokeAction] method on this class directly calls the [Action.invoke]
/// method on the [Action] object.
///
/// For [ContextAction] actions, if no `context` is provided, the
/// [BuildContext] of the [primaryFocus] is used instead.
///
/// See also:
///
/// - [ShortcutManager], that uses this class to invoke actions.
/// - [Shortcuts] widget, which defines key mappings to [Intent]s.
/// - [Actions] widget, which defines a mapping between a in [Intent] type and
/// an [Action].
class ActionDispatcher with Diagnosticable {
/// Creates an action dispatcher that invokes actions directly.
const ActionDispatcher();
/// Invokes the given `action`, passing it the given `intent`.
///
/// The action will be invoked with the given `context`, if given, but only if
/// the action is a [ContextAction] subclass. If no `context` is given, and
/// the action is a [ContextAction], then the context from the [primaryFocus]
/// is used.
///
/// Returns the object returned from [Action.invoke].
///
/// The caller must receive a `true` result from [Action.isEnabled] before
/// calling this function (or [ContextAction.isEnabled] with the same
/// `context`, if the `action` is a [ContextAction]). This function will
/// assert if the action is not enabled when called.
///
/// Consider using [invokeActionIfEnabled] to invoke the action conditionally
/// based on whether it is enabled or not, without having to check first.
Object? invokeAction(
covariant Action<Intent> action,
covariant Intent intent, [
BuildContext? context,
]) {
final BuildContext? target = context ?? primaryFocus?.context;
assert(action._isEnabled(intent, target), 'Action must be enabled when calling invokeAction');
return action._invoke(intent, target);
}
/// Invokes the given `action`, passing it the given `intent`, but only if the
/// action is enabled.
///
/// The action will be invoked with the given `context`, if given, but only if
/// the action is a [ContextAction] subclass. If no `context` is given, and
/// the action is a [ContextAction], then the context from the [primaryFocus]
/// is used.
///
/// The return value has two components. The first is a boolean indicating if
/// the action was enabled (as per [Action.isEnabled]). If this is false, the
/// second return value is null. Otherwise, the second return value is the
/// object returned from [Action.invoke].
///
/// Consider using [invokeAction] if the enabled state of the action is not in
/// question; this avoids calling [Action.isEnabled] redundantly.
(bool, Object?) invokeActionIfEnabled(
covariant Action<Intent> action,
covariant Intent intent, [
BuildContext? context,
]) {
final BuildContext? target = context ?? primaryFocus?.context;
if (action._isEnabled(intent, target)) {
return (true, action._invoke(intent, target));
}
return (false, null);
}
}
/// A widget that maps [Intent]s to [Action]s to be used by its descendants
/// when invoking an [Action].
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=XawP1i314WM}
///
/// Actions are typically invoked using [Shortcuts]. They can also be invoked
/// using [Actions.invoke] on a context containing an ambient [Actions] widget.
///
/// {@tool dartpad}
/// This example creates a custom [Action] subclass `ModifyAction` for modifying
/// a model, and another, `SaveAction` for saving it.
///
/// This example demonstrates passing arguments to the [Intent] to be carried to
/// the [Action]. Actions can get data either from their own construction (like
/// the `model` in this example), or from the intent passed to them when invoked
/// (like the increment `amount` in this example).
///
/// This example also demonstrates how to use Intents to limit a widget's
/// dependencies on its surroundings. The `SaveButton` widget defined in this
/// example can invoke actions defined in its ancestor widgets, which can be
/// customized to match the part of the widget tree that it is in. It doesn't
/// need to know about the `SaveAction` class, only the `SaveIntent`, and it
/// only needs to know about a value notifier, not the entire model.
///
/// ** See code in examples/api/lib/widgets/actions/actions.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [Shortcuts], a widget used to bind key combinations to [Intent]s.
/// * [Intent], a class that contains configuration information for running an
/// [Action].
/// * [Action], a class for containing and defining an invocation of a user
/// action.
/// * [ActionDispatcher], the object that this widget uses to manage actions.
class Actions extends StatefulWidget {
/// Creates an [Actions] widget.
const Actions({
super.key,
this.dispatcher,
required this.actions,
required this.child,
});
/// The [ActionDispatcher] object that invokes actions.
///
/// This is what is returned from [Actions.of], and used by [Actions.invoke].
///
/// If this [dispatcher] is null, then [Actions.of] and [Actions.invoke] will
/// look up the tree until they find an Actions widget that has a dispatcher
/// set. If no such widget is found, then they will return/use a
/// default-constructed [ActionDispatcher].
final ActionDispatcher? dispatcher;
/// {@template flutter.widgets.actions.actions}
/// A map of [Intent] keys to [Action<Intent>] objects that defines which
/// actions this widget knows about.
///
/// For performance reasons, it is recommended that a pre-built map is
/// passed in here (e.g. a final variable from your widget class) instead of
/// defining it inline in the build function.
/// {@endtemplate}
final Map<Type, Action<Intent>> actions;
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
// Visits the Actions widget ancestors of the given element using
// getElementForInheritedWidgetOfExactType. Returns true if the visitor found
// what it was looking for.
static bool _visitActionsAncestors(BuildContext context, bool Function(InheritedElement element) visitor) {
if (!context.mounted) {
return false;
}
InheritedElement? actionsElement = context.getElementForInheritedWidgetOfExactType<_ActionsScope>();
while (actionsElement != null) {
if (visitor(actionsElement)) {
break;
}
// _getParent is needed here because
// context.getElementForInheritedWidgetOfExactType will return itself if it
// happens to be of the correct type.
final BuildContext parent = _getParent(actionsElement);
actionsElement = parent.getElementForInheritedWidgetOfExactType<_ActionsScope>();
}
return actionsElement != null;
}
// Finds the nearest valid ActionDispatcher, or creates a new one if it
// doesn't find one.
static ActionDispatcher _findDispatcher(BuildContext context) {
ActionDispatcher? dispatcher;
_visitActionsAncestors(context, (InheritedElement element) {
final ActionDispatcher? found = (element.widget as _ActionsScope).dispatcher;
if (found != null) {
dispatcher = found;
return true;
}
return false;
});
return dispatcher ?? const ActionDispatcher();
}
/// Returns a [VoidCallback] handler that invokes the bound action for the
/// given `intent` if the action is enabled, and returns null if the action is
/// not enabled, or no matching action is found.
///
/// This is intended to be used in widgets which have something similar to an
/// `onTap` handler, which takes a `VoidCallback`, and can be set to the
/// result of calling this function.
///
/// Creates a dependency on the [Actions] widget that maps the bound action so
/// that if the actions change, the context will be rebuilt and find the
/// updated action.
///
/// The value returned from the [Action.invoke] method is discarded when the
/// returned callback is called. If the return value is needed, consider using
/// [Actions.invoke] instead.
static VoidCallback? handler<T extends Intent>(BuildContext context, T intent) {
final Action<T>? action = Actions.maybeFind<T>(context);
if (action != null && action._isEnabled(intent, context)) {
return () {
// Could be that the action was enabled when the closure was created,
// but is now no longer enabled, so check again.
if (action._isEnabled(intent, context)) {
Actions.of(context).invokeAction(action, intent, context);
}
};
}
return null;
}
/// Finds the [Action] bound to the given intent type `T` in the given `context`.
///
/// Creates a dependency on the [Actions] widget that maps the bound action so
/// that if the actions change, the context will be rebuilt and find the
/// updated action.
///
/// The optional `intent` argument supplies the type of the intent to look for
/// if the concrete type of the intent sought isn't available. If not
/// supplied, then `T` is used.
///
/// If no [Actions] widget surrounds the given context, this function will
/// assert in debug mode, and throw an exception in release mode.
///
/// See also:
///
/// * [maybeFind], which is similar to this function, but will return null if
/// no [Actions] ancestor is found.
static Action<T> find<T extends Intent>(BuildContext context, { T? intent }) {
final Action<T>? action = maybeFind(context, intent: intent);
assert(() {
if (action == null) {
final Type type = intent?.runtimeType ?? T;
throw FlutterError(
'Unable to find an action for a $type in an $Actions widget '
'in the given context.\n'
"$Actions.find() was called on a context that doesn't contain an "
'$Actions widget with a mapping for the given intent type.\n'
'The context used was:\n'
' $context\n'
'The intent type requested was:\n'
' $type',
);
}
return true;
}());
return action!;
}
/// Finds the [Action] bound to the given intent type `T` in the given `context`.
///
/// Creates a dependency on the [Actions] widget that maps the bound action so
/// that if the actions change, the context will be rebuilt and find the
/// updated action.
///
/// The optional `intent` argument supplies the type of the intent to look for
/// if the concrete type of the intent sought isn't available. If not
/// supplied, then `T` is used.
///
/// If no [Actions] widget surrounds the given context, this function will
/// return null.
///
/// See also:
///
/// * [find], which is similar to this function, but will throw if
/// no [Actions] ancestor is found.
static Action<T>? maybeFind<T extends Intent>(BuildContext context, { T? intent }) {
Action<T>? action;
// Specialize the type if a runtime example instance of the intent is given.
// This allows this function to be called by code that doesn't know the
// concrete type of the intent at compile time.
final Type type = intent?.runtimeType ?? T;
assert(
type != Intent,
'The type passed to "find" resolved to "Intent": either a non-Intent '
'generic type argument or an example intent derived from Intent must be '
'specified. Intent may be used as the generic type as long as the optional '
'"intent" argument is passed.',
);
_visitActionsAncestors(context, (InheritedElement element) {
final _ActionsScope actions = element.widget as _ActionsScope;
final Action<T>? result = _castAction(actions, intent: intent);
if (result != null) {
context.dependOnInheritedElement(element);
action = result;
return true;
}
return false;
});
return action;
}
static Action<T>? _maybeFindWithoutDependingOn<T extends Intent>(BuildContext context, { T? intent }) {
Action<T>? action;
// Specialize the type if a runtime example instance of the intent is given.
// This allows this function to be called by code that doesn't know the
// concrete type of the intent at compile time.
final Type type = intent?.runtimeType ?? T;
assert(
type != Intent,
'The type passed to "find" resolved to "Intent": either a non-Intent '
'generic type argument or an example intent derived from Intent must be '
'specified. Intent may be used as the generic type as long as the optional '
'"intent" argument is passed.',
);
_visitActionsAncestors(context, (InheritedElement element) {
final _ActionsScope actions = element.widget as _ActionsScope;
final Action<T>? result = _castAction(actions, intent: intent);
if (result != null) {
action = result;
return true;
}
return false;
});
return action;
}
// Find the [Action] that handles the given `intent` in the given
// `_ActionsScope`, and verify it has the right type parameter.
static Action<T>? _castAction<T extends Intent>(_ActionsScope actionsMarker, { T? intent }) {
final Action<Intent>? mappedAction = actionsMarker.actions[intent?.runtimeType ?? T];
if (mappedAction is Action<T>?) {
return mappedAction;
} else {
assert(
false,
'$T cannot be handled by an Action of runtime type ${mappedAction.runtimeType}.'
);
return null;
}
}
/// Returns the [ActionDispatcher] associated with the [Actions] widget that
/// most tightly encloses the given [BuildContext].
///
/// Will return a newly created [ActionDispatcher] if no ambient [Actions]
/// widget is found.
static ActionDispatcher of(BuildContext context) {
final _ActionsScope? marker = context.dependOnInheritedWidgetOfExactType<_ActionsScope>();
return marker?.dispatcher ?? _findDispatcher(context);
}
/// Invokes the action associated with the given [Intent] using the
/// [Actions] widget that most tightly encloses the given [BuildContext].
///
/// This method returns the result of invoking the action's [Action.invoke]
/// method.
///
/// If the given `intent` doesn't map to an action, then it will look to the
/// next ancestor [Actions] widget in the hierarchy until it reaches the root.
///
/// This method will throw an exception if no ambient [Actions] widget is
/// found, or when a suitable [Action] is found but it returns false for
/// [Action.isEnabled].
static Object? invoke<T extends Intent>(
BuildContext context,
T intent,
) {
Object? returnValue;
final bool actionFound = _visitActionsAncestors(context, (InheritedElement element) {
final _ActionsScope actions = element.widget as _ActionsScope;
final Action<T>? result = _castAction(actions, intent: intent);
if (result != null && result._isEnabled(intent, context)) {
// Invoke the action we found using the relevant dispatcher from the Actions
// Element we found.
returnValue = _findDispatcher(element).invokeAction(result, intent, context);
}
return result != null;
});
assert(() {
if (!actionFound) {
throw FlutterError(
'Unable to find an action for an Intent with type '
'${intent.runtimeType} in an $Actions widget in the given context.\n'
'$Actions.invoke() was unable to find an $Actions widget that '
"contained a mapping for the given intent, or the intent type isn't the "
'same as the type argument to invoke (which is $T - try supplying a '
'type argument to invoke if one was not given)\n'
'The context used was:\n'
' $context\n'
'The intent type requested was:\n'
' ${intent.runtimeType}',
);
}
return true;
}());
return returnValue;
}
/// Invokes the action associated with the given [Intent] using the
/// [Actions] widget that most tightly encloses the given [BuildContext].
///
/// This method returns the result of invoking the action's [Action.invoke]
/// method. If no action mapping was found for the specified intent, or if the
/// first action found was disabled, or the action itself returns null
/// from [Action.invoke], then this method returns null.
///
/// If the given `intent` doesn't map to an action, then it will look to the
/// next ancestor [Actions] widget in the hierarchy until it reaches the root.
/// If a suitable [Action] is found but its [Action.isEnabled] returns false,
/// the search will stop and this method will return null.
static Object? maybeInvoke<T extends Intent>(
BuildContext context,
T intent,
) {
Object? returnValue;
_visitActionsAncestors(context, (InheritedElement element) {
final _ActionsScope actions = element.widget as _ActionsScope;
final Action<T>? result = _castAction(actions, intent: intent);
if (result != null && result._isEnabled(intent, context)) {
// Invoke the action we found using the relevant dispatcher from the Actions
// element we found.
returnValue = _findDispatcher(element).invokeAction(result, intent, context);
}
return result != null;
});
return returnValue;
}
@override
State<Actions> createState() => _ActionsState();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<ActionDispatcher>('dispatcher', dispatcher));
properties.add(DiagnosticsProperty<Map<Type, Action<Intent>>>('actions', actions));
}
}
class _ActionsState extends State<Actions> {
// The set of actions that this Actions widget is current listening to.
Set<Action<Intent>>? listenedActions = <Action<Intent>>{};
// Used to tell the marker to rebuild its dependencies when the state of an
// action in the map changes.
Object rebuildKey = Object();
@override
void initState() {
super.initState();
_updateActionListeners();
}
void _handleActionChanged(Action<Intent> action) {
// Generate a new key so that the marker notifies dependents.
setState(() {
rebuildKey = Object();
});
}
void _updateActionListeners() {
final Set<Action<Intent>> widgetActions = widget.actions.values.toSet();
final Set<Action<Intent>> removedActions = listenedActions!.difference(widgetActions);
final Set<Action<Intent>> addedActions = widgetActions.difference(listenedActions!);
for (final Action<Intent> action in removedActions) {
action.removeActionListener(_handleActionChanged);
}
for (final Action<Intent> action in addedActions) {
action.addActionListener(_handleActionChanged);
}
listenedActions = widgetActions;
}
@override
void didUpdateWidget(Actions oldWidget) {
super.didUpdateWidget(oldWidget);
_updateActionListeners();
}
@override
void dispose() {
super.dispose();
for (final Action<Intent> action in listenedActions!) {
action.removeActionListener(_handleActionChanged);
}
listenedActions = null;
}
@override
Widget build(BuildContext context) {
return _ActionsScope(
actions: widget.actions,
dispatcher: widget.dispatcher,
rebuildKey: rebuildKey,
child: widget.child,
);
}
}
// An inherited widget used by Actions widget for fast lookup of the Actions
// widget information.
class _ActionsScope extends InheritedWidget {
const _ActionsScope({
required this.dispatcher,
required this.actions,
required this.rebuildKey,
required super.child,
});
final ActionDispatcher? dispatcher;
final Map<Type, Action<Intent>> actions;
final Object rebuildKey;
@override
bool updateShouldNotify(_ActionsScope oldWidget) {
return rebuildKey != oldWidget.rebuildKey
|| oldWidget.dispatcher != dispatcher
|| !mapEquals<Type, Action<Intent>>(oldWidget.actions, actions);
}
}
/// A widget that combines the functionality of [Actions], [Shortcuts],
/// [MouseRegion] and a [Focus] widget to create a detector that defines actions
/// and key bindings, and provides callbacks for handling focus and hover
/// highlights.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=R84AGg0lKs8}
///
/// This widget can be used to give a control the required detection modes for
/// focus and hover handling. It is most often used when authoring a new control
/// widget, and the new control should be enabled for keyboard traversal and
/// activation.
///
/// {@tool dartpad}
/// This example shows how keyboard interaction can be added to a custom control
/// that changes color when hovered and focused, and can toggle a light when
/// activated, either by touch or by hitting the `X` key on the keyboard when
/// the "And Me" button has the keyboard focus (be sure to use TAB to move the
/// focus to the "And Me" button before trying it out).
///
/// This example defines its own key binding for the `X` key, but in this case,
/// there is also a default key binding for [ActivateAction] in the default key
/// bindings created by [WidgetsApp] (the parent for [MaterialApp], and
/// [CupertinoApp]), so the `ENTER` key will also activate the buttons.
///
/// ** See code in examples/api/lib/widgets/actions/focusable_action_detector.0.dart **
/// {@end-tool}
///
/// This widget doesn't have any visual representation, it is just a detector that
/// provides focus and hover capabilities.
///
/// It hosts its own [FocusNode] or uses [focusNode], if given.
class FocusableActionDetector extends StatefulWidget {
/// Create a const [FocusableActionDetector].
const FocusableActionDetector({
super.key,
this.enabled = true,
this.focusNode,
this.autofocus = false,
this.descendantsAreFocusable = true,
this.descendantsAreTraversable = true,
this.shortcuts,
this.actions,
this.onShowFocusHighlight,
this.onShowHoverHighlight,
this.onFocusChange,
this.mouseCursor = MouseCursor.defer,
this.includeFocusSemantics = true,
required this.child,
});
/// Is this widget enabled or not.
///
/// If disabled, will not send any notifications needed to update highlight or
/// focus state, and will not define or respond to any actions or shortcuts.
///
/// When disabled, adds [Focus] to the widget tree, but sets
/// [Focus.canRequestFocus] to false.
final bool enabled;
/// {@macro flutter.widgets.Focus.focusNode}
final FocusNode? focusNode;
/// {@macro flutter.widgets.Focus.autofocus}
final bool autofocus;
/// {@macro flutter.widgets.Focus.descendantsAreFocusable}
final bool descendantsAreFocusable;
/// {@macro flutter.widgets.Focus.descendantsAreTraversable}
final bool descendantsAreTraversable;
/// {@macro flutter.widgets.actions.actions}
final Map<Type, Action<Intent>>? actions;
/// {@macro flutter.widgets.shortcuts.shortcuts}
final Map<ShortcutActivator, Intent>? shortcuts;
/// A function that will be called when the focus highlight should be shown or
/// hidden.
///
/// This method is not triggered at the unmount of the widget.
final ValueChanged<bool>? onShowFocusHighlight;
/// A function that will be called when the hover highlight should be shown or hidden.
///
/// This method is not triggered at the unmount of the widget.
final ValueChanged<bool>? onShowHoverHighlight;
/// A function that will be called when the focus changes.
///
/// Called with true if the [focusNode] has primary focus.
final ValueChanged<bool>? onFocusChange;
/// The cursor for a mouse pointer when it enters or is hovering over the
/// widget.
///
/// The [mouseCursor] defaults to [MouseCursor.defer], deferring the choice of
/// cursor to the next region behind it in hit-test order.
final MouseCursor mouseCursor;
/// Whether to include semantics from [Focus].
///
/// Defaults to true.
final bool includeFocusSemantics;
/// The child widget for this [FocusableActionDetector] widget.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
@override
State<FocusableActionDetector> createState() => _FocusableActionDetectorState();
}
class _FocusableActionDetectorState extends State<FocusableActionDetector> {
@override
void initState() {
super.initState();
SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
_updateHighlightMode(FocusManager.instance.highlightMode);
}, debugLabel: 'FocusableActionDetector.updateHighlightMode');
FocusManager.instance.addHighlightModeListener(_handleFocusHighlightModeChange);
}
@override
void dispose() {
FocusManager.instance.removeHighlightModeListener(_handleFocusHighlightModeChange);
super.dispose();
}
bool _canShowHighlight = false;
void _updateHighlightMode(FocusHighlightMode mode) {
_mayTriggerCallback(task: () {
_canShowHighlight = switch (FocusManager.instance.highlightMode) {
FocusHighlightMode.touch => false,
FocusHighlightMode.traditional => true,
};
});
}
// Have to have this separate from the _updateHighlightMode because it gets
// called in initState, where things aren't mounted yet.
// Since this method is a highlight mode listener, it is only called
// immediately following pointer events.
void _handleFocusHighlightModeChange(FocusHighlightMode mode) {
if (!mounted) {
return;
}
_updateHighlightMode(mode);
}
bool _hovering = false;
void _handleMouseEnter(PointerEnterEvent event) {
if (!_hovering) {
_mayTriggerCallback(task: () {
_hovering = true;
});
}
}
void _handleMouseExit(PointerExitEvent event) {
if (_hovering) {
_mayTriggerCallback(task: () {
_hovering = false;
});
}
}
bool _focused = false;
void _handleFocusChange(bool focused) {
if (_focused != focused) {
_mayTriggerCallback(task: () {
_focused = focused;
});
widget.onFocusChange?.call(_focused);
}
}
// Record old states, do `task` if not null, then compare old states with the
// new states, and trigger callbacks if necessary.
//
// The old states are collected from `oldWidget` if it is provided, or the
// current widget (before doing `task`) otherwise. The new states are always
// collected from the current widget.
void _mayTriggerCallback({VoidCallback? task, FocusableActionDetector? oldWidget}) {
bool shouldShowHoverHighlight(FocusableActionDetector target) {
return _hovering && target.enabled && _canShowHighlight;
}
bool canRequestFocus(FocusableActionDetector target) {
return switch (MediaQuery.maybeNavigationModeOf(context)) {
NavigationMode.traditional || null => target.enabled,
NavigationMode.directional => true,
};
}
bool shouldShowFocusHighlight(FocusableActionDetector target) {
return _focused && _canShowHighlight && canRequestFocus(target);
}
assert(SchedulerBinding.instance.schedulerPhase != SchedulerPhase.persistentCallbacks);
final FocusableActionDetector oldTarget = oldWidget ?? widget;
final bool didShowHoverHighlight = shouldShowHoverHighlight(oldTarget);
final bool didShowFocusHighlight = shouldShowFocusHighlight(oldTarget);
if (task != null) {
task();
}
final bool doShowHoverHighlight = shouldShowHoverHighlight(widget);
final bool doShowFocusHighlight = shouldShowFocusHighlight(widget);
if (didShowFocusHighlight != doShowFocusHighlight) {
widget.onShowFocusHighlight?.call(doShowFocusHighlight);
}
if (didShowHoverHighlight != doShowHoverHighlight) {
widget.onShowHoverHighlight?.call(doShowHoverHighlight);
}
}
@override
void didUpdateWidget(FocusableActionDetector oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.enabled != oldWidget.enabled) {
SchedulerBinding.instance.addPostFrameCallback((Duration duration) {
_mayTriggerCallback(oldWidget: oldWidget);
}, debugLabel: 'FocusableActionDetector.mayTriggerCallback');
}
}
bool get _canRequestFocus {
return switch (MediaQuery.maybeNavigationModeOf(context)) {
NavigationMode.traditional || null => widget.enabled,
NavigationMode.directional => true,
};
}
// This global key is needed to keep only the necessary widgets in the tree
// while maintaining the subtree's state.
//
// See https://github.com/flutter/flutter/issues/64058 for an explanation of
// why using a global key over keeping the shape of the tree.
final GlobalKey _mouseRegionKey = GlobalKey();
@override
Widget build(BuildContext context) {
Widget child = MouseRegion(
key: _mouseRegionKey,
onEnter: _handleMouseEnter,
onExit: _handleMouseExit,
cursor: widget.mouseCursor,
child: Focus(
focusNode: widget.focusNode,
autofocus: widget.autofocus,
descendantsAreFocusable: widget.descendantsAreFocusable,
descendantsAreTraversable: widget.descendantsAreTraversable,
canRequestFocus: _canRequestFocus,
onFocusChange: _handleFocusChange,
includeSemantics: widget.includeFocusSemantics,
child: widget.child,
),
);
if (widget.enabled && widget.actions != null && widget.actions!.isNotEmpty) {
child = Actions(actions: widget.actions!, child: child);
}
if (widget.enabled && widget.shortcuts != null && widget.shortcuts!.isNotEmpty) {
child = Shortcuts(shortcuts: widget.shortcuts!, child: child);
}
return child;
}
}
/// An [Intent] that keeps a [VoidCallback] to be invoked by a
/// [VoidCallbackAction] when it receives this intent.
class VoidCallbackIntent extends Intent {
/// Creates a [VoidCallbackIntent].
const VoidCallbackIntent(this.callback);
/// The callback that is to be called by the [VoidCallbackAction] that
/// receives this intent.
final VoidCallback callback;
}
/// An [Action] that invokes the [VoidCallback] given to it in the
/// [VoidCallbackIntent] passed to it when invoked.
///
/// See also:
///
/// * [CallbackAction], which is an action that will invoke a callback with the
/// intent passed to the action's invoke method. The callback is configured
/// on the action, not the intent, like this class.
class VoidCallbackAction extends Action<VoidCallbackIntent> {
@override
Object? invoke(VoidCallbackIntent intent) {
intent.callback();
return null;
}
}
/// An [Intent] that is bound to a [DoNothingAction].
///
/// Attaching a [DoNothingIntent] to a [Shortcuts] mapping is one way to disable
/// a keyboard shortcut defined by a widget higher in the widget hierarchy and
/// consume any key event that triggers it via a shortcut.
///
/// This intent cannot be subclassed.
///
/// See also:
///
/// * [DoNothingAndStopPropagationIntent], a similar intent that will not
/// handle the key event, but will still keep it from being passed to other key
/// handlers in the focus chain.
class DoNothingIntent extends Intent {
/// Creates a const [DoNothingIntent].
const factory DoNothingIntent() = DoNothingIntent._;
// Make DoNothingIntent constructor private so it can't be subclassed.
const DoNothingIntent._();
}
/// An [Intent] that is bound to a [DoNothingAction], but, in addition to not
/// performing an action, also stops the propagation of the key event bound to
/// this intent to other key event handlers in the focus chain.
///
/// Attaching a [DoNothingAndStopPropagationIntent] to a [Shortcuts.shortcuts]
/// mapping is one way to disable a keyboard shortcut defined by a widget higher
/// in the widget hierarchy. In addition, the bound [DoNothingAction] will
/// return false from [DoNothingAction.consumesKey], causing the key bound to
/// this intent to be passed on to the platform embedding as "not handled" with
/// out passing it to other key handlers in the focus chain (e.g. parent
/// `Shortcuts` widgets higher up in the chain).
///
/// This intent cannot be subclassed.
///
/// See also:
///
/// * [DoNothingIntent], a similar intent that will handle the key event.
class DoNothingAndStopPropagationIntent extends Intent {
/// Creates a const [DoNothingAndStopPropagationIntent].
const factory DoNothingAndStopPropagationIntent() = DoNothingAndStopPropagationIntent._;
// Make DoNothingAndStopPropagationIntent constructor private so it can't be subclassed.
const DoNothingAndStopPropagationIntent._();
}
/// An [Action] that doesn't perform any action when invoked.
///
/// Attaching a [DoNothingAction] to an [Actions.actions] mapping is a way to
/// disable an action defined by a widget higher in the widget hierarchy.
///
/// If [consumesKey] returns false, then not only will this action do nothing,
/// but it will stop the propagation of the key event used to trigger it to
/// other widgets in the focus chain and tell the embedding that the key wasn't
/// handled, allowing text input fields or other non-Flutter elements to receive
/// that key event. The return value of [consumesKey] can be set via the
/// `consumesKey` argument to the constructor.
///
/// This action can be bound to any [Intent].
///
/// See also:
/// - [DoNothingIntent], which is an intent that can be bound to a [KeySet] in
/// a [Shortcuts] widget to do nothing.
/// - [DoNothingAndStopPropagationIntent], which is an intent that can be bound
/// to a [KeySet] in a [Shortcuts] widget to do nothing and also stop key event
/// propagation to other key handlers in the focus chain.
class DoNothingAction extends Action<Intent> {
/// Creates a [DoNothingAction].
///
/// The optional [consumesKey] argument defaults to true.
DoNothingAction({bool consumesKey = true}) : _consumesKey = consumesKey;
@override
bool consumesKey(Intent intent) => _consumesKey;
final bool _consumesKey;
@override
void invoke(Intent intent) {}
}
/// An [Intent] that activates the currently focused control.
///
/// This intent is bound by default to the [LogicalKeyboardKey.space] key on all
/// platforms, and also to the [LogicalKeyboardKey.enter] key on all platforms
/// except the web, where ENTER doesn't toggle selection. On the web, ENTER is
/// bound to [ButtonActivateIntent] instead.
///
/// See also:
///
/// * [WidgetsApp.defaultShortcuts], which contains the default shortcuts used
/// in apps.
/// * [WidgetsApp.shortcuts], which defines the shortcuts to use in an
/// application (and defaults to [WidgetsApp.defaultShortcuts]).
class ActivateIntent extends Intent {
/// Creates an intent that activates the currently focused control.
const ActivateIntent();
}
/// An [Intent] that activates the currently focused button.
///
/// This intent is bound by default to the [LogicalKeyboardKey.enter] key on the
/// web, where ENTER can be used to activate buttons, but not toggle selection.
/// All other platforms bind [LogicalKeyboardKey.enter] to [ActivateIntent].
///
/// See also:
///
/// * [WidgetsApp.defaultShortcuts], which contains the default shortcuts used
/// in apps.
/// * [WidgetsApp.shortcuts], which defines the shortcuts to use in an
/// application (and defaults to [WidgetsApp.defaultShortcuts]).
class ButtonActivateIntent extends Intent {
/// Creates an intent that activates the currently focused control,
/// if it's a button.
const ButtonActivateIntent();
}
/// An [Action] that activates the currently focused control.
///
/// This is an abstract class that serves as a base class for actions that
/// activate a control. By default, is bound to [LogicalKeyboardKey.enter],
/// [LogicalKeyboardKey.gameButtonA], and [LogicalKeyboardKey.space] in the
/// default keyboard map in [WidgetsApp].
abstract class ActivateAction extends Action<ActivateIntent> { }
/// An [Intent] that selects the currently focused control.
class SelectIntent extends Intent {
/// Creates an intent that selects the currently focused control.
const SelectIntent();
}
/// An action that selects the currently focused control.
///
/// This is an abstract class that serves as a base class for actions that
/// select something. It is not bound to any key by default.
abstract class SelectAction extends Action<SelectIntent> { }
/// An [Intent] that dismisses the currently focused widget.
///
/// The [WidgetsApp.defaultShortcuts] binds this intent to the
/// [LogicalKeyboardKey.escape] and [LogicalKeyboardKey.gameButtonB] keys.
///
/// See also:
/// - [ModalRoute] which listens for this intent to dismiss modal routes
/// (dialogs, pop-up menus, drawers, etc).
class DismissIntent extends Intent {
/// Creates an intent that dismisses the currently focused widget.
const DismissIntent();
}
/// An [Action] that dismisses the focused widget.
///
/// This is an abstract class that serves as a base class for dismiss actions.
abstract class DismissAction extends Action<DismissIntent> { }
/// An [Intent] that evaluates a series of specified [orderedIntents] for
/// execution.
///
/// The first intent that matches an enabled action is used.
class PrioritizedIntents extends Intent {
/// Creates an intent that is used with [PrioritizedAction] to specify a list
/// of intents, the first available of which will be used.
const PrioritizedIntents({
required this.orderedIntents,
});
/// List of intents to be evaluated in order for execution. When an
/// [Action.isEnabled] returns true, that action will be invoked and
/// progression through the ordered intents stops.
final List<Intent> orderedIntents;
}
/// An [Action] that iterates through a list of [Intent]s, invoking the first
/// that is enabled.
///
/// The [isEnabled] method must be called before [invoke]. Calling [isEnabled]
/// configures the object by seeking the first intent with an enabled action.
/// If the actions have an opportunity to change enabled state, [isEnabled]
/// must be called again before calling [invoke].
class PrioritizedAction extends ContextAction<PrioritizedIntents> {
late Action<dynamic> _selectedAction;
late Intent _selectedIntent;
@override
bool isEnabled(PrioritizedIntents intent, [ BuildContext? context ]) {
final FocusNode? focus = primaryFocus;
if (focus == null || focus.context == null) {
return false;
}
for (final Intent candidateIntent in intent.orderedIntents) {
final Action<Intent>? candidateAction = Actions.maybeFind<Intent>(
focus.context!,
intent: candidateIntent,
);
if (candidateAction != null && candidateAction._isEnabled(candidateIntent, context)) {
_selectedAction = candidateAction;
_selectedIntent = candidateIntent;
return true;
}
}
return false;
}
@override
void invoke(PrioritizedIntents intent, [ BuildContext? context ]) {
_selectedAction._invoke(_selectedIntent, context);
}
}
mixin _OverridableActionMixin<T extends Intent> on Action<T> {
// When debugAssertMutuallyRecursive is true, this action will throw an
// assertion error when the override calls this action's "invoke" method and
// the override is already being invoked from within the "invoke" method.
bool debugAssertMutuallyRecursive = false;
bool debugAssertIsActionEnabledMutuallyRecursive = false;
bool debugAssertIsEnabledMutuallyRecursive = false;
bool debugAssertConsumeKeyMutuallyRecursive = false;
// The default action to invoke if an enabled override Action can't be found
// using [lookupContext].
Action<T> get defaultAction;
// The [BuildContext] used to find the override of this [Action].
BuildContext get lookupContext;
// How to invoke [defaultAction], given the caller [fromAction].
Object? invokeDefaultAction(T intent, Action<T>? fromAction, BuildContext? context);
Action<T>? getOverrideAction({ bool declareDependency = false }) {
final Action<T>? override = declareDependency
? Actions.maybeFind(lookupContext)
: Actions._maybeFindWithoutDependingOn(lookupContext);
assert(!identical(override, this));
return override;
}
@override
void _updateCallingAction(Action<T>? value) {
super._updateCallingAction(value);
defaultAction._updateCallingAction(value);
}
Object? _invokeOverride(Action<T> overrideAction, T intent, BuildContext? context) {
assert(!debugAssertMutuallyRecursive);
assert(() {
debugAssertMutuallyRecursive = true;
return true;
}());
overrideAction._updateCallingAction(defaultAction);
final Object? returnValue = overrideAction._invoke(intent, context);
overrideAction._updateCallingAction(null);
assert(() {
debugAssertMutuallyRecursive = false;
return true;
}());
return returnValue;
}
@override
Object? invoke(T intent, [BuildContext? context]) {
final Action<T>? overrideAction = getOverrideAction();
final Object? returnValue = overrideAction == null
? invokeDefaultAction(intent, callingAction, context)
: _invokeOverride(overrideAction, intent, context);
return returnValue;
}
bool isOverrideActionEnabled(Action<T> overrideAction) {
assert(!debugAssertIsActionEnabledMutuallyRecursive);
assert(() {
debugAssertIsActionEnabledMutuallyRecursive = true;
return true;
}());
overrideAction._updateCallingAction(defaultAction);
final bool isOverrideEnabled = overrideAction.isActionEnabled;
overrideAction._updateCallingAction(null);
assert(() {
debugAssertIsActionEnabledMutuallyRecursive = false;
return true;
}());
return isOverrideEnabled;
}
@override
bool get isActionEnabled {
final Action<T>? overrideAction = getOverrideAction(declareDependency: true);
final bool returnValue = overrideAction != null
? isOverrideActionEnabled(overrideAction)
: defaultAction.isActionEnabled;
return returnValue;
}
@override
bool isEnabled(T intent, [BuildContext? context]) {
assert(!debugAssertIsEnabledMutuallyRecursive);
assert(() {
debugAssertIsEnabledMutuallyRecursive = true;
return true;
}());
final Action<T>? overrideAction = getOverrideAction();
overrideAction?._updateCallingAction(defaultAction);
final bool returnValue = (overrideAction ?? defaultAction)._isEnabled(intent, context);
overrideAction?._updateCallingAction(null);
assert(() {
debugAssertIsEnabledMutuallyRecursive = false;
return true;
}());
return returnValue;
}
@override
bool consumesKey(T intent) {
assert(!debugAssertConsumeKeyMutuallyRecursive);
assert(() {
debugAssertConsumeKeyMutuallyRecursive = true;
return true;
}());
final Action<T>? overrideAction = getOverrideAction();
overrideAction?._updateCallingAction(defaultAction);
final bool isEnabled = (overrideAction ?? defaultAction).consumesKey(intent);
overrideAction?._updateCallingAction(null);
assert(() {
debugAssertConsumeKeyMutuallyRecursive = false;
return true;
}());
return isEnabled;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Action<T>>('defaultAction', defaultAction));
}
}
class _OverridableAction<T extends Intent> extends ContextAction<T> with _OverridableActionMixin<T> {
_OverridableAction({ required this.defaultAction, required this.lookupContext }) ;
@override
final Action<T> defaultAction;
@override
final BuildContext lookupContext;
@override
Object? invokeDefaultAction(T intent, Action<T>? fromAction, BuildContext? context) {
if (fromAction == null) {
return defaultAction.invoke(intent);
} else {
final Object? returnValue = defaultAction.invoke(intent);
return returnValue;
}
}
@override
ContextAction<T> _makeOverridableAction(BuildContext context) {
return _OverridableAction<T>(defaultAction: defaultAction, lookupContext: context);
}
}
class _OverridableContextAction<T extends Intent> extends ContextAction<T> with _OverridableActionMixin<T> {
_OverridableContextAction({ required this.defaultAction, required this.lookupContext });
@override
final ContextAction<T> defaultAction;
@override
final BuildContext lookupContext;
@override
Object? _invokeOverride(Action<T> overrideAction, T intent, BuildContext? context) {
assert(context != null);
assert(!debugAssertMutuallyRecursive);
assert(() {
debugAssertMutuallyRecursive = true;
return true;
}());
// Wrap the default Action together with the calling context in case
// overrideAction is not a ContextAction and thus have no access to the
// calling BuildContext.
final Action<T> wrappedDefault = _ContextActionToActionAdapter<T>(invokeContext: context!, action: defaultAction);
overrideAction._updateCallingAction(wrappedDefault);
final Object? returnValue = overrideAction._invoke(intent, context);
overrideAction._updateCallingAction(null);
assert(() {
debugAssertMutuallyRecursive = false;
return true;
}());
return returnValue;
}
@override
Object? invokeDefaultAction(T intent, Action<T>? fromAction, BuildContext? context) {
if (fromAction == null) {
return defaultAction.invoke(intent, context);
} else {
final Object? returnValue = defaultAction.invoke(intent, context);
return returnValue;
}
}
@override
ContextAction<T> _makeOverridableAction(BuildContext context) {
return _OverridableContextAction<T>(defaultAction: defaultAction, lookupContext: context);
}
}
class _ContextActionToActionAdapter<T extends Intent> extends Action<T> {
_ContextActionToActionAdapter({required this.invokeContext, required this.action});
final BuildContext invokeContext;
final ContextAction<T> action;
@override
void _updateCallingAction(Action<T>? value) {
action._updateCallingAction(value);
}
@override
Action<T>? get callingAction => action.callingAction;
@override
bool isEnabled(T intent) => action.isEnabled(intent, invokeContext);
@override
bool get isActionEnabled => action.isActionEnabled;
@override
bool consumesKey(T intent) => action.consumesKey(intent);
@override
void addActionListener(ActionListenerCallback listener) {
super.addActionListener(listener);
action.addActionListener(listener);
}
@override
void removeActionListener(ActionListenerCallback listener) {
super.removeActionListener(listener);
action.removeActionListener(listener);
}
@override
@protected
void notifyActionListeners() => action.notifyActionListeners();
@override
Object? invoke(T intent) => action.invoke(intent, invokeContext);
}
| flutter/packages/flutter/lib/src/widgets/actions.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/actions.dart",
"repo_id": "flutter",
"token_count": 21113
} | 817 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' show Color;
import 'framework.dart';
/// An interactive button within either material's [BottomNavigationBar]
/// or the iOS themed [CupertinoTabBar] with an icon and title.
///
/// This class is rarely used in isolation. It is typically embedded in one of
/// the bottom navigation widgets above.
///
/// See also:
///
/// * [BottomNavigationBar]
/// * <https://material.io/design/components/bottom-navigation.html>
/// * [CupertinoTabBar]
/// * <https://developer.apple.com/design/human-interface-guidelines/tab-bars/>
class BottomNavigationBarItem {
/// Creates an item that is used with [BottomNavigationBar.items].
///
/// The argument [icon] should not be null and the argument [label] should not be null when used in a Material Design's [BottomNavigationBar].
const BottomNavigationBarItem({
this.key,
required this.icon,
this.label,
Widget? activeIcon,
this.backgroundColor,
this.tooltip,
}) : activeIcon = activeIcon ?? icon;
/// A key to be passed through to the resultant widget.
///
/// This allows the identification of different [BottomNavigationBarItem]s through their keys.
///
/// When changing the number of bar items in response to a bar item being tapped, giving
/// each item a key will allow the inkwell / splash animation to be correctly positioned.
final Key? key;
/// The icon of the item.
///
/// Typically the icon is an [Icon] or an [ImageIcon] widget. If another type
/// of widget is provided then it should configure itself to match the current
/// [IconTheme] size and color.
///
/// If [activeIcon] is provided, this will only be displayed when the item is
/// not selected.
///
/// To make the bottom navigation bar more accessible, consider choosing an
/// icon with a stroked and filled version, such as [Icons.cloud] and
/// [Icons.cloud_queue]. [icon] should be set to the stroked version and
/// [activeIcon] to the filled version.
///
/// If a particular icon doesn't have a stroked or filled version, then don't
/// pair unrelated icons. Instead, make sure to use a
/// [BottomNavigationBarType.shifting].
final Widget icon;
/// An alternative icon displayed when this bottom navigation item is
/// selected.
///
/// If this icon is not provided, the bottom navigation bar will display
/// [icon] in either state.
///
/// See also:
///
/// * [BottomNavigationBarItem.icon], for a description of how to pair icons.
final Widget activeIcon;
/// The text label for this [BottomNavigationBarItem].
///
/// This will be used to create a [Text] widget to put in the bottom navigation bar.
final String? label;
/// The color of the background radial animation for material [BottomNavigationBar].
///
/// If the navigation bar's type is [BottomNavigationBarType.shifting], then
/// the entire bar is flooded with the [backgroundColor] when this item is
/// tapped. This will override [BottomNavigationBar.backgroundColor].
///
/// Not used for [CupertinoTabBar]. Control the invariant bar color directly
/// via [CupertinoTabBar.backgroundColor].
///
/// See also:
///
/// * [Icon.color] and [ImageIcon.color] to control the foreground color of
/// the icons themselves.
final Color? backgroundColor;
/// The text to display in the [Tooltip] for this [BottomNavigationBarItem].
///
/// A [Tooltip] will only appear on this item if [tooltip] is set to a non-empty string.
///
/// Defaults to null, in which case the tooltip is not shown.
final String? tooltip;
}
| flutter/packages/flutter/lib/src/widgets/bottom_navigation_bar_item.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/bottom_navigation_bar_item.dart",
"repo_id": "flutter",
"token_count": 1038
} | 818 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'basic.dart';
import 'framework.dart';
/// Builder callback used by [DualTransitionBuilder].
///
/// The builder is expected to return a transition powered by the provided
/// `animation` and wrapping the provided `child`.
///
/// The `animation` provided to the builder always runs forward from 0.0 to 1.0.
typedef AnimatedTransitionBuilder = Widget Function(
BuildContext context,
Animation<double> animation,
Widget? child,
);
/// A transition builder that animates its [child] based on the
/// [AnimationStatus] of the provided [animation].
///
/// This widget can be used to specify different enter and exit transitions for
/// a [child].
///
/// While the [animation] runs forward, the [child] is animated according to
/// [forwardBuilder] and while the [animation] is running in reverse, it is
/// animated according to [reverseBuilder].
///
/// Using this builder allows the widget tree to maintain its shape by nesting
/// the enter and exit transitions. This ensures that no state information of
/// any descendant widget is lost when the transition starts or completes.
class DualTransitionBuilder extends StatefulWidget {
/// Creates a [DualTransitionBuilder].
const DualTransitionBuilder({
super.key,
required this.animation,
required this.forwardBuilder,
required this.reverseBuilder,
this.child,
});
/// The animation that drives the [child]'s transition.
///
/// When this animation runs forward, the [child] transitions as specified by
/// [forwardBuilder]. When it runs in reverse, the child transitions according
/// to [reverseBuilder].
final Animation<double> animation;
/// A builder for the transition that makes [child] appear on screen.
///
/// The [child] should be fully visible when the provided `animation` reaches
/// 1.0.
///
/// The `animation` provided to this builder is running forward from 0.0 to
/// 1.0 when [animation] runs _forward_. When [animation] runs in reverse,
/// the given `animation` is set to [kAlwaysCompleteAnimation].
///
/// See also:
///
/// * [reverseBuilder], which builds the transition for making the [child]
/// disappear from the screen.
final AnimatedTransitionBuilder forwardBuilder;
/// A builder for a transition that makes [child] disappear from the screen.
///
/// The [child] should be fully invisible when the provided `animation`
/// reaches 1.0.
///
/// The `animation` provided to this builder is running forward from 0.0 to
/// 1.0 when [animation] runs in _reverse_. When [animation] runs forward,
/// the given `animation` is set to [kAlwaysDismissedAnimation].
///
/// See also:
///
/// * [forwardBuilder], which builds the transition for making the [child]
/// appear on screen.
final AnimatedTransitionBuilder reverseBuilder;
/// The widget below this [DualTransitionBuilder] in the tree.
///
/// This child widget will be wrapped by the transitions built by
/// [forwardBuilder] and [reverseBuilder].
final Widget? child;
@override
State<DualTransitionBuilder> createState() => _DualTransitionBuilderState();
}
class _DualTransitionBuilderState extends State<DualTransitionBuilder> {
late AnimationStatus _effectiveAnimationStatus;
final ProxyAnimation _forwardAnimation = ProxyAnimation();
final ProxyAnimation _reverseAnimation = ProxyAnimation();
@override
void initState() {
super.initState();
_effectiveAnimationStatus = widget.animation.status;
widget.animation.addStatusListener(_animationListener);
_updateAnimations();
}
void _animationListener(AnimationStatus animationStatus) {
final AnimationStatus oldEffective = _effectiveAnimationStatus;
_effectiveAnimationStatus = _calculateEffectiveAnimationStatus(
lastEffective: _effectiveAnimationStatus,
current: animationStatus,
);
if (oldEffective != _effectiveAnimationStatus) {
_updateAnimations();
}
}
@override
void didUpdateWidget(DualTransitionBuilder oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.animation != widget.animation) {
oldWidget.animation.removeStatusListener(_animationListener);
widget.animation.addStatusListener(_animationListener);
_animationListener(widget.animation.status);
}
}
// When a transition is interrupted midway we just want to play the ongoing
// animation in reverse. Switching to the actual reverse transition would
// yield a disjoint experience since the forward and reverse transitions are
// very different.
AnimationStatus _calculateEffectiveAnimationStatus({
required AnimationStatus lastEffective,
required AnimationStatus current,
}) {
switch (current) {
case AnimationStatus.dismissed:
case AnimationStatus.completed:
return current;
case AnimationStatus.forward:
switch (lastEffective) {
case AnimationStatus.dismissed:
case AnimationStatus.completed:
case AnimationStatus.forward:
return current;
case AnimationStatus.reverse:
return lastEffective;
}
case AnimationStatus.reverse:
switch (lastEffective) {
case AnimationStatus.dismissed:
case AnimationStatus.completed:
case AnimationStatus.reverse:
return current;
case AnimationStatus.forward:
return lastEffective;
}
}
}
void _updateAnimations() {
switch (_effectiveAnimationStatus) {
case AnimationStatus.dismissed:
case AnimationStatus.forward:
_forwardAnimation.parent = widget.animation;
_reverseAnimation.parent = kAlwaysDismissedAnimation;
case AnimationStatus.reverse:
case AnimationStatus.completed:
_forwardAnimation.parent = kAlwaysCompleteAnimation;
_reverseAnimation.parent = ReverseAnimation(widget.animation);
}
}
@override
void dispose() {
widget.animation.removeStatusListener(_animationListener);
super.dispose();
}
@override
Widget build(BuildContext context) {
return widget.forwardBuilder(
context,
_forwardAnimation,
widget.reverseBuilder(
context,
_reverseAnimation,
widget.child,
),
);
}
}
| flutter/packages/flutter/lib/src/widgets/dual_transition_builder.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/dual_transition_builder.dart",
"repo_id": "flutter",
"token_count": 1930
} | 819 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'framework.dart';
/// Applies an [ImageFilter] to its child.
///
/// An image filter will always apply its filter operation to the child widget,
/// even if said filter is conceptually a "no-op", such as an ImageFilter.blur
/// with a radius of 0 or an ImageFilter.matrix with an identity matrix. Setting
/// [ImageFiltered.enabled] to `false` is a more efficient manner of disabling
/// an image filter.
///
/// The framework does not attempt to optimize out "no-op" filters because it
/// cannot tell the difference between an intentional no-op and a filter that is
/// only incidentally a no-op. Consider an ImageFilter.matrix that is animated
/// and happens to pass through the identity matrix. If the framework identified it
/// as a no-op it would drop and then recreate the layer during the animation which
/// would be more expensive than keeping it around.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=7Lftorq4i2o}
///
/// See also:
///
/// * [BackdropFilter], which applies an [ImageFilter] to everything
/// beneath its child.
/// * [ColorFiltered], which applies a [ColorFilter] to its child.
@immutable
class ImageFiltered extends SingleChildRenderObjectWidget {
/// Creates a widget that applies an [ImageFilter] to its child.
const ImageFiltered({
super.key,
required this.imageFilter,
super.child,
this.enabled = true,
});
/// The image filter to apply to the child of this widget.
final ImageFilter imageFilter;
/// Whether or not to apply the image filter operation to the child of this
/// widget.
///
/// Prefer setting enabled to `false` instead of creating a "no-op" filter
/// type for performance reasons.
final bool enabled;
@override
RenderObject createRenderObject(BuildContext context) => _ImageFilterRenderObject(imageFilter, enabled);
@override
void updateRenderObject(BuildContext context, RenderObject renderObject) {
(renderObject as _ImageFilterRenderObject)
..enabled = enabled
..imageFilter = imageFilter;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<ImageFilter>('imageFilter', imageFilter));
}
}
class _ImageFilterRenderObject extends RenderProxyBox {
_ImageFilterRenderObject(this._imageFilter, this._enabled);
bool get enabled => _enabled;
bool _enabled;
set enabled(bool value) {
if (enabled == value) {
return;
}
final bool wasRepaintBoundary = isRepaintBoundary;
_enabled = value;
if (isRepaintBoundary != wasRepaintBoundary) {
markNeedsCompositingBitsUpdate();
}
markNeedsPaint();
}
ImageFilter get imageFilter => _imageFilter;
ImageFilter _imageFilter;
set imageFilter(ImageFilter value) {
if (value != _imageFilter) {
_imageFilter = value;
markNeedsCompositedLayerUpdate();
}
}
@override
bool get alwaysNeedsCompositing => child != null && enabled;
@override
bool get isRepaintBoundary => alwaysNeedsCompositing;
@override
OffsetLayer updateCompositedLayer({required covariant ImageFilterLayer? oldLayer}) {
final ImageFilterLayer layer = oldLayer ?? ImageFilterLayer();
layer.imageFilter = imageFilter;
return layer;
}
}
| flutter/packages/flutter/lib/src/widgets/image_filter.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/image_filter.dart",
"repo_id": "flutter",
"token_count": 1041
} | 820 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:developer' as developer;
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'basic.dart';
import 'binding.dart';
import 'focus_manager.dart';
import 'focus_scope.dart';
import 'focus_traversal.dart';
import 'framework.dart';
import 'heroes.dart';
import 'notification_listener.dart';
import 'overlay.dart';
import 'restoration.dart';
import 'restoration_properties.dart';
import 'routes.dart';
import 'ticker_provider.dart';
// Duration for delay before refocusing in android so that the focus won't be interrupted.
const Duration _kAndroidRefocusingDelayDuration = Duration(milliseconds: 300);
// Examples can assume:
// typedef MyAppHome = Placeholder;
// typedef MyHomePage = Placeholder;
// typedef MyPage = ListTile; // any const widget with a Widget "title" constructor argument would do
// late NavigatorState navigator;
// late BuildContext context;
/// Creates a route for the given route settings.
///
/// Used by [Navigator.onGenerateRoute].
///
/// See also:
///
/// * [Navigator], which is where all the [Route]s end up.
typedef RouteFactory = Route<dynamic>? Function(RouteSettings settings);
/// Creates a series of one or more routes.
///
/// Used by [Navigator.onGenerateInitialRoutes].
typedef RouteListFactory = List<Route<dynamic>> Function(NavigatorState navigator, String initialRoute);
/// Creates a [Route] that is to be added to a [Navigator].
///
/// The route can be configured with the provided `arguments`. The provided
/// `context` is the `BuildContext` of the [Navigator] to which the route is
/// added.
///
/// Used by the restorable methods of the [Navigator] that add anonymous routes
/// (e.g. [NavigatorState.restorablePush]). For this use case, the
/// [RestorableRouteBuilder] must be static function annotated with
/// `@pragma('vm:entry-point')`. The [Navigator] will call it again during
/// state restoration to re-create the route.
typedef RestorableRouteBuilder<T> = Route<T> Function(BuildContext context, Object? arguments);
/// Signature for the [Navigator.popUntil] predicate argument.
typedef RoutePredicate = bool Function(Route<dynamic> route);
/// Signature for a callback that verifies that it's OK to call [Navigator.pop].
///
/// Used by [Form.onWillPop], [ModalRoute.addScopedWillPopCallback],
/// [ModalRoute.removeScopedWillPopCallback], and [WillPopScope].
@Deprecated(
'Use PopInvokedCallback instead. '
'This feature was deprecated after v3.12.0-1.0.pre.',
)
typedef WillPopCallback = Future<bool> Function();
/// Signature for the [Navigator.onPopPage] callback.
///
/// This callback must call [Route.didPop] on the specified route and must
/// properly update the pages list the next time it is passed into
/// [Navigator.pages] so that it no longer includes the corresponding [Page].
/// (Otherwise, the page will be interpreted as a new page to show when the
/// [Navigator.pages] list is next updated.)
typedef PopPageCallback = bool Function(Route<dynamic> route, dynamic result);
/// Indicates whether the current route should be popped.
///
/// Used as the return value for [Route.willPop].
///
/// See also:
///
/// * [WillPopScope], a widget that hooks into the route's [Route.willPop]
/// mechanism.
enum RoutePopDisposition {
/// Pop the route.
///
/// If [Route.willPop] or [Route.popDisposition] return [pop] then the back
/// button will actually pop the current route.
pop,
/// Do not pop the route.
///
/// If [Route.willPop] or [Route.popDisposition] return [doNotPop] then the
/// back button will be ignored.
doNotPop,
/// Delegate this to the next level of navigation.
///
/// If [Route.willPop] or [Route.popDisposition] return [bubble] then the back
/// button will be handled by the [SystemNavigator], which will usually close
/// the application.
bubble,
}
/// An abstraction for an entry managed by a [Navigator].
///
/// This class defines an abstract interface between the navigator and the
/// "routes" that are pushed on and popped off the navigator. Most routes have
/// visual affordances, which they place in the navigators [Overlay] using one
/// or more [OverlayEntry] objects.
///
/// See [Navigator] for more explanation of how to use a [Route] with
/// navigation, including code examples.
///
/// See [MaterialPageRoute] for a route that replaces the entire screen with a
/// platform-adaptive transition.
///
/// A route can belong to a page if the [settings] are a subclass of [Page]. A
/// page-based route, as opposed to a pageless route, is created from
/// [Page.createRoute] during [Navigator.pages] updates. The page associated
/// with this route may change during the lifetime of the route. If the
/// [Navigator] updates the page of this route, it calls [changedInternalState]
/// to notify the route that the page has been updated.
///
/// The type argument `T` is the route's return type, as used by
/// [currentResult], [popped], and [didPop]. The type `void` may be used if the
/// route does not return a value.
abstract class Route<T> extends _RoutePlaceholder {
/// Initialize the [Route].
///
/// If the [settings] are not provided, an empty [RouteSettings] object is
/// used instead.
Route({ RouteSettings? settings }) : _settings = settings ?? const RouteSettings() {
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectCreated(
library: 'package:flutter/widgets.dart',
className: '$Route<$T>',
object: this,
);
}
}
/// The navigator that the route is in, if any.
NavigatorState? get navigator => _navigator;
NavigatorState? _navigator;
/// The settings for this route.
///
/// See [RouteSettings] for details.
///
/// The settings can change during the route's lifetime. If the settings
/// change, the route's overlays will be marked dirty (see
/// [changedInternalState]).
///
/// If the route is created from a [Page] in the [Navigator.pages] list, then
/// this will be a [Page] subclass, and it will be updated each time its
/// corresponding [Page] in the [Navigator.pages] has changed. Once the
/// [Route] is removed from the history, this value stops updating (and
/// remains with its last value).
RouteSettings get settings => _settings;
RouteSettings _settings;
/// The restoration scope ID to be used for the [RestorationScope] surrounding
/// this route.
///
/// The restoration scope ID is null if restoration is currently disabled
/// for this route.
///
/// If the restoration scope ID changes (e.g. because restoration is enabled
/// or disabled) during the life of the route, the [ValueListenable] notifies
/// its listeners. As an example, the ID changes to null while the route is
/// transitioning off screen, which triggers a notification on this field. At
/// that point, the route is considered as no longer present for restoration
/// purposes and its state will not be restored.
ValueListenable<String?> get restorationScopeId => _restorationScopeId;
final ValueNotifier<String?> _restorationScopeId = ValueNotifier<String?>(null);
void _updateSettings(RouteSettings newSettings) {
if (_settings != newSettings) {
_settings = newSettings;
changedInternalState();
}
}
// ignore: use_setters_to_change_properties, (setters can't be private)
void _updateRestorationId(String? restorationId) {
_restorationScopeId.value = restorationId;
}
/// The overlay entries of this route.
///
/// These are typically populated by [install]. The [Navigator] is in charge
/// of adding them to and removing them from the [Overlay].
///
/// There must be at least one entry in this list after [install] has been
/// invoked.
///
/// The [Navigator] will take care of keeping the entries together if the
/// route is moved in the history.
List<OverlayEntry> get overlayEntries => const <OverlayEntry>[];
/// Called when the route is inserted into the navigator.
///
/// Uses this to populate [overlayEntries]. There must be at least one entry in
/// this list after [install] has been invoked. The [Navigator] will be in charge
/// to add them to the [Overlay] or remove them from it by calling
/// [OverlayEntry.remove].
@protected
@mustCallSuper
void install() { }
/// Called after [install] when the route is pushed onto the navigator.
///
/// The returned value resolves when the push transition is complete.
///
/// The [didAdd] method will be called instead of [didPush] when the route
/// immediately appears on screen without any push transition.
///
/// The [didChangeNext] and [didChangePrevious] methods are typically called
/// immediately after this method is called.
@protected
@mustCallSuper
TickerFuture didPush() {
return TickerFuture.complete()..then<void>((void _) {
if (navigator?.widget.requestFocus ?? false) {
navigator!.focusNode.enclosingScope?.requestFocus();
}
});
}
/// Called after [install] when the route is added to the navigator.
///
/// This method is called instead of [didPush] when the route immediately
/// appears on screen without any push transition.
///
/// The [didChangeNext] and [didChangePrevious] methods are typically called
/// immediately after this method is called.
@protected
@mustCallSuper
void didAdd() {
if (navigator?.widget.requestFocus ?? false) {
// This TickerFuture serves two purposes. First, we want to make sure that
// animations triggered by other operations will finish before focusing
// the navigator. Second, navigator.focusNode might acquire more focused
// children in Route.install asynchronously. This TickerFuture will wait
// for it to finish first.
//
// The later case can be found when subclasses manage their own focus scopes.
// For example, ModalRoute creates a focus scope in its overlay entries. The
// focused child can only be attached to navigator after initState which
// will be guarded by the asynchronous gap.
TickerFuture.complete().then<void>((void _) {
// The route can be disposed before the ticker future completes. This can
// happen when the navigator is under a TabView that warps from one tab to
// another, non-adjacent tab, with an animation. The TabView reorders its
// children before and after the warping completes, and that causes its
// children to be built and disposed within the same frame. If one of its
// children contains a navigator, the routes in that navigator are also
// added and disposed within that frame.
//
// Since the reference to the navigator will be set to null after it is
// disposed, we have to do a null-safe operation in case that happens
// within the same frame when it is added.
navigator?.focusNode.enclosingScope?.requestFocus();
});
}
}
/// Called after [install] when the route replaced another in the navigator.
///
/// The [didChangeNext] and [didChangePrevious] methods are typically called
/// immediately after this method is called.
@protected
@mustCallSuper
void didReplace(Route<dynamic>? oldRoute) { }
/// Returns whether calling [Navigator.maybePop] when this [Route] is current
/// ([isCurrent]) should do anything.
///
/// [Navigator.maybePop] is usually used instead of [Navigator.pop] to handle
/// the system back button.
///
/// By default, if a [Route] is the first route in the history (i.e., if
/// [isFirst]), it reports that pops should be bubbled
/// ([RoutePopDisposition.bubble]). This behavior prevents the user from
/// popping the first route off the history and being stranded at a blank
/// screen; instead, the larger scope is popped (e.g. the application quits,
/// so that the user returns to the previous application).
///
/// In other cases, the default behavior is to accept the pop
/// ([RoutePopDisposition.pop]).
///
/// The third possible value is [RoutePopDisposition.doNotPop], which causes
/// the pop request to be ignored entirely.
///
/// See also:
///
/// * [Form], which provides a [Form.onWillPop] callback that uses this
/// mechanism.
/// * [WillPopScope], another widget that provides a way to intercept the
/// back button.
@Deprecated(
'Use popDisposition instead. '
'This feature was deprecated after v3.12.0-1.0.pre.',
)
Future<RoutePopDisposition> willPop() async {
return isFirst ? RoutePopDisposition.bubble : RoutePopDisposition.pop;
}
/// Returns whether calling [Navigator.maybePop] when this [Route] is current
/// ([isCurrent]) should do anything.
///
/// [Navigator.maybePop] is usually used instead of [Navigator.pop] to handle
/// the system back button, when it hasn't been disabled via
/// [SystemNavigator.setFrameworkHandlesBack].
///
/// By default, if a [Route] is the first route in the history (i.e., if
/// [isFirst]), it reports that pops should be bubbled
/// ([RoutePopDisposition.bubble]). This behavior prevents the user from
/// popping the first route off the history and being stranded at a blank
/// screen; instead, the larger scope is popped (e.g. the application quits,
/// so that the user returns to the previous application).
///
/// In other cases, the default behavior is to accept the pop
/// ([RoutePopDisposition.pop]).
///
/// The third possible value is [RoutePopDisposition.doNotPop], which causes
/// the pop request to be ignored entirely.
///
/// See also:
///
/// * [Form], which provides a [Form.canPop] boolean that is similar.
/// * [PopScope], a widget that provides a way to intercept the back button.
RoutePopDisposition get popDisposition {
return isFirst ? RoutePopDisposition.bubble : RoutePopDisposition.pop;
}
/// {@template flutter.widgets.navigator.onPopInvoked}
/// Called after a route pop was handled.
///
/// Even when the pop is canceled, for example by a [PopScope] widget, this
/// will still be called. The `didPop` parameter indicates whether or not the
/// back navigation actually happened successfully.
/// {@endtemplate}
void onPopInvoked(bool didPop) {}
/// Whether calling [didPop] would return false.
bool get willHandlePopInternally => false;
/// When this route is popped (see [Navigator.pop]) if the result isn't
/// specified or if it's null, this value will be used instead.
///
/// This fallback is implemented by [didComplete]. This value is used if the
/// argument to that method is null.
T? get currentResult => null;
/// A future that completes when this route is popped off the navigator.
///
/// The future completes with the value given to [Navigator.pop], if any, or
/// else the value of [currentResult]. See [didComplete] for more discussion
/// on this topic.
Future<T?> get popped => _popCompleter.future;
final Completer<T?> _popCompleter = Completer<T?>();
final Completer<T?> _disposeCompleter = Completer<T?>();
/// A request was made to pop this route. If the route can handle it
/// internally (e.g. because it has its own stack of internal state) then
/// return false, otherwise return true (by returning the value of calling
/// `super.didPop`). Returning false will prevent the default behavior of
/// [NavigatorState.pop].
///
/// When this function returns true, the navigator removes this route from
/// the history but does not yet call [dispose]. Instead, it is the route's
/// responsibility to call [NavigatorState.finalizeRoute], which will in turn
/// call [dispose] on the route. This sequence lets the route perform an
/// exit animation (or some other visual effect) after being popped but prior
/// to being disposed.
///
/// This method should call [didComplete] to resolve the [popped] future (and
/// this is all that the default implementation does); routes should not wait
/// for their exit animation to complete before doing so.
///
/// See [popped], [didComplete], and [currentResult] for a discussion of the
/// `result` argument.
@mustCallSuper
bool didPop(T? result) {
didComplete(result);
return true;
}
/// The route was popped or is otherwise being removed somewhat gracefully.
///
/// This is called by [didPop] and in response to
/// [NavigatorState.pushReplacement]. If [didPop] was not called, then the
/// [NavigatorState.finalizeRoute] method must be called immediately, and no exit
/// animation will run.
///
/// The [popped] future is completed by this method. The `result` argument
/// specifies the value that this future is completed with, unless it is null,
/// in which case [currentResult] is used instead.
///
/// This should be called before the pop animation, if any, takes place,
/// though in some cases the animation may be driven by the user before the
/// route is committed to being popped; this can in particular happen with the
/// iOS-style back gesture. See [NavigatorState.didStartUserGesture].
@protected
@mustCallSuper
void didComplete(T? result) {
_popCompleter.complete(result ?? currentResult);
}
/// The given route, which was above this one, has been popped off the
/// navigator.
///
/// This route is now the current route ([isCurrent] is now true), and there
/// is no next route.
@protected
@mustCallSuper
void didPopNext(Route<dynamic> nextRoute) { }
/// This route's next route has changed to the given new route.
///
/// This is called on a route whenever the next route changes for any reason,
/// so long as it is in the history, including when a route is first added to
/// a [Navigator] (e.g. by [Navigator.push]), except for cases when
/// [didPopNext] would be called.
///
/// The `nextRoute` argument will be null if there's no new next route (i.e.
/// if [isCurrent] is true).
@protected
@mustCallSuper
void didChangeNext(Route<dynamic>? nextRoute) { }
/// This route's previous route has changed to the given new route.
///
/// This is called on a route whenever the previous route changes for any
/// reason, so long as it is in the history, except for immediately after the
/// route itself has been pushed (in which case [didPush] or [didReplace] will
/// be called instead).
///
/// The `previousRoute` argument will be null if there's no previous route
/// (i.e. if [isFirst] is true).
@protected
@mustCallSuper
void didChangePrevious(Route<dynamic>? previousRoute) { }
/// Called whenever the internal state of the route has changed.
///
/// This should be called whenever [willHandlePopInternally], [didPop],
/// [ModalRoute.offstage], or other internal state of the route changes value.
/// It is used by [ModalRoute], for example, to report the new information via
/// its inherited widget to any children of the route.
///
/// See also:
///
/// * [changedExternalState], which is called when the [Navigator] has
/// updated in some manner that might affect the routes.
@protected
@mustCallSuper
void changedInternalState() { }
/// Called whenever the [Navigator] has updated in some manner that might
/// affect routes, to indicate that the route may wish to rebuild as well.
///
/// This is called by the [Navigator] whenever the
/// [NavigatorState]'s [State.widget] changes (as in [State.didUpdateWidget]),
/// for example because the [MaterialApp] has been rebuilt. This
/// ensures that routes that directly refer to the state of the
/// widget that built the [MaterialApp] will be notified when that
/// widget rebuilds, since it would otherwise be difficult to notify
/// the routes that state they depend on may have changed.
///
/// It is also called whenever the [Navigator]'s dependencies change
/// (as in [State.didChangeDependencies]). This allows routes to use the
/// [Navigator]'s context ([NavigatorState.context]), for example in
/// [ModalRoute.barrierColor], and update accordingly.
///
/// The [ModalRoute] subclass overrides this to force the barrier
/// overlay to rebuild.
///
/// See also:
///
/// * [changedInternalState], the equivalent but for changes to the internal
/// state of the route.
@protected
@mustCallSuper
void changedExternalState() { }
/// Discards any resources used by the object.
///
/// This method should not remove its [overlayEntries] from the [Overlay]. The
/// object's owner is in charge of doing that.
///
/// After this is called, the object is not in a usable state and should be
/// discarded.
///
/// This method should only be called by the object's owner; typically the
/// [Navigator] owns a route and so will call this method when the route is
/// removed, after which the route is no longer referenced by the navigator.
@mustCallSuper
@protected
void dispose() {
_navigator = null;
_restorationScopeId.dispose();
_disposeCompleter.complete();
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this);
}
}
/// Whether this route is the top-most route on the navigator.
///
/// If this is true, then [isActive] is also true.
bool get isCurrent {
if (_navigator == null) {
return false;
}
final _RouteEntry? currentRouteEntry = _navigator!._lastRouteEntryWhereOrNull(_RouteEntry.isPresentPredicate);
if (currentRouteEntry == null) {
return false;
}
return currentRouteEntry.route == this;
}
/// Whether this route is the bottom-most active route on the navigator.
///
/// If [isFirst] and [isCurrent] are both true then this is the only route on
/// the navigator (and [isActive] will also be true).
bool get isFirst {
if (_navigator == null) {
return false;
}
final _RouteEntry? currentRouteEntry = _navigator!._firstRouteEntryWhereOrNull(_RouteEntry.isPresentPredicate);
if (currentRouteEntry == null) {
return false;
}
return currentRouteEntry.route == this;
}
/// Whether there is at least one active route underneath this route.
@protected
bool get hasActiveRouteBelow {
if (_navigator == null) {
return false;
}
for (final _RouteEntry entry in _navigator!._history) {
if (entry.route == this) {
return false;
}
if (_RouteEntry.isPresentPredicate(entry)) {
return true;
}
}
return false;
}
/// Whether this route is on the navigator.
///
/// If the route is not only active, but also the current route (the top-most
/// route), then [isCurrent] will also be true. If it is the first route (the
/// bottom-most route), then [isFirst] will also be true.
///
/// If a higher route is entirely opaque, then the route will be active but not
/// rendered. It is even possible for the route to be active but for the stateful
/// widgets within the route to not be instantiated. See [ModalRoute.maintainState].
bool get isActive {
return _navigator?._firstRouteEntryWhereOrNull(_RouteEntry.isRoutePredicate(this))?.isPresent ?? false;
}
}
/// Data that might be useful in constructing a [Route].
@immutable
class RouteSettings {
/// Creates data used to construct routes.
const RouteSettings({
this.name,
this.arguments,
});
/// The name of the route (e.g., "/settings").
///
/// If null, the route is anonymous.
final String? name;
/// The arguments passed to this route.
///
/// May be used when building the route, e.g. in [Navigator.onGenerateRoute].
final Object? arguments;
@override
String toString() => '${objectRuntimeType(this, 'RouteSettings')}(${name == null ? 'none' : '"$name"'}, $arguments)';
}
/// Describes the configuration of a [Route].
///
/// The type argument `T` is the corresponding [Route]'s return type, as
/// used by [Route.currentResult], [Route.popped], and [Route.didPop].
///
/// See also:
///
/// * [Navigator.pages], which accepts a list of [Page]s and updates its routes
/// history.
abstract class Page<T> extends RouteSettings {
/// Creates a page and initializes [key] for subclasses.
const Page({
this.key,
super.name,
super.arguments,
this.restorationId,
});
/// The key associated with this page.
///
/// This key will be used for comparing pages in [canUpdate].
final LocalKey? key;
/// Restoration ID to save and restore the state of the [Route] configured by
/// this page.
///
/// If no restoration ID is provided, the [Route] will not restore its state.
///
/// See also:
///
/// * [RestorationManager], which explains how state restoration works in
/// Flutter.
final String? restorationId;
/// Whether this page can be updated with the [other] page.
///
/// Two pages are consider updatable if they have same the [runtimeType] and
/// [key].
bool canUpdate(Page<dynamic> other) {
return other.runtimeType == runtimeType &&
other.key == key;
}
/// Creates the [Route] that corresponds to this page.
///
/// The created [Route] must have its [Route.settings] property set to this [Page].
@factory
Route<T> createRoute(BuildContext context);
@override
String toString() => '${objectRuntimeType(this, 'Page')}("$name", $key, $arguments)';
}
/// An interface for observing the behavior of a [Navigator].
class NavigatorObserver {
/// The navigator that the observer is observing, if any.
NavigatorState? get navigator => _navigators[this];
// Expando mapping instances of NavigatorObserver to their associated
// NavigatorState (or `null`, if there is no associated NavigatorState). The
// reason we don't use a private instance field of type
// `NavigatorState?` is because as part of implementing
// https://github.com/dart-lang/language/issues/2020, it will soon become a
// runtime error to invoke a private member that is mocked in another
// library. By using an expando rather than an instance field, we ensure
// that a mocked NavigatorObserver can still properly keep track of its
// associated NavigatorState.
static final Expando<NavigatorState> _navigators = Expando<NavigatorState>();
/// The [Navigator] pushed `route`.
///
/// The route immediately below that one, and thus the previously active
/// route, is `previousRoute`.
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) { }
/// The [Navigator] popped `route`.
///
/// The route immediately below that one, and thus the newly active
/// route, is `previousRoute`.
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) { }
/// The [Navigator] removed `route`.
///
/// If only one route is being removed, then the route immediately below
/// that one, if any, is `previousRoute`.
///
/// If multiple routes are being removed, then the route below the
/// bottommost route being removed, if any, is `previousRoute`, and this
/// method will be called once for each removed route, from the topmost route
/// to the bottommost route.
void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) { }
/// The [Navigator] replaced `oldRoute` with `newRoute`.
void didReplace({ Route<dynamic>? newRoute, Route<dynamic>? oldRoute }) { }
/// The [Navigator]'s routes are being moved by a user gesture.
///
/// For example, this is called when an iOS back gesture starts, and is used
/// to disabled hero animations during such interactions.
void didStartUserGesture(Route<dynamic> route, Route<dynamic>? previousRoute) { }
/// User gesture is no longer controlling the [Navigator].
///
/// Paired with an earlier call to [didStartUserGesture].
void didStopUserGesture() { }
}
/// An inherited widget to host a hero controller.
///
/// The hosted hero controller will be picked up by the navigator in the
/// [child] subtree. Once a navigator picks up this controller, the navigator
/// will bar any navigator below its subtree from receiving this controller.
///
/// The hero controller inside the [HeroControllerScope] can only subscribe to
/// one navigator at a time. An assertion will be thrown if the hero controller
/// subscribes to more than one navigators. This can happen when there are
/// multiple navigators under the same [HeroControllerScope] in parallel.
class HeroControllerScope extends InheritedWidget {
/// Creates a widget to host the input [controller].
const HeroControllerScope({
super.key,
required HeroController this.controller,
required super.child,
});
/// Creates a widget to prevent the subtree from receiving the hero controller
/// above.
const HeroControllerScope.none({
super.key,
required super.child,
}) : controller = null;
/// The hero controller that is hosted inside this widget.
final HeroController? controller;
/// Retrieves the [HeroController] from the closest [HeroControllerScope]
/// ancestor, or null if none exists.
///
/// Calling this method will create a dependency on the closest
/// [HeroControllerScope] in the [context], if there is one.
///
/// See also:
///
/// * [HeroControllerScope.of], which is similar to this method, but asserts
/// if no [HeroControllerScope] ancestor is found.
static HeroController? maybeOf(BuildContext context) {
final HeroControllerScope? host = context.dependOnInheritedWidgetOfExactType<HeroControllerScope>();
return host?.controller;
}
/// Retrieves the [HeroController] from the closest [HeroControllerScope]
/// ancestor.
///
/// If no ancestor is found, this method will assert in debug mode, and throw
/// an exception in release mode.
///
/// Calling this method will create a dependency on the closest
/// [HeroControllerScope] in the [context].
///
/// See also:
///
/// * [HeroControllerScope.maybeOf], which is similar to this method, but
/// returns null if no [HeroControllerScope] ancestor is found.
static HeroController of(BuildContext context) {
final HeroController? controller = maybeOf(context);
assert(() {
if (controller == null) {
throw FlutterError(
'HeroControllerScope.of() was called with a context that does not contain a '
'HeroControllerScope widget.\n'
'No HeroControllerScope widget ancestor could be found starting from the '
'context that was passed to HeroControllerScope.of(). This can happen '
'because you are using a widget that looks for a HeroControllerScope '
'ancestor, but no such ancestor exists.\n'
'The context used was:\n'
' $context',
);
}
return true;
}());
return controller!;
}
@override
bool updateShouldNotify(HeroControllerScope oldWidget) {
return oldWidget.controller != controller;
}
}
/// A [Route] wrapper interface that can be staged for [TransitionDelegate] to
/// decide how its underlying [Route] should transition on or off screen.
abstract class RouteTransitionRecord {
/// Retrieves the wrapped [Route].
Route<dynamic> get route;
/// Whether this route is waiting for the decision on how to enter the screen.
///
/// If this property is true, this route requires an explicit decision on how
/// to transition into the screen. Such a decision should be made in the
/// [TransitionDelegate.resolve].
bool get isWaitingForEnteringDecision;
/// Whether this route is waiting for the decision on how to exit the screen.
///
/// If this property is true, this route requires an explicit decision on how
/// to transition off the screen. Such a decision should be made in the
/// [TransitionDelegate.resolve].
bool get isWaitingForExitingDecision;
/// Marks the [route] to be pushed with transition.
///
/// During [TransitionDelegate.resolve], this can be called on an entering
/// route (where [RouteTransitionRecord.isWaitingForEnteringDecision] is true) in indicate that the
/// route should be pushed onto the [Navigator] with an animated transition.
void markForPush();
/// Marks the [route] to be added without transition.
///
/// During [TransitionDelegate.resolve], this can be called on an entering
/// route (where [RouteTransitionRecord.isWaitingForEnteringDecision] is true) in indicate that the
/// route should be added onto the [Navigator] without an animated transition.
void markForAdd();
/// Marks the [route] to be popped with transition.
///
/// During [TransitionDelegate.resolve], this can be called on an exiting
/// route to indicate that the route should be popped off the [Navigator] with
/// an animated transition.
void markForPop([dynamic result]);
/// Marks the [route] to be completed without transition.
///
/// During [TransitionDelegate.resolve], this can be called on an exiting
/// route to indicate that the route should be completed with the provided
/// result and removed from the [Navigator] without an animated transition.
void markForComplete([dynamic result]);
/// Marks the [route] to be removed without transition.
///
/// During [TransitionDelegate.resolve], this can be called on an exiting
/// route to indicate that the route should be removed from the [Navigator]
/// without completing and without an animated transition.
void markForRemove();
}
/// The delegate that decides how pages added and removed from [Navigator.pages]
/// transition in or out of the screen.
///
/// This abstract class implements the API to be called by [Navigator] when it
/// requires explicit decisions on how the routes transition on or off the screen.
///
/// To make route transition decisions, subclass must implement [resolve].
///
/// {@tool snippet}
/// The following example demonstrates how to implement a subclass that always
/// removes or adds routes without animated transitions and puts the removed
/// routes at the top of the list.
///
/// ```dart
/// class NoAnimationTransitionDelegate extends TransitionDelegate<void> {
/// @override
/// Iterable<RouteTransitionRecord> resolve({
/// required List<RouteTransitionRecord> newPageRouteHistory,
/// required Map<RouteTransitionRecord?, RouteTransitionRecord> locationToExitingPageRoute,
/// required Map<RouteTransitionRecord?, List<RouteTransitionRecord>> pageRouteToPagelessRoutes,
/// }) {
/// final List<RouteTransitionRecord> results = <RouteTransitionRecord>[];
///
/// for (final RouteTransitionRecord pageRoute in newPageRouteHistory) {
/// if (pageRoute.isWaitingForEnteringDecision) {
/// pageRoute.markForAdd();
/// }
/// results.add(pageRoute);
///
/// }
/// for (final RouteTransitionRecord exitingPageRoute in locationToExitingPageRoute.values) {
/// if (exitingPageRoute.isWaitingForExitingDecision) {
/// exitingPageRoute.markForRemove();
/// final List<RouteTransitionRecord>? pagelessRoutes = pageRouteToPagelessRoutes[exitingPageRoute];
/// if (pagelessRoutes != null) {
/// for (final RouteTransitionRecord pagelessRoute in pagelessRoutes) {
/// pagelessRoute.markForRemove();
/// }
/// }
/// }
/// results.add(exitingPageRoute);
///
/// }
/// return results;
/// }
/// }
///
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [Navigator.transitionDelegate], which uses this class to make route
/// transition decisions.
/// * [DefaultTransitionDelegate], which implements the default way to decide
/// how routes transition in or out of the screen.
abstract class TransitionDelegate<T> {
/// Creates a delegate and enables subclass to create a constant class.
const TransitionDelegate();
Iterable<RouteTransitionRecord> _transition({
required List<RouteTransitionRecord> newPageRouteHistory,
required Map<RouteTransitionRecord?, RouteTransitionRecord> locationToExitingPageRoute,
required Map<RouteTransitionRecord?, List<RouteTransitionRecord>> pageRouteToPagelessRoutes,
}) {
final Iterable<RouteTransitionRecord> results = resolve(
newPageRouteHistory: newPageRouteHistory,
locationToExitingPageRoute: locationToExitingPageRoute,
pageRouteToPagelessRoutes: pageRouteToPagelessRoutes,
);
// Verifies the integrity after the decisions have been made.
//
// Here are the rules:
// - All the entering routes in newPageRouteHistory must either be pushed or
// added.
// - All the exiting routes in locationToExitingPageRoute must either be
// popped, completed or removed.
// - All the pageless routes that belong to exiting routes must either be
// popped, completed or removed.
// - All the entering routes in the result must preserve the same order as
// the entering routes in newPageRouteHistory, and the result must contain
// all exiting routes.
// ex:
//
// newPageRouteHistory = [A, B, C]
//
// locationToExitingPageRoute = {A -> D, C -> E}
//
// results = [A, B ,C ,D ,E] is valid
// results = [D, A, B ,C ,E] is also valid because exiting route can be
// inserted in any place
//
// results = [B, A, C ,D ,E] is invalid because B must be after A.
// results = [A, B, C ,E] is invalid because results must include D.
assert(() {
final List<RouteTransitionRecord> resultsToVerify = results.toList(growable: false);
final Set<RouteTransitionRecord> exitingPageRoutes = locationToExitingPageRoute.values.toSet();
// Firstly, verifies all exiting routes have been marked.
for (final RouteTransitionRecord exitingPageRoute in exitingPageRoutes) {
assert(!exitingPageRoute.isWaitingForExitingDecision);
if (pageRouteToPagelessRoutes.containsKey(exitingPageRoute)) {
for (final RouteTransitionRecord pagelessRoute in pageRouteToPagelessRoutes[exitingPageRoute]!) {
assert(!pagelessRoute.isWaitingForExitingDecision);
}
}
}
// Secondly, verifies the order of results matches the newPageRouteHistory
// and contains all the exiting routes.
int indexOfNextRouteInNewHistory = 0;
for (final _RouteEntry routeEntry in resultsToVerify.cast<_RouteEntry>()) {
assert(!routeEntry.isWaitingForEnteringDecision && !routeEntry.isWaitingForExitingDecision);
if (
indexOfNextRouteInNewHistory >= newPageRouteHistory.length ||
routeEntry != newPageRouteHistory[indexOfNextRouteInNewHistory]
) {
assert(exitingPageRoutes.contains(routeEntry));
exitingPageRoutes.remove(routeEntry);
} else {
indexOfNextRouteInNewHistory += 1;
}
}
assert(
indexOfNextRouteInNewHistory == newPageRouteHistory.length &&
exitingPageRoutes.isEmpty,
'The merged result from the $runtimeType.resolve does not include all '
'required routes. Do you remember to merge all exiting routes?',
);
return true;
}());
return results;
}
/// A method that will be called by the [Navigator] to decide how routes
/// transition in or out of the screen when [Navigator.pages] is updated.
///
/// The `newPageRouteHistory` list contains all page-based routes in the order
/// that will be on the [Navigator]'s history stack after this update
/// completes. If a route in `newPageRouteHistory` has its
/// [RouteTransitionRecord.isWaitingForEnteringDecision] set to true, this
/// route requires explicit decision on how it should transition onto the
/// Navigator. To make a decision, call [RouteTransitionRecord.markForPush] or
/// [RouteTransitionRecord.markForAdd].
///
/// The `locationToExitingPageRoute` contains the pages-based routes that
/// are removed from the routes history after page update. This map records
/// page-based routes to be removed with the location of the route in the
/// original route history before the update. The keys are the locations
/// represented by the page-based routes that are directly below the removed
/// routes, and the value are the page-based routes to be removed. The
/// location is null if the route to be removed is the bottom most route. If
/// a route in `locationToExitingPageRoute` has its
/// [RouteTransitionRecord.isWaitingForExitingDecision] set to true, this
/// route requires explicit decision on how it should transition off the
/// Navigator. To make a decision for a removed route, call
/// [RouteTransitionRecord.markForPop],
/// [RouteTransitionRecord.markForComplete] or
/// [RouteTransitionRecord.markForRemove]. It is possible that decisions are
/// not required for routes in the `locationToExitingPageRoute`. This can
/// happen if the routes have already been popped in earlier page updates and
/// are still waiting for popping animations to finish. In such case, those
/// routes are still included in the `locationToExitingPageRoute` with their
/// [RouteTransitionRecord.isWaitingForExitingDecision] set to false and no
/// decisions are required.
///
/// The `pageRouteToPagelessRoutes` records the page-based routes and their
/// associated pageless routes. If a page-based route is waiting for exiting
/// decision, its associated pageless routes also require explicit decisions
/// on how to transition off the screen.
///
/// Once all the decisions have been made, this method must merge the removed
/// routes (whether or not they require decisions) and the
/// `newPageRouteHistory` and return the merged result. The order in the
/// result will be the order the [Navigator] uses for updating the route
/// history. The return list must preserve the same order of routes in
/// `newPageRouteHistory`. The removed routes, however, can be inserted into
/// the return list freely as long as all of them are included.
///
/// For example, consider the following case.
///
/// `newPageRouteHistory = [A, B, C]`
///
/// `locationToExitingPageRoute = {A -> D, C -> E}`
///
/// The following outputs are valid.
///
/// `result = [A, B ,C ,D ,E]` is valid.
/// `result = [D, A, B ,C ,E]` is also valid because exiting route can be
/// inserted in any place.
///
/// The following outputs are invalid.
///
/// `result = [B, A, C ,D ,E]` is invalid because B must be after A.
/// `result = [A, B, C ,E]` is invalid because results must include D.
///
/// See also:
///
/// * [RouteTransitionRecord.markForPush], which makes route enter the screen
/// with an animated transition.
/// * [RouteTransitionRecord.markForAdd], which makes route enter the screen
/// without an animated transition.
/// * [RouteTransitionRecord.markForPop], which makes route exit the screen
/// with an animated transition.
/// * [RouteTransitionRecord.markForRemove], which does not complete the
/// route and makes it exit the screen without an animated transition.
/// * [RouteTransitionRecord.markForComplete], which completes the route and
/// makes it exit the screen without an animated transition.
/// * [DefaultTransitionDelegate.resolve], which implements the default way
/// to decide how routes transition in or out of the screen.
Iterable<RouteTransitionRecord> resolve({
required List<RouteTransitionRecord> newPageRouteHistory,
required Map<RouteTransitionRecord?, RouteTransitionRecord> locationToExitingPageRoute,
required Map<RouteTransitionRecord?, List<RouteTransitionRecord>> pageRouteToPagelessRoutes,
});
}
/// The default implementation of [TransitionDelegate] that the [Navigator] will
/// use if its [Navigator.transitionDelegate] is not specified.
///
/// This transition delegate follows two rules. Firstly, all the entering routes
/// are placed on top of the exiting routes if they are at the same location.
/// Secondly, the top most route will always transition with an animated transition.
/// All the other routes below will either be completed with
/// [Route.currentResult] or added without an animated transition.
class DefaultTransitionDelegate<T> extends TransitionDelegate<T> {
/// Creates a default transition delegate.
const DefaultTransitionDelegate() : super();
@override
Iterable<RouteTransitionRecord> resolve({
required List<RouteTransitionRecord> newPageRouteHistory,
required Map<RouteTransitionRecord?, RouteTransitionRecord> locationToExitingPageRoute,
required Map<RouteTransitionRecord?, List<RouteTransitionRecord>> pageRouteToPagelessRoutes,
}) {
final List<RouteTransitionRecord> results = <RouteTransitionRecord>[];
// This method will handle the exiting route and its corresponding pageless
// route at this location. It will also recursively check if there is any
// other exiting routes above it and handle them accordingly.
void handleExitingRoute(RouteTransitionRecord? location, bool isLast) {
final RouteTransitionRecord? exitingPageRoute = locationToExitingPageRoute[location];
if (exitingPageRoute == null) {
return;
}
if (exitingPageRoute.isWaitingForExitingDecision) {
final bool hasPagelessRoute = pageRouteToPagelessRoutes.containsKey(exitingPageRoute);
final bool isLastExitingPageRoute = isLast && !locationToExitingPageRoute.containsKey(exitingPageRoute);
if (isLastExitingPageRoute && !hasPagelessRoute) {
exitingPageRoute.markForPop(exitingPageRoute.route.currentResult);
} else {
exitingPageRoute.markForComplete(exitingPageRoute.route.currentResult);
}
if (hasPagelessRoute) {
final List<RouteTransitionRecord> pagelessRoutes = pageRouteToPagelessRoutes[exitingPageRoute]!;
for (final RouteTransitionRecord pagelessRoute in pagelessRoutes) {
// It is possible that a pageless route that belongs to an exiting
// page-based route does not require exiting decision. This can
// happen if the page list is updated right after a Navigator.pop.
if (pagelessRoute.isWaitingForExitingDecision) {
if (isLastExitingPageRoute && pagelessRoute == pagelessRoutes.last) {
pagelessRoute.markForPop(pagelessRoute.route.currentResult);
} else {
pagelessRoute.markForComplete(pagelessRoute.route.currentResult);
}
}
}
}
}
results.add(exitingPageRoute);
// It is possible there is another exiting route above this exitingPageRoute.
handleExitingRoute(exitingPageRoute, isLast);
}
// Handles exiting route in the beginning of list.
handleExitingRoute(null, newPageRouteHistory.isEmpty);
for (final RouteTransitionRecord pageRoute in newPageRouteHistory) {
final bool isLastIteration = newPageRouteHistory.last == pageRoute;
if (pageRoute.isWaitingForEnteringDecision) {
if (!locationToExitingPageRoute.containsKey(pageRoute) && isLastIteration) {
pageRoute.markForPush();
} else {
pageRoute.markForAdd();
}
}
results.add(pageRoute);
handleExitingRoute(pageRoute, isLastIteration);
}
return results;
}
}
/// The default value of [Navigator.routeTraversalEdgeBehavior].
///
/// {@macro flutter.widgets.navigator.routeTraversalEdgeBehavior}
const TraversalEdgeBehavior kDefaultRouteTraversalEdgeBehavior = TraversalEdgeBehavior.parentScope;
/// A widget that manages a set of child widgets with a stack discipline.
///
/// Many apps have a navigator near the top of their widget hierarchy in order
/// to display their logical history using an [Overlay] with the most recently
/// visited pages visually on top of the older pages. Using this pattern lets
/// the navigator visually transition from one page to another by moving the widgets
/// around in the overlay. Similarly, the navigator can be used to show a dialog
/// by positioning the dialog widget above the current page.
///
/// ## Using the Pages API
///
/// The [Navigator] will convert its [Navigator.pages] into a stack of [Route]s
/// if it is provided. A change in [Navigator.pages] will trigger an update to
/// the stack of [Route]s. The [Navigator] will update its routes to match the
/// new configuration of its [Navigator.pages]. To use this API, one can create
/// a [Page] subclass and defines a list of [Page]s for [Navigator.pages]. A
/// [Navigator.onPopPage] callback is also required to properly clean up the
/// input pages in case of a pop.
///
/// By Default, the [Navigator] will use [DefaultTransitionDelegate] to decide
/// how routes transition in or out of the screen. To customize it, define a
/// [TransitionDelegate] subclass and provide it to the
/// [Navigator.transitionDelegate].
///
/// For more information on using the pages API, see the [Router] widget.
///
/// ## Using the Navigator API
///
/// Mobile apps typically reveal their contents via full-screen elements
/// called "screens" or "pages". In Flutter these elements are called
/// routes and they're managed by a [Navigator] widget. The navigator
/// manages a stack of [Route] objects and provides two ways for managing
/// the stack, the declarative API [Navigator.pages] or imperative API
/// [Navigator.push] and [Navigator.pop].
///
/// When your user interface fits this paradigm of a stack, where the user
/// should be able to _navigate_ back to an earlier element in the stack,
/// the use of routes and the Navigator is appropriate. On certain platforms,
/// such as Android, the system UI will provide a back button (outside the
/// bounds of your application) that will allow the user to navigate back
/// to earlier routes in your application's stack. On platforms that don't
/// have this build-in navigation mechanism, the use of an [AppBar] (typically
/// used in the [Scaffold.appBar] property) can automatically add a back
/// button for user navigation.
///
/// ### Displaying a full-screen route
///
/// Although you can create a navigator directly, it's most common to use the
/// navigator created by the `Router` which itself is created and configured by
/// a [WidgetsApp] or a [MaterialApp] widget. You can refer to that navigator
/// with [Navigator.of].
///
/// A [MaterialApp] is the simplest way to set things up. The [MaterialApp]'s
/// home becomes the route at the bottom of the [Navigator]'s stack. It is what
/// you see when the app is launched.
///
/// ```dart
/// void main() {
/// runApp(const MaterialApp(home: MyAppHome()));
/// }
/// ```
///
/// To push a new route on the stack you can create an instance of
/// [MaterialPageRoute] with a builder function that creates whatever you
/// want to appear on the screen. For example:
///
/// ```dart
/// Navigator.push(context, MaterialPageRoute<void>(
/// builder: (BuildContext context) {
/// return Scaffold(
/// appBar: AppBar(title: const Text('My Page')),
/// body: Center(
/// child: TextButton(
/// child: const Text('POP'),
/// onPressed: () {
/// Navigator.pop(context);
/// },
/// ),
/// ),
/// );
/// },
/// ));
/// ```
///
/// The route defines its widget with a builder function instead of a
/// child widget because it will be built and rebuilt in different
/// contexts depending on when it's pushed and popped.
///
/// As you can see, the new route can be popped, revealing the app's home
/// page, with the Navigator's pop method:
///
/// ```dart
/// Navigator.pop(context);
/// ```
///
/// It usually isn't necessary to provide a widget that pops the Navigator
/// in a route with a [Scaffold] because the Scaffold automatically adds a
/// 'back' button to its AppBar. Pressing the back button causes
/// [Navigator.pop] to be called. On Android, pressing the system back
/// button does the same thing.
///
/// ### Using named navigator routes
///
/// Mobile apps often manage a large number of routes and it's often
/// easiest to refer to them by name. Route names, by convention,
/// use a path-like structure (for example, '/a/b/c').
/// The app's home page route is named '/' by default.
///
/// The [MaterialApp] can be created
/// with a [Map<String, WidgetBuilder>] which maps from a route's name to
/// a builder function that will create it. The [MaterialApp] uses this
/// map to create a value for its navigator's [onGenerateRoute] callback.
///
/// ```dart
/// void main() {
/// runApp(MaterialApp(
/// home: const MyAppHome(), // becomes the route named '/'
/// routes: <String, WidgetBuilder> {
/// '/a': (BuildContext context) => const MyPage(title: Text('page A')),
/// '/b': (BuildContext context) => const MyPage(title: Text('page B')),
/// '/c': (BuildContext context) => const MyPage(title: Text('page C')),
/// },
/// ));
/// }
/// ```
///
/// To show a route by name:
///
/// ```dart
/// Navigator.pushNamed(context, '/b');
/// ```
///
/// ### Routes can return a value
///
/// When a route is pushed to ask the user for a value, the value can be
/// returned via the [pop] method's result parameter.
///
/// Methods that push a route return a [Future]. The Future resolves when the
/// route is popped and the [Future]'s value is the [pop] method's `result`
/// parameter.
///
/// For example if we wanted to ask the user to press 'OK' to confirm an
/// operation we could `await` the result of [Navigator.push]:
///
/// ```dart
/// bool? value = await Navigator.push(context, MaterialPageRoute<bool>(
/// builder: (BuildContext context) {
/// return Center(
/// child: GestureDetector(
/// child: const Text('OK'),
/// onTap: () { Navigator.pop(context, true); }
/// ),
/// );
/// }
/// ));
/// ```
///
/// If the user presses 'OK' then value will be true. If the user backs
/// out of the route, for example by pressing the Scaffold's back button,
/// the value will be null.
///
/// When a route is used to return a value, the route's type parameter must
/// match the type of [pop]'s result. That's why we've used
/// `MaterialPageRoute<bool>` instead of `MaterialPageRoute<void>` or just
/// `MaterialPageRoute`. (If you prefer to not specify the types, though, that's
/// fine too.)
///
/// ### Popup routes
///
/// Routes don't have to obscure the entire screen. [PopupRoute]s cover the
/// screen with a [ModalRoute.barrierColor] that can be only partially opaque to
/// allow the current screen to show through. Popup routes are "modal" because
/// they block input to the widgets below.
///
/// There are functions which create and show popup routes. For
/// example: [showDialog], [showMenu], and [showModalBottomSheet]. These
/// functions return their pushed route's Future as described above.
/// Callers can await the returned value to take an action when the
/// route is popped, or to discover the route's value.
///
/// There are also widgets which create popup routes, like [PopupMenuButton] and
/// [DropdownButton]. These widgets create internal subclasses of PopupRoute
/// and use the Navigator's push and pop methods to show and dismiss them.
///
/// ### Custom routes
///
/// You can create your own subclass of one of the widget library route classes
/// like [PopupRoute], [ModalRoute], or [PageRoute], to control the animated
/// transition employed to show the route, the color and behavior of the route's
/// modal barrier, and other aspects of the route.
///
/// The [PageRouteBuilder] class makes it possible to define a custom route
/// in terms of callbacks. Here's an example that rotates and fades its child
/// when the route appears or disappears. This route does not obscure the entire
/// screen because it specifies `opaque: false`, just as a popup route does.
///
/// ```dart
/// Navigator.push(context, PageRouteBuilder<void>(
/// opaque: false,
/// pageBuilder: (BuildContext context, _, __) {
/// return const Center(child: Text('My PageRoute'));
/// },
/// transitionsBuilder: (___, Animation<double> animation, ____, Widget child) {
/// return FadeTransition(
/// opacity: animation,
/// child: RotationTransition(
/// turns: Tween<double>(begin: 0.5, end: 1.0).animate(animation),
/// child: child,
/// ),
/// );
/// }
/// ));
/// ```
///
/// The page route is built in two parts, the "page" and the
/// "transitions". The page becomes a descendant of the child passed to
/// the `transitionsBuilder` function. Typically the page is only built once,
/// because it doesn't depend on its animation parameters (elided with `_`
/// and `__` in this example). The transition is built on every frame
/// for its duration.
///
/// (In this example, `void` is used as the return type for the route, because
/// it does not return a value.)
///
/// ### Nesting Navigators
///
/// An app can use more than one [Navigator]. Nesting one [Navigator] below
/// another [Navigator] can be used to create an "inner journey" such as tabbed
/// navigation, user registration, store checkout, or other independent journeys
/// that represent a subsection of your overall application.
///
/// #### Example
///
/// It is standard practice for iOS apps to use tabbed navigation where each
/// tab maintains its own navigation history. Therefore, each tab has its own
/// [Navigator], creating a kind of "parallel navigation."
///
/// In addition to the parallel navigation of the tabs, it is still possible to
/// launch full-screen pages that completely cover the tabs. For example: an
/// on-boarding flow, or an alert dialog. Therefore, there must exist a "root"
/// [Navigator] that sits above the tab navigation. As a result, each of the
/// tab's [Navigator]s are actually nested [Navigator]s sitting below a single
/// root [Navigator].
///
/// In practice, the nested [Navigator]s for tabbed navigation sit in the
/// [WidgetsApp] and [CupertinoTabView] widgets and do not need to be explicitly
/// created or managed.
///
/// {@tool sample}
/// The following example demonstrates how a nested [Navigator] can be used to
/// present a standalone user registration journey.
///
/// Even though this example uses two [Navigator]s to demonstrate nested
/// [Navigator]s, a similar result is possible using only a single [Navigator].
///
/// Run this example with `flutter run --route=/signup` to start it with
/// the signup flow instead of on the home page.
///
/// ** See code in examples/api/lib/widgets/navigator/navigator.0.dart **
/// {@end-tool}
///
/// [Navigator.of] operates on the nearest ancestor [Navigator] from the given
/// [BuildContext]. Be sure to provide a [BuildContext] below the intended
/// [Navigator], especially in large `build` methods where nested [Navigator]s
/// are created. The [Builder] widget can be used to access a [BuildContext] at
/// a desired location in the widget subtree.
///
/// ### Finding the enclosing route
///
/// In the common case of a modal route, the enclosing route can be obtained
/// from inside a build method using [ModalRoute.of]. To determine if the
/// enclosing route is the active route (e.g. so that controls can be dimmed
/// when the route is not active), the [Route.isCurrent] property can be checked
/// on the returned route.
///
/// ## State Restoration
///
/// If provided with a [restorationScopeId] and when surrounded by a valid
/// [RestorationScope] the [Navigator] will restore its state by recreating
/// the current history stack of [Route]s during state restoration and by
/// restoring the internal state of those [Route]s. However, not all [Route]s
/// on the stack can be restored:
///
/// * [Page]-based routes restore their state if [Page.restorationId] is
/// provided.
/// * [Route]s added with the classic imperative API ([push], [pushNamed], and
/// friends) can never restore their state.
/// * A [Route] added with the restorable imperative API ([restorablePush],
/// [restorablePushNamed], and all other imperative methods with "restorable"
/// in their name) restores its state if all routes below it up to and
/// including the first [Page]-based route below it are restored. If there
/// is no [Page]-based route below it, it only restores its state if all
/// routes below it restore theirs.
///
/// If a [Route] is deemed restorable, the [Navigator] will set its
/// [Route.restorationScopeId] to a non-null value. Routes can use that ID to
/// store and restore their own state. As an example, the [ModalRoute] will
/// use this ID to create a [RestorationScope] for its content widgets.
class Navigator extends StatefulWidget {
/// Creates a widget that maintains a stack-based history of child widgets.
///
/// If the [pages] is not empty, the [onPopPage] must not be null.
const Navigator({
super.key,
this.pages = const <Page<dynamic>>[],
this.onPopPage,
this.initialRoute,
this.onGenerateInitialRoutes = Navigator.defaultGenerateInitialRoutes,
this.onGenerateRoute,
this.onUnknownRoute,
this.transitionDelegate = const DefaultTransitionDelegate<dynamic>(),
this.reportsRouteUpdateToEngine = false,
this.clipBehavior = Clip.hardEdge,
this.observers = const <NavigatorObserver>[],
this.requestFocus = true,
this.restorationScopeId,
this.routeTraversalEdgeBehavior = kDefaultRouteTraversalEdgeBehavior,
});
/// The list of pages with which to populate the history.
///
/// Pages are turned into routes using [Page.createRoute] in a manner
/// analogous to how [Widget]s are turned into [Element]s (and [State]s or
/// [RenderObject]s) using [Widget.createElement] (and
/// [StatefulWidget.createState] or [RenderObjectWidget.createRenderObject]).
///
/// When this list is updated, the new list is compared to the previous
/// list and the set of routes is updated accordingly.
///
/// Some [Route]s do not correspond to [Page] objects, namely, those that are
/// added to the history using the [Navigator] API ([push] and friends). A
/// [Route] that does not correspond to a [Page] object is called a pageless
/// route and is tied to the [Route] that _does_ correspond to a [Page] object
/// that is below it in the history.
///
/// Pages that are added or removed may be animated as controlled by the
/// [transitionDelegate]. If a page is removed that had other pageless routes
/// pushed on top of it using [push] and friends, those pageless routes are
/// also removed with or without animation as determined by the
/// [transitionDelegate].
///
/// To use this API, an [onPopPage] callback must also be provided to properly
/// clean up this list if a page has been popped.
///
/// If [initialRoute] is non-null when the widget is first created, then
/// [onGenerateInitialRoutes] is used to generate routes that are above those
/// corresponding to [pages] in the initial history.
final List<Page<dynamic>> pages;
/// Called when [pop] is invoked but the current [Route] corresponds to a
/// [Page] found in the [pages] list.
///
/// The `result` argument is the value with which the route is to complete
/// (e.g. the value returned from a dialog).
///
/// This callback is responsible for calling [Route.didPop] and returning
/// whether this pop is successful.
///
/// The [Navigator] widget should be rebuilt with a [pages] list that does not
/// contain the [Page] for the given [Route]. The next time the [pages] list
/// is updated, if the [Page] corresponding to this [Route] is still present,
/// it will be interpreted as a new route to display.
final PopPageCallback? onPopPage;
/// The delegate used for deciding how routes transition in or off the screen
/// during the [pages] updates.
///
/// Defaults to [DefaultTransitionDelegate].
final TransitionDelegate<dynamic> transitionDelegate;
/// The name of the first route to show.
///
/// Defaults to [Navigator.defaultRouteName].
///
/// The value is interpreted according to [onGenerateInitialRoutes], which
/// defaults to [defaultGenerateInitialRoutes].
///
/// Changing the [initialRoute] will have no effect, as it only controls the
/// _initial_ route. To change the route while the application is running, use
/// the static functions on this class, such as [push] or [replace].
final String? initialRoute;
/// Called to generate a route for a given [RouteSettings].
final RouteFactory? onGenerateRoute;
/// Called when [onGenerateRoute] fails to generate a route.
///
/// This callback is typically used for error handling. For example, this
/// callback might always generate a "not found" page that describes the route
/// that wasn't found.
///
/// Unknown routes can arise either from errors in the app or from external
/// requests to push routes, such as from Android intents.
final RouteFactory? onUnknownRoute;
/// A list of observers for this navigator.
final List<NavigatorObserver> observers;
/// Restoration ID to save and restore the state of the navigator, including
/// its history.
///
/// {@template flutter.widgets.navigator.restorationScopeId}
/// If a restoration ID is provided, the navigator will persist its internal
/// state (including the route history as well as the restorable state of the
/// routes) and restore it during state restoration.
///
/// If no restoration ID is provided, the route history stack will not be
/// restored and state restoration is disabled for the individual routes as
/// well.
///
/// The state is persisted in a [RestorationBucket] claimed from
/// the surrounding [RestorationScope] using the provided restoration ID.
/// Within that bucket, the [Navigator] also creates a new [RestorationScope]
/// for its children (the [Route]s).
///
/// See also:
///
/// * [RestorationManager], which explains how state restoration works in
/// Flutter.
/// * [RestorationMixin], which contains a runnable code sample showcasing
/// state restoration in Flutter.
/// * [Navigator], which explains under the heading "state restoration"
/// how and under what conditions the navigator restores its state.
/// * [Navigator.restorablePush], which includes an example showcasing how
/// to push a restorable route unto the navigator.
/// {@endtemplate}
final String? restorationScopeId;
/// Controls the transfer of focus beyond the first and the last items of a
/// focus scope that defines focus traversal of widgets within a route.
///
/// {@template flutter.widgets.navigator.routeTraversalEdgeBehavior}
/// The focus inside routes installed in the top of the app affects how
/// the app behaves with respect to the platform content surrounding it.
/// For example, on the web, an app is at a minimum surrounded by browser UI,
/// such as the address bar, browser tabs, and more. The user should be able
/// to reach browser UI using normal focus shortcuts. Similarly, if the app
/// is embedded within an `<iframe>` or inside a custom element, it should
/// be able to participate in the overall focus traversal, including elements
/// not rendered by Flutter.
/// {@endtemplate}
final TraversalEdgeBehavior routeTraversalEdgeBehavior;
/// The name for the default route of the application.
///
/// See also:
///
/// * [dart:ui.PlatformDispatcher.defaultRouteName], which reflects the route that the
/// application was started with.
static const String defaultRouteName = '/';
/// Called when the widget is created to generate the initial list of [Route]
/// objects if [initialRoute] is not null.
///
/// Defaults to [defaultGenerateInitialRoutes].
///
/// The [NavigatorState] and [initialRoute] will be passed to the callback.
/// The callback must return a list of [Route] objects with which the history
/// will be primed.
///
/// When parsing the initialRoute, if there's any chance that the it may
/// contain complex characters, it's best to use the
/// [characters](https://pub.dev/packages/characters) API. This will ensure
/// that extended grapheme clusters and surrogate pairs are treated as single
/// characters by the code, the same way that they appear to the user. For
/// example, the string "👨👩👦" appears to the user as a single
/// character and `string.characters.length` intuitively returns 1. On the
/// other hand, `string.length` returns 8, and `string.runes.length` returns
/// 5!
final RouteListFactory onGenerateInitialRoutes;
/// Whether this navigator should report route update message back to the
/// engine when the top-most route changes.
///
/// If the property is set to true, this navigator automatically sends the
/// route update message to the engine when it detects top-most route changes.
/// The messages are used by the web engine to update the browser URL bar.
///
/// If the property is set to true when the [Navigator] is first created,
/// single-entry history mode is requested using
/// [SystemNavigator.selectSingleEntryHistory]. This means this property
/// should not be used at the same time as [PlatformRouteInformationProvider]
/// is used with a [Router] (including when used with [MaterialApp.router],
/// for example).
///
/// If there are multiple navigators in the widget tree, at most one of them
/// can set this property to true (typically, the top-most one created from
/// the [WidgetsApp]). Otherwise, the web engine may receive multiple route
/// update messages from different navigators and fail to update the URL
/// bar.
///
/// Defaults to false.
final bool reportsRouteUpdateToEngine;
/// {@macro flutter.material.Material.clipBehavior}
///
/// In cases where clipping is not desired, consider setting this property to
/// [Clip.none].
///
/// Defaults to [Clip.hardEdge].
final Clip clipBehavior;
/// Whether or not the navigator and it's new topmost route should request focus
/// when the new route is pushed onto the navigator.
///
/// Defaults to true.
final bool requestFocus;
/// Push a named route onto the navigator that most tightly encloses the given
/// context.
///
/// {@template flutter.widgets.navigator.pushNamed}
/// The route name will be passed to the [Navigator.onGenerateRoute]
/// callback. The returned route will be pushed into the navigator.
///
/// The new route and the previous route (if any) are notified (see
/// [Route.didPush] and [Route.didChangeNext]). If the [Navigator] has any
/// [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didPush]).
///
/// Ongoing gestures within the current route are canceled when a new route is
/// pushed.
///
/// The `T` type argument is the type of the return value of the route.
///
/// To use [pushNamed], an [Navigator.onGenerateRoute] callback must be
/// provided,
/// {@endtemplate}
///
/// {@template flutter.widgets.navigator.pushNamed.returnValue}
/// Returns a [Future] that completes to the `result` value passed to [pop]
/// when the pushed route is popped off the navigator.
/// {@endtemplate}
///
/// {@template flutter.widgets.Navigator.pushNamed}
/// The provided `arguments` are passed to the pushed route via
/// [RouteSettings.arguments]. Any object can be passed as `arguments` (e.g. a
/// [String], [int], or an instance of a custom `MyRouteArguments` class).
/// Often, a [Map] is used to pass key-value pairs.
///
/// The `arguments` may be used in [Navigator.onGenerateRoute] or
/// [Navigator.onUnknownRoute] to construct the route.
/// {@endtemplate}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _didPushButton() {
/// Navigator.pushNamed(context, '/settings');
/// }
/// ```
/// {@end-tool}
///
/// {@tool snippet}
///
/// The following example shows how to pass additional `arguments` to the
/// route:
///
/// ```dart
/// void _showBerlinWeather() {
/// Navigator.pushNamed(
/// context,
/// '/weather',
/// arguments: <String, String>{
/// 'city': 'Berlin',
/// 'country': 'Germany',
/// },
/// );
/// }
/// ```
/// {@end-tool}
///
/// {@tool snippet}
///
/// The following example shows how to pass a custom Object to the route:
///
/// ```dart
/// class WeatherRouteArguments {
/// WeatherRouteArguments({ required this.city, required this.country });
/// final String city;
/// final String country;
///
/// bool get isGermanCapital {
/// return country == 'Germany' && city == 'Berlin';
/// }
/// }
///
/// void _showWeather() {
/// Navigator.pushNamed(
/// context,
/// '/weather',
/// arguments: WeatherRouteArguments(city: 'Berlin', country: 'Germany'),
/// );
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePushNamed], which pushes a route that can be restored
/// during state restoration.
@optionalTypeArgs
static Future<T?> pushNamed<T extends Object?>(
BuildContext context,
String routeName, {
Object? arguments,
}) {
return Navigator.of(context).pushNamed<T>(routeName, arguments: arguments);
}
/// Push a named route onto the navigator that most tightly encloses the given
/// context.
///
/// {@template flutter.widgets.navigator.restorablePushNamed}
/// Unlike [Route]s pushed via [pushNamed], [Route]s pushed with this method
/// are restored during state restoration according to the rules outlined
/// in the "State Restoration" section of [Navigator].
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.pushNamed}
///
/// {@template flutter.widgets.Navigator.restorablePushNamed.arguments}
/// The provided `arguments` are passed to the pushed route via
/// [RouteSettings.arguments]. Any object that is serializable via the
/// [StandardMessageCodec] can be passed as `arguments`. Often, a Map is used
/// to pass key-value pairs.
///
/// The arguments may be used in [Navigator.onGenerateRoute] or
/// [Navigator.onUnknownRoute] to construct the route.
/// {@endtemplate}
///
/// {@template flutter.widgets.Navigator.restorablePushNamed.returnValue}
/// The method returns an opaque ID for the pushed route that can be used by
/// the [RestorableRouteFuture] to gain access to the actual [Route] object
/// added to the navigator and its return value. You can ignore the return
/// value of this method, if you do not care about the route object or the
/// route's return value.
/// {@endtemplate}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _showParisWeather() {
/// Navigator.restorablePushNamed(
/// context,
/// '/weather',
/// arguments: <String, String>{
/// 'city': 'Paris',
/// 'country': 'France',
/// },
/// );
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
static String restorablePushNamed<T extends Object?>(
BuildContext context,
String routeName, {
Object? arguments,
}) {
return Navigator.of(context).restorablePushNamed<T>(routeName, arguments: arguments);
}
/// Replace the current route of the navigator that most tightly encloses the
/// given context by pushing the route named [routeName] and then disposing
/// the previous route once the new route has finished animating in.
///
/// {@template flutter.widgets.navigator.pushReplacementNamed}
/// If non-null, `result` will be used as the result of the route that is
/// removed; the future that had been returned from pushing that old route
/// will complete with `result`. Routes such as dialogs or popup menus
/// typically use this mechanism to return the value selected by the user to
/// the widget that created their route. The type of `result`, if provided,
/// must match the type argument of the class of the old route (`TO`).
///
/// The route name will be passed to the [Navigator.onGenerateRoute]
/// callback. The returned route will be pushed into the navigator.
///
/// The new route and the route below the removed route are notified (see
/// [Route.didPush] and [Route.didChangeNext]). If the [Navigator] has any
/// [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didReplace]). The removed route is notified once the
/// new route has finished animating (see [Route.didComplete]). The removed
/// route's exit animation is not run (see [popAndPushNamed] for a variant
/// that does animated the removed route).
///
/// Ongoing gestures within the current route are canceled when a new route is
/// pushed.
///
/// The `T` type argument is the type of the return value of the new route,
/// and `TO` is the type of the return value of the old route.
///
/// To use [pushReplacementNamed], a [Navigator.onGenerateRoute] callback must
/// be provided.
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.pushNamed.returnValue}
///
/// {@macro flutter.widgets.Navigator.pushNamed}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _switchToBrightness() {
/// Navigator.pushReplacementNamed(context, '/settings/brightness');
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePushReplacementNamed], which pushes a replacement route that
/// can be restored during state restoration.
@optionalTypeArgs
static Future<T?> pushReplacementNamed<T extends Object?, TO extends Object?>(
BuildContext context,
String routeName, {
TO? result,
Object? arguments,
}) {
return Navigator.of(context).pushReplacementNamed<T, TO>(routeName, arguments: arguments, result: result);
}
/// Replace the current route of the navigator that most tightly encloses the
/// given context by pushing the route named [routeName] and then disposing
/// the previous route once the new route has finished animating in.
///
/// {@template flutter.widgets.navigator.restorablePushReplacementNamed}
/// Unlike [Route]s pushed via [pushReplacementNamed], [Route]s pushed with
/// this method are restored during state restoration according to the rules
/// outlined in the "State Restoration" section of [Navigator].
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.pushReplacementNamed}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.arguments}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _switchToAudioVolume() {
/// Navigator.restorablePushReplacementNamed(context, '/settings/volume');
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
static String restorablePushReplacementNamed<T extends Object?, TO extends Object?>(
BuildContext context,
String routeName, {
TO? result,
Object? arguments,
}) {
return Navigator.of(context).restorablePushReplacementNamed<T, TO>(routeName, arguments: arguments, result: result);
}
/// Pop the current route off the navigator that most tightly encloses the
/// given context and push a named route in its place.
///
/// {@template flutter.widgets.navigator.popAndPushNamed}
/// The popping of the previous route is handled as per [pop].
///
/// The new route's name will be passed to the [Navigator.onGenerateRoute]
/// callback. The returned route will be pushed into the navigator.
///
/// The new route, the old route, and the route below the old route (if any)
/// are all notified (see [Route.didPop], [Route.didComplete],
/// [Route.didPopNext], [Route.didPush], and [Route.didChangeNext]). If the
/// [Navigator] has any [Navigator.observers], they will be notified as well
/// (see [NavigatorObserver.didPop] and [NavigatorObserver.didPush]). The
/// animations for the pop and the push are performed simultaneously, so the
/// route below may be briefly visible even if both the old route and the new
/// route are opaque (see [TransitionRoute.opaque]).
///
/// Ongoing gestures within the current route are canceled when a new route is
/// pushed.
///
/// The `T` type argument is the type of the return value of the new route,
/// and `TO` is the return value type of the old route.
///
/// To use [popAndPushNamed], a [Navigator.onGenerateRoute] callback must be provided.
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.pushNamed.returnValue}
///
/// {@macro flutter.widgets.Navigator.pushNamed}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _selectAccessibility() {
/// Navigator.popAndPushNamed(context, '/settings/accessibility');
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePopAndPushNamed], which pushes a new route that can be
/// restored during state restoration.
@optionalTypeArgs
static Future<T?> popAndPushNamed<T extends Object?, TO extends Object?>(
BuildContext context,
String routeName, {
TO? result,
Object? arguments,
}) {
return Navigator.of(context).popAndPushNamed<T, TO>(routeName, arguments: arguments, result: result);
}
/// Pop the current route off the navigator that most tightly encloses the
/// given context and push a named route in its place.
///
/// {@template flutter.widgets.navigator.restorablePopAndPushNamed}
/// Unlike [Route]s pushed via [popAndPushNamed], [Route]s pushed with
/// this method are restored during state restoration according to the rules
/// outlined in the "State Restoration" section of [Navigator].
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.popAndPushNamed}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.arguments}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _selectNetwork() {
/// Navigator.restorablePopAndPushNamed(context, '/settings/network');
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
static String restorablePopAndPushNamed<T extends Object?, TO extends Object?>(
BuildContext context,
String routeName, {
TO? result,
Object? arguments,
}) {
return Navigator.of(context).restorablePopAndPushNamed<T, TO>(routeName, arguments: arguments, result: result);
}
/// Push the route with the given name onto the navigator that most tightly
/// encloses the given context, and then remove all the previous routes until
/// the `predicate` returns true.
///
/// {@template flutter.widgets.navigator.pushNamedAndRemoveUntil}
/// The predicate may be applied to the same route more than once if
/// [Route.willHandlePopInternally] is true.
///
/// To remove routes until a route with a certain name, use the
/// [RoutePredicate] returned from [ModalRoute.withName].
///
/// To remove all the routes below the pushed route, use a [RoutePredicate]
/// that always returns false (e.g. `(Route<dynamic> route) => false`).
///
/// The removed routes are removed without being completed, so this method
/// does not take a return value argument.
///
/// The new route's name (`routeName`) will be passed to the
/// [Navigator.onGenerateRoute] callback. The returned route will be pushed
/// into the navigator.
///
/// The new route and the route below the bottommost removed route (which
/// becomes the route below the new route) are notified (see [Route.didPush]
/// and [Route.didChangeNext]). If the [Navigator] has any
/// [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didPush] and [NavigatorObserver.didRemove]). The
/// removed routes are disposed, without being notified, once the new route
/// has finished animating. The futures that had been returned from pushing
/// those routes will not complete.
///
/// Ongoing gestures within the current route are canceled when a new route is
/// pushed.
///
/// The `T` type argument is the type of the return value of the new route.
///
/// To use [pushNamedAndRemoveUntil], an [Navigator.onGenerateRoute] callback
/// must be provided.
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.pushNamed.returnValue}
///
/// {@macro flutter.widgets.Navigator.pushNamed}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _resetToCalendar() {
/// Navigator.pushNamedAndRemoveUntil(context, '/calendar', ModalRoute.withName('/'));
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePushNamedAndRemoveUntil], which pushes a new route that can
/// be restored during state restoration.
@optionalTypeArgs
static Future<T?> pushNamedAndRemoveUntil<T extends Object?>(
BuildContext context,
String newRouteName,
RoutePredicate predicate, {
Object? arguments,
}) {
return Navigator.of(context).pushNamedAndRemoveUntil<T>(newRouteName, predicate, arguments: arguments);
}
/// Push the route with the given name onto the navigator that most tightly
/// encloses the given context, and then remove all the previous routes until
/// the `predicate` returns true.
///
/// {@template flutter.widgets.navigator.restorablePushNamedAndRemoveUntil}
/// Unlike [Route]s pushed via [pushNamedAndRemoveUntil], [Route]s pushed with
/// this method are restored during state restoration according to the rules
/// outlined in the "State Restoration" section of [Navigator].
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.pushNamedAndRemoveUntil}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.arguments}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _resetToOverview() {
/// Navigator.restorablePushNamedAndRemoveUntil(context, '/overview', ModalRoute.withName('/'));
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
static String restorablePushNamedAndRemoveUntil<T extends Object?>(
BuildContext context,
String newRouteName,
RoutePredicate predicate, {
Object? arguments,
}) {
return Navigator.of(context).restorablePushNamedAndRemoveUntil<T>(newRouteName, predicate, arguments: arguments);
}
/// Push the given route onto the navigator that most tightly encloses the
/// given context.
///
/// {@template flutter.widgets.navigator.push}
/// The new route and the previous route (if any) are notified (see
/// [Route.didPush] and [Route.didChangeNext]). If the [Navigator] has any
/// [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didPush]).
///
/// Ongoing gestures within the current route are canceled when a new route is
/// pushed.
///
/// The `T` type argument is the type of the return value of the route.
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.pushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _openMyPage() {
/// Navigator.push<void>(
/// context,
/// MaterialPageRoute<void>(
/// builder: (BuildContext context) => const MyPage(),
/// ),
/// );
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePush], which pushes a route that can be restored during
/// state restoration.
@optionalTypeArgs
static Future<T?> push<T extends Object?>(BuildContext context, Route<T> route) {
return Navigator.of(context).push(route);
}
/// Push a new route onto the navigator that most tightly encloses the
/// given context.
///
/// {@template flutter.widgets.navigator.restorablePush}
/// Unlike [Route]s pushed via [push], [Route]s pushed with this method are
/// restored during state restoration according to the rules outlined in the
/// "State Restoration" section of [Navigator].
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.push}
///
/// {@template flutter.widgets.Navigator.restorablePush}
/// The method takes a [RestorableRouteBuilder] as argument, which must be a
/// _static_ function annotated with `@pragma('vm:entry-point')`. It must
/// instantiate and return a new [Route] object that will be added to the
/// navigator. The provided `arguments` object is passed to the
/// `routeBuilder`. The navigator calls the static `routeBuilder` function
/// again during state restoration to re-create the route object.
///
/// Any object that is serializable via the [StandardMessageCodec] can be
/// passed as `arguments`. Often, a Map is used to pass key-value pairs.
/// {@endtemplate}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool dartpad}
/// Typical usage is as follows:
///
/// ** See code in examples/api/lib/widgets/navigator/navigator.restorable_push.0.dart **
/// {@end-tool}
@optionalTypeArgs
static String restorablePush<T extends Object?>(BuildContext context, RestorableRouteBuilder<T> routeBuilder, {Object? arguments}) {
return Navigator.of(context).restorablePush(routeBuilder, arguments: arguments);
}
/// Replace the current route of the navigator that most tightly encloses the
/// given context by pushing the given route and then disposing the previous
/// route once the new route has finished animating in.
///
/// {@template flutter.widgets.navigator.pushReplacement}
/// If non-null, `result` will be used as the result of the route that is
/// removed; the future that had been returned from pushing that old route will
/// complete with `result`. Routes such as dialogs or popup menus typically
/// use this mechanism to return the value selected by the user to the widget
/// that created their route. The type of `result`, if provided, must match
/// the type argument of the class of the old route (`TO`).
///
/// The new route and the route below the removed route are notified (see
/// [Route.didPush] and [Route.didChangeNext]). If the [Navigator] has any
/// [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didReplace]). The removed route is notified once the
/// new route has finished animating (see [Route.didComplete]).
///
/// Ongoing gestures within the current route are canceled when a new route is
/// pushed.
///
/// The `T` type argument is the type of the return value of the new route,
/// and `TO` is the type of the return value of the old route.
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.pushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _completeLogin() {
/// Navigator.pushReplacement<void, void>(
/// context,
/// MaterialPageRoute<void>(
/// builder: (BuildContext context) => const MyHomePage(),
/// ),
/// );
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePushReplacement], which pushes a replacement route that can
/// be restored during state restoration.
@optionalTypeArgs
static Future<T?> pushReplacement<T extends Object?, TO extends Object?>(BuildContext context, Route<T> newRoute, { TO? result }) {
return Navigator.of(context).pushReplacement<T, TO>(newRoute, result: result);
}
/// Replace the current route of the navigator that most tightly encloses the
/// given context by pushing a new route and then disposing the previous
/// route once the new route has finished animating in.
///
/// {@template flutter.widgets.navigator.restorablePushReplacement}
/// Unlike [Route]s pushed via [pushReplacement], [Route]s pushed with this
/// method are restored during state restoration according to the rules
/// outlined in the "State Restoration" section of [Navigator].
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.pushReplacement}
///
/// {@macro flutter.widgets.Navigator.restorablePush}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool dartpad}
/// Typical usage is as follows:
///
/// ** See code in examples/api/lib/widgets/navigator/navigator.restorable_push_replacement.0.dart **
/// {@end-tool}
@optionalTypeArgs
static String restorablePushReplacement<T extends Object?, TO extends Object?>(BuildContext context, RestorableRouteBuilder<T> routeBuilder, { TO? result, Object? arguments }) {
return Navigator.of(context).restorablePushReplacement<T, TO>(routeBuilder, result: result, arguments: arguments);
}
/// Push the given route onto the navigator that most tightly encloses the
/// given context, and then remove all the previous routes until the
/// `predicate` returns true.
///
/// {@template flutter.widgets.navigator.pushAndRemoveUntil}
/// The predicate may be applied to the same route more than once if
/// [Route.willHandlePopInternally] is true.
///
/// To remove routes until a route with a certain name, use the
/// [RoutePredicate] returned from [ModalRoute.withName].
///
/// To remove all the routes below the pushed route, use a [RoutePredicate]
/// that always returns false (e.g. `(Route<dynamic> route) => false`).
///
/// The removed routes are removed without being completed, so this method
/// does not take a return value argument.
///
/// The newly pushed route and its preceding route are notified for
/// [Route.didPush]. After removal, the new route and its new preceding route,
/// (the route below the bottommost removed route) are notified through
/// [Route.didChangeNext]). If the [Navigator] has any [Navigator.observers],
/// they will be notified as well (see [NavigatorObserver.didPush] and
/// [NavigatorObserver.didRemove]). The removed routes are disposed of and
/// notified, once the new route has finished animating. The futures that had
/// been returned from pushing those routes will not complete.
///
/// Ongoing gestures within the current route are canceled when a new route is
/// pushed.
///
/// The `T` type argument is the type of the return value of the new route.
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.pushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _finishAccountCreation() {
/// Navigator.pushAndRemoveUntil<void>(
/// context,
/// MaterialPageRoute<void>(builder: (BuildContext context) => const MyHomePage()),
/// ModalRoute.withName('/'),
/// );
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePushAndRemoveUntil], which pushes a route that can be
/// restored during state restoration.
@optionalTypeArgs
static Future<T?> pushAndRemoveUntil<T extends Object?>(BuildContext context, Route<T> newRoute, RoutePredicate predicate) {
return Navigator.of(context).pushAndRemoveUntil<T>(newRoute, predicate);
}
/// Push a new route onto the navigator that most tightly encloses the
/// given context, and then remove all the previous routes until the
/// `predicate` returns true.
///
/// {@template flutter.widgets.navigator.restorablePushAndRemoveUntil}
/// Unlike [Route]s pushed via [pushAndRemoveUntil], [Route]s pushed with this
/// method are restored during state restoration according to the rules
/// outlined in the "State Restoration" section of [Navigator].
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.pushAndRemoveUntil}
///
/// {@macro flutter.widgets.Navigator.restorablePush}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool dartpad}
/// Typical usage is as follows:
///
/// ** See code in examples/api/lib/widgets/navigator/navigator.restorable_push_and_remove_until.0.dart **
/// {@end-tool}
@optionalTypeArgs
static String restorablePushAndRemoveUntil<T extends Object?>(BuildContext context, RestorableRouteBuilder<T> newRouteBuilder, RoutePredicate predicate, {Object? arguments}) {
return Navigator.of(context).restorablePushAndRemoveUntil<T>(newRouteBuilder, predicate, arguments: arguments);
}
/// Replaces a route on the navigator that most tightly encloses the given
/// context with a new route.
///
/// {@template flutter.widgets.navigator.replace}
/// The old route must not be currently visible, as this method skips the
/// animations and therefore the removal would be jarring if it was visible.
/// To replace the top-most route, consider [pushReplacement] instead, which
/// _does_ animate the new route, and delays removing the old route until the
/// new route has finished animating.
///
/// The removed route is removed without being completed, so this method does
/// not take a return value argument.
///
/// The new route, the route below the new route (if any), and the route above
/// the new route, are all notified (see [Route.didReplace],
/// [Route.didChangeNext], and [Route.didChangePrevious]). If the [Navigator]
/// has any [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didReplace]). The removed route is disposed without
/// being notified. The future that had been returned from pushing that routes
/// will not complete.
///
/// This can be useful in combination with [removeRouteBelow] when building a
/// non-linear user experience.
///
/// The `T` type argument is the type of the return value of the new route.
/// {@endtemplate}
///
/// See also:
///
/// * [replaceRouteBelow], which is the same but identifies the route to be
/// removed by reference to the route above it, rather than directly.
/// * [restorableReplace], which adds a replacement route that can be
/// restored during state restoration.
@optionalTypeArgs
static void replace<T extends Object?>(BuildContext context, { required Route<dynamic> oldRoute, required Route<T> newRoute }) {
return Navigator.of(context).replace<T>(oldRoute: oldRoute, newRoute: newRoute);
}
/// Replaces a route on the navigator that most tightly encloses the given
/// context with a new route.
///
/// {@template flutter.widgets.navigator.restorableReplace}
/// Unlike [Route]s added via [replace], [Route]s added with this method are
/// restored during state restoration according to the rules outlined in the
/// "State Restoration" section of [Navigator].
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.replace}
///
/// {@macro flutter.widgets.Navigator.restorablePush}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
@optionalTypeArgs
static String restorableReplace<T extends Object?>(BuildContext context, { required Route<dynamic> oldRoute, required RestorableRouteBuilder<T> newRouteBuilder, Object? arguments }) {
return Navigator.of(context).restorableReplace<T>(oldRoute: oldRoute, newRouteBuilder: newRouteBuilder, arguments: arguments);
}
/// Replaces a route on the navigator that most tightly encloses the given
/// context with a new route. The route to be replaced is the one below the
/// given `anchorRoute`.
///
/// {@template flutter.widgets.navigator.replaceRouteBelow}
/// The old route must not be current visible, as this method skips the
/// animations and therefore the removal would be jarring if it was visible.
/// To replace the top-most route, consider [pushReplacement] instead, which
/// _does_ animate the new route, and delays removing the old route until the
/// new route has finished animating.
///
/// The removed route is removed without being completed, so this method does
/// not take a return value argument.
///
/// The new route, the route below the new route (if any), and the route above
/// the new route, are all notified (see [Route.didReplace],
/// [Route.didChangeNext], and [Route.didChangePrevious]). If the [Navigator]
/// has any [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didReplace]). The removed route is disposed without
/// being notified. The future that had been returned from pushing that routes
/// will not complete.
///
/// The `T` type argument is the type of the return value of the new route.
/// {@endtemplate}
///
/// See also:
///
/// * [replace], which is the same but identifies the route to be removed
/// directly.
/// * [restorableReplaceRouteBelow], which adds a replacement route that can
/// be restored during state restoration.
@optionalTypeArgs
static void replaceRouteBelow<T extends Object?>(BuildContext context, { required Route<dynamic> anchorRoute, required Route<T> newRoute }) {
return Navigator.of(context).replaceRouteBelow<T>(anchorRoute: anchorRoute, newRoute: newRoute);
}
/// Replaces a route on the navigator that most tightly encloses the given
/// context with a new route. The route to be replaced is the one below the
/// given `anchorRoute`.
///
/// {@template flutter.widgets.navigator.restorableReplaceRouteBelow}
/// Unlike [Route]s added via [restorableReplaceRouteBelow], [Route]s added
/// with this method are restored during state restoration according to the
/// rules outlined in the "State Restoration" section of [Navigator].
/// {@endtemplate}
///
/// {@macro flutter.widgets.navigator.replaceRouteBelow}
///
/// {@macro flutter.widgets.Navigator.restorablePush}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
@optionalTypeArgs
static String restorableReplaceRouteBelow<T extends Object?>(BuildContext context, { required Route<dynamic> anchorRoute, required RestorableRouteBuilder<T> newRouteBuilder, Object? arguments }) {
return Navigator.of(context).restorableReplaceRouteBelow<T>(anchorRoute: anchorRoute, newRouteBuilder: newRouteBuilder, arguments: arguments);
}
/// Whether the navigator that most tightly encloses the given context can be
/// popped.
///
/// {@template flutter.widgets.navigator.canPop}
/// The initial route cannot be popped off the navigator, which implies that
/// this function returns true only if popping the navigator would not remove
/// the initial route.
///
/// If there is no [Navigator] in scope, returns false.
///
/// Does not consider anything that might externally prevent popping, such as
/// [PopEntry].
/// {@endtemplate}
///
/// See also:
///
/// * [Route.isFirst], which returns true for routes for which [canPop]
/// returns false.
static bool canPop(BuildContext context) {
final NavigatorState? navigator = Navigator.maybeOf(context);
return navigator != null && navigator.canPop();
}
/// Consults the current route's [Route.popDisposition] getter or
/// [Route.willPop] method, and acts accordingly, potentially popping the
/// route as a result; returns whether the pop request should be considered
/// handled.
///
/// {@template flutter.widgets.navigator.maybePop}
/// If the [RoutePopDisposition] is [RoutePopDisposition.pop], then the [pop]
/// method is called, and this method returns true, indicating that it handled
/// the pop request.
///
/// If the [RoutePopDisposition] is [RoutePopDisposition.doNotPop], then this
/// method returns true, but does not do anything beyond that.
///
/// If the [RoutePopDisposition] is [RoutePopDisposition.bubble], then this
/// method returns false, and the caller is responsible for sending the
/// request to the containing scope (e.g. by closing the application).
///
/// This method is typically called for a user-initiated [pop]. For example on
/// Android it's called by the binding for the system's back button.
///
/// The `T` type argument is the type of the return value of the current
/// route. (Typically this isn't known; consider specifying `dynamic` or
/// `Null`.)
/// {@endtemplate}
///
/// See also:
///
/// * [Form], which provides an `onWillPop` callback that enables the form
/// to veto a [pop] initiated by the app's back button.
/// * [ModalRoute], which provides a `scopedWillPopCallback` that can be used
/// to define the route's `willPop` method.
@optionalTypeArgs
static Future<bool> maybePop<T extends Object?>(BuildContext context, [ T? result ]) {
return Navigator.of(context).maybePop<T>(result);
}
/// Pop the top-most route off the navigator that most tightly encloses the
/// given context.
///
/// {@template flutter.widgets.navigator.pop}
/// The current route's [Route.didPop] method is called first. If that method
/// returns false, then the route remains in the [Navigator]'s history (the
/// route is expected to have popped some internal state; see e.g.
/// [LocalHistoryRoute]). Otherwise, the rest of this description applies.
///
/// If non-null, `result` will be used as the result of the route that is
/// popped; the future that had been returned from pushing the popped route
/// will complete with `result`. Routes such as dialogs or popup menus
/// typically use this mechanism to return the value selected by the user to
/// the widget that created their route. The type of `result`, if provided,
/// must match the type argument of the class of the popped route (`T`).
///
/// The popped route and the route below it are notified (see [Route.didPop],
/// [Route.didComplete], and [Route.didPopNext]). If the [Navigator] has any
/// [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didPop]).
///
/// The `T` type argument is the type of the return value of the popped route.
///
/// The type of `result`, if provided, must match the type argument of the
/// class of the popped route (`T`).
/// {@endtemplate}
///
/// {@tool snippet}
///
/// Typical usage for closing a route is as follows:
///
/// ```dart
/// void _close() {
/// Navigator.pop(context);
/// }
/// ```
/// {@end-tool}
///
/// A dialog box might be closed with a result:
///
/// ```dart
/// void _accept() {
/// Navigator.pop(context, true); // dialog returns true
/// }
/// ```
@optionalTypeArgs
static void pop<T extends Object?>(BuildContext context, [ T? result ]) {
Navigator.of(context).pop<T>(result);
}
/// Calls [pop] repeatedly on the navigator that most tightly encloses the
/// given context until the predicate returns true.
///
/// {@template flutter.widgets.navigator.popUntil}
/// The predicate may be applied to the same route more than once if
/// [Route.willHandlePopInternally] is true.
///
/// To pop until a route with a certain name, use the [RoutePredicate]
/// returned from [ModalRoute.withName].
///
/// The routes are closed with null as their `return` value.
///
/// See [pop] for more details of the semantics of popping a route.
/// {@endtemplate}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _logout() {
/// Navigator.popUntil(context, ModalRoute.withName('/login'));
/// }
/// ```
/// {@end-tool}
static void popUntil(BuildContext context, RoutePredicate predicate) {
Navigator.of(context).popUntil(predicate);
}
/// Immediately remove `route` from the navigator that most tightly encloses
/// the given context, and [Route.dispose] it.
///
/// {@template flutter.widgets.navigator.removeRoute}
/// The removed route is removed without being completed, so this method does
/// not take a return value argument. No animations are run as a result of
/// this method call.
///
/// The routes below and above the removed route are notified (see
/// [Route.didChangeNext] and [Route.didChangePrevious]). If the [Navigator]
/// has any [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didRemove]). The removed route is disposed without
/// being notified. The future that had been returned from pushing that routes
/// will not complete.
///
/// The given `route` must be in the history; this method will throw an
/// exception if it is not.
///
/// Ongoing gestures within the current route are canceled.
/// {@endtemplate}
///
/// This method is used, for example, to instantly dismiss dropdown menus that
/// are up when the screen's orientation changes.
static void removeRoute(BuildContext context, Route<dynamic> route) {
return Navigator.of(context).removeRoute(route);
}
/// Immediately remove a route from the navigator that most tightly encloses
/// the given context, and [Route.dispose] it. The route to be removed is the
/// one below the given `anchorRoute`.
///
/// {@template flutter.widgets.navigator.removeRouteBelow}
/// The removed route is removed without being completed, so this method does
/// not take a return value argument. No animations are run as a result of
/// this method call.
///
/// The routes below and above the removed route are notified (see
/// [Route.didChangeNext] and [Route.didChangePrevious]). If the [Navigator]
/// has any [Navigator.observers], they will be notified as well (see
/// [NavigatorObserver.didRemove]). The removed route is disposed without
/// being notified. The future that had been returned from pushing that routes
/// will not complete.
///
/// The given `anchorRoute` must be in the history and must have a route below
/// it; this method will throw an exception if it is not or does not.
///
/// Ongoing gestures within the current route are canceled.
/// {@endtemplate}
static void removeRouteBelow(BuildContext context, Route<dynamic> anchorRoute) {
return Navigator.of(context).removeRouteBelow(anchorRoute);
}
/// The state from the closest instance of this class that encloses the given
/// context.
///
/// Typical usage is as follows:
///
/// ```dart
/// Navigator.of(context)
/// ..pop()
/// ..pop()
/// ..pushNamed('/settings');
/// ```
///
/// If `rootNavigator` is set to true, the state from the furthest instance of
/// this class is given instead. Useful for pushing contents above all
/// subsequent instances of [Navigator].
///
/// If there is no [Navigator] in the give `context`, this function will throw
/// a [FlutterError] in debug mode, and an exception in release mode.
///
/// This method can be expensive (it walks the element tree).
static NavigatorState of(
BuildContext context, {
bool rootNavigator = false,
}) {
// Handles the case where the input context is a navigator element.
NavigatorState? navigator;
if (context is StatefulElement && context.state is NavigatorState) {
navigator = context.state as NavigatorState;
}
if (rootNavigator) {
navigator = context.findRootAncestorStateOfType<NavigatorState>() ?? navigator;
} else {
navigator = navigator ?? context.findAncestorStateOfType<NavigatorState>();
}
assert(() {
if (navigator == null) {
throw FlutterError(
'Navigator operation requested with a context that does not include a Navigator.\n'
'The context used to push or pop routes from the Navigator must be that of a '
'widget that is a descendant of a Navigator widget.',
);
}
return true;
}());
return navigator!;
}
/// The state from the closest instance of this class that encloses the given
/// context, if any.
///
/// Typical usage is as follows:
///
/// ```dart
/// NavigatorState? navigatorState = Navigator.maybeOf(context);
/// if (navigatorState != null) {
/// navigatorState
/// ..pop()
/// ..pop()
/// ..pushNamed('/settings');
/// }
/// ```
///
/// If `rootNavigator` is set to true, the state from the furthest instance of
/// this class is given instead. Useful for pushing contents above all
/// subsequent instances of [Navigator].
///
/// Will return null if there is no ancestor [Navigator] in the `context`.
///
/// This method can be expensive (it walks the element tree).
static NavigatorState? maybeOf(
BuildContext context, {
bool rootNavigator = false,
}) {
// Handles the case where the input context is a navigator element.
NavigatorState? navigator;
if (context is StatefulElement && context.state is NavigatorState) {
navigator = context.state as NavigatorState;
}
if (rootNavigator) {
navigator = context.findRootAncestorStateOfType<NavigatorState>() ?? navigator;
} else {
navigator = navigator ?? context.findAncestorStateOfType<NavigatorState>();
}
return navigator;
}
/// Turn a route name into a set of [Route] objects.
///
/// This is the default value of [onGenerateInitialRoutes], which is used if
/// [initialRoute] is not null.
///
/// If this string starts with a `/` character and has multiple `/` characters
/// in it, then the string is split on those characters and substrings from
/// the start of the string up to each such character are, in turn, used as
/// routes to push.
///
/// For example, if the route `/stocks/HOOLI` was used as the [initialRoute],
/// then the [Navigator] would push the following routes on startup: `/`,
/// `/stocks`, `/stocks/HOOLI`. This enables deep linking while allowing the
/// application to maintain a predictable route history.
static List<Route<dynamic>> defaultGenerateInitialRoutes(NavigatorState navigator, String initialRouteName) {
final List<Route<dynamic>?> result = <Route<dynamic>?>[];
if (initialRouteName.startsWith('/') && initialRouteName.length > 1) {
initialRouteName = initialRouteName.substring(1); // strip leading '/'
assert(Navigator.defaultRouteName == '/');
List<String>? debugRouteNames;
assert(() {
debugRouteNames = <String>[ Navigator.defaultRouteName ];
return true;
}());
result.add(navigator._routeNamed<dynamic>(Navigator.defaultRouteName, arguments: null, allowNull: true));
final List<String> routeParts = initialRouteName.split('/');
if (initialRouteName.isNotEmpty) {
String routeName = '';
for (final String part in routeParts) {
routeName += '/$part';
assert(() {
debugRouteNames!.add(routeName);
return true;
}());
result.add(navigator._routeNamed<dynamic>(routeName, arguments: null, allowNull: true));
}
}
if (result.last == null) {
assert(() {
FlutterError.reportError(
FlutterErrorDetails(
exception:
'Could not navigate to initial route.\n'
'The requested route name was: "/$initialRouteName"\n'
'There was no corresponding route in the app, and therefore the initial route specified will be '
'ignored and "${Navigator.defaultRouteName}" will be used instead.',
),
);
return true;
}());
for (final Route<dynamic>? route in result) {
route?.dispose();
}
result.clear();
}
} else if (initialRouteName != Navigator.defaultRouteName) {
// If initialRouteName wasn't '/', then we try to get it with allowNull:true, so that if that fails,
// we fall back to '/' (without allowNull:true, see below).
result.add(navigator._routeNamed<dynamic>(initialRouteName, arguments: null, allowNull: true));
}
// Null route might be a result of gap in initialRouteName
//
// For example, routes = ['A', 'A/B/C'], and initialRouteName = 'A/B/C'
// This should result in result = ['A', null,'A/B/C'] where 'A/B' produces
// the null. In this case, we want to filter out the null and return
// result = ['A', 'A/B/C'].
result.removeWhere((Route<dynamic>? route) => route == null);
if (result.isEmpty) {
result.add(navigator._routeNamed<dynamic>(Navigator.defaultRouteName, arguments: null));
}
return result.cast<Route<dynamic>>();
}
@override
NavigatorState createState() => NavigatorState();
}
// The _RouteLifecycle state machine (only goes down):
//
// [creation of a _RouteEntry]
// |
// +
// |\
// | \
// | staging
// | /
// |/
// +-+----------+--+-------+
// / | | |
// / | | |
// / | | |
// / | | |
// / | | |
// pushReplace push* add* replace*
// \ | | |
// \ | | /
// +--pushing# adding /
// \ / /
// \ / /
// idle--+-----+
// / \
// / +------+
// / | |
// / | complete*
// | | /
// pop* remove*
// / \
// / removing#
// popping# |
// | |
// [finalizeRoute] |
// \ |
// dispose*
// |
// disposing
// |
// disposed
// |
// |
// [_RouteEntry garbage collected]
// (terminal state)
//
// * These states are transient; as soon as _flushHistoryUpdates is run the
// route entry will exit that state.
// # These states await futures or other events, then transition automatically.
enum _RouteLifecycle {
staging, // we will wait for transition delegate to decide what to do with this route.
//
// routes that are present:
//
add, // we'll want to run install, didAdd, etc; a route created by onGenerateInitialRoutes or by the initial widget.pages
adding, // we'll waiting for the future from didPush of top-most route to complete
// routes that are ready for transition.
push, // we'll want to run install, didPush, etc; a route added via push() and friends
pushReplace, // we'll want to run install, didPush, etc; a route added via pushReplace() and friends
pushing, // we're waiting for the future from didPush to complete
replace, // we'll want to run install, didReplace, etc; a route added via replace() and friends
idle, // route is being harmless
//
// routes that are not present:
//
// routes that should be included in route announcement and should still listen to transition changes.
pop, // we'll want to call didPop
complete, // we'll want to call didComplete,
remove, // we'll want to run didReplace/didRemove etc
// routes should not be included in route announcement but should still listen to transition changes.
popping, // we're waiting for the route to call finalizeRoute to switch to dispose
removing, // we are waiting for subsequent routes to be done animating, then will switch to dispose
// routes that are completely removed from the navigator and overlay.
dispose, // we will dispose the route momentarily
disposing, // The entry is waiting for its widget subtree to be disposed
// first. It is stored in _entryWaitingForSubTreeDisposal while
// awaiting that.
disposed, // we have disposed the route
}
typedef _RouteEntryPredicate = bool Function(_RouteEntry entry);
/// Placeholder for a route.
class _RoutePlaceholder {
const _RoutePlaceholder();
}
class _RouteEntry extends RouteTransitionRecord {
_RouteEntry(
this.route, {
required _RouteLifecycle initialState,
required this.pageBased,
this.restorationInformation,
}) : assert(!pageBased || route.settings is Page),
assert(
initialState == _RouteLifecycle.staging ||
initialState == _RouteLifecycle.add ||
initialState == _RouteLifecycle.push ||
initialState == _RouteLifecycle.pushReplace ||
initialState == _RouteLifecycle.replace,
),
currentState = initialState {
// TODO(polina-c): stop duplicating code across disposables
// https://github.com/flutter/flutter/issues/137435
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectCreated(
library: 'package:flutter/widgets.dart',
className: '$_RouteEntry',
object: this,
);
}
}
@override
final Route<dynamic> route;
final _RestorationInformation? restorationInformation;
final bool pageBased;
/// The limit this route entry will attempt to pop in the case of route being
/// remove as a result of a page update.
static const int kDebugPopAttemptLimit = 100;
static const _RoutePlaceholder notAnnounced = _RoutePlaceholder();
_RouteLifecycle currentState;
_RoutePlaceholder? lastAnnouncedPreviousRoute = notAnnounced; // last argument to Route.didChangePrevious
WeakReference<_RoutePlaceholder> lastAnnouncedPoppedNextRoute = WeakReference<_RoutePlaceholder>(notAnnounced); // last argument to Route.didPopNext
_RoutePlaceholder? lastAnnouncedNextRoute = notAnnounced; // last argument to Route.didChangeNext
int? lastFocusNode; // The last focused semantic node for the route entry.
/// Restoration ID to be used for the encapsulating route when restoration is
/// enabled for it or null if restoration cannot be enabled for it.
String? get restorationId {
// User-provided restoration ids of Pages are prefixed with 'p+'. Generated
// ids for pageless routes are prefixed with 'r+' to avoid clashes.
if (pageBased) {
final Page<Object?> page = route.settings as Page<Object?>;
return page.restorationId != null ? 'p+${page.restorationId}' : null;
}
if (restorationInformation != null) {
return 'r+${restorationInformation!.restorationScopeId}';
}
return null;
}
bool canUpdateFrom(Page<dynamic> page) {
if (!willBePresent) {
return false;
}
if (!pageBased) {
return false;
}
final Page<dynamic> routePage = route.settings as Page<dynamic>;
return page.canUpdate(routePage);
}
void handleAdd({ required NavigatorState navigator, required Route<dynamic>? previousPresent }) {
assert(currentState == _RouteLifecycle.add);
assert(navigator._debugLocked);
assert(route._navigator == null);
route._navigator = navigator;
route.install();
assert(route.overlayEntries.isNotEmpty);
currentState = _RouteLifecycle.adding;
navigator._observedRouteAdditions.add(
_NavigatorPushObservation(route, previousPresent),
);
}
void handlePush({ required NavigatorState navigator, required bool isNewFirst, required Route<dynamic>? previous, required Route<dynamic>? previousPresent }) {
assert(currentState == _RouteLifecycle.push || currentState == _RouteLifecycle.pushReplace || currentState == _RouteLifecycle.replace);
assert(navigator._debugLocked);
assert(
route._navigator == null,
'The pushed route has already been used. When pushing a route, a new '
'Route object must be provided.',
);
final _RouteLifecycle previousState = currentState;
route._navigator = navigator;
route.install();
assert(route.overlayEntries.isNotEmpty);
if (currentState == _RouteLifecycle.push || currentState == _RouteLifecycle.pushReplace) {
final TickerFuture routeFuture = route.didPush();
currentState = _RouteLifecycle.pushing;
routeFuture.whenCompleteOrCancel(() {
if (currentState == _RouteLifecycle.pushing) {
currentState = _RouteLifecycle.idle;
assert(!navigator._debugLocked);
assert(() { navigator._debugLocked = true; return true; }());
navigator._flushHistoryUpdates();
assert(() { navigator._debugLocked = false; return true; }());
}
});
} else {
assert(currentState == _RouteLifecycle.replace);
route.didReplace(previous);
currentState = _RouteLifecycle.idle;
}
if (isNewFirst) {
route.didChangeNext(null);
}
if (previousState == _RouteLifecycle.replace || previousState == _RouteLifecycle.pushReplace) {
navigator._observedRouteAdditions.add(
_NavigatorReplaceObservation(route, previousPresent),
);
} else {
assert(previousState == _RouteLifecycle.push);
navigator._observedRouteAdditions.add(
_NavigatorPushObservation(route, previousPresent),
);
}
}
void handleDidPopNext(Route<dynamic> poppedRoute) {
route.didPopNext(poppedRoute);
lastAnnouncedPoppedNextRoute = WeakReference<Route<dynamic>>(poppedRoute);
if (lastFocusNode != null) {
// Move focus back to the last focused node.
poppedRoute._disposeCompleter.future.then((dynamic result) async {
switch (defaultTargetPlatform) {
case TargetPlatform.android:
// In the Android platform, we have to wait for the system refocus to complete before
// sending the refocus message. Otherwise, the refocus message will be ignored.
// TODO(hangyujin): update this logic if Android provide a better way to do so.
final int? reFocusNode = lastFocusNode;
await Future<void>.delayed(_kAndroidRefocusingDelayDuration);
SystemChannels.accessibility.send(const FocusSemanticEvent().toMap(nodeId: reFocusNode));
case TargetPlatform.iOS:
SystemChannels.accessibility.send(const FocusSemanticEvent().toMap(nodeId: lastFocusNode));
case _:
break ;
}
});
}
}
/// Process the to-be-popped route.
///
/// A route can be marked for pop by transition delegate or Navigator.pop,
/// this method actually pops the route by calling Route.didPop.
///
/// Returns true if the route is popped; otherwise, returns false if the route
/// refuses to be popped.
bool handlePop({ required NavigatorState navigator, required Route<dynamic>? previousPresent }) {
assert(navigator._debugLocked);
assert(route._navigator == navigator);
currentState = _RouteLifecycle.popping;
if (route._popCompleter.isCompleted) {
// This is a page-based route popped through the Navigator.pop. The
// didPop should have been called. No further action is needed.
assert(pageBased);
assert(pendingResult == null);
return true;
}
if (!route.didPop(pendingResult)) {
currentState = _RouteLifecycle.idle;
return false;
}
pendingResult = null;
return true;
}
void handleComplete() {
route.didComplete(pendingResult);
pendingResult = null;
assert(route._popCompleter.isCompleted); // implies didComplete was called
currentState = _RouteLifecycle.remove;
}
void handleRemoval({ required NavigatorState navigator, required Route<dynamic>? previousPresent }) {
assert(navigator._debugLocked);
assert(route._navigator == navigator);
currentState = _RouteLifecycle.removing;
if (_reportRemovalToObserver) {
navigator._observedRouteDeletions.add(
_NavigatorRemoveObservation(route, previousPresent),
);
}
}
void didAdd({ required NavigatorState navigator, required bool isNewFirst}) {
route.didAdd();
currentState = _RouteLifecycle.idle;
if (isNewFirst) {
route.didChangeNext(null);
}
}
Object? pendingResult;
void pop<T>(T? result) {
assert(isPresent);
pendingResult = result;
currentState = _RouteLifecycle.pop;
route.onPopInvoked(true);
}
bool _reportRemovalToObserver = true;
// Route is removed without being completed.
void remove({ bool isReplaced = false }) {
assert(
!pageBased || isWaitingForExitingDecision,
'A page-based route cannot be completed using imperative api, provide a '
'new list without the corresponding Page to Navigator.pages instead. ',
);
if (currentState.index >= _RouteLifecycle.remove.index) {
return;
}
assert(isPresent);
_reportRemovalToObserver = !isReplaced;
currentState = _RouteLifecycle.remove;
}
// Route completes with `result` and is removed.
void complete<T>(T result, { bool isReplaced = false }) {
assert(
!pageBased || isWaitingForExitingDecision,
'A page-based route cannot be completed using imperative api, provide a '
'new list without the corresponding Page to Navigator.pages instead. ',
);
if (currentState.index >= _RouteLifecycle.remove.index) {
return;
}
assert(isPresent);
_reportRemovalToObserver = !isReplaced;
pendingResult = result;
currentState = _RouteLifecycle.complete;
}
void finalize() {
assert(currentState.index < _RouteLifecycle.dispose.index);
currentState = _RouteLifecycle.dispose;
}
/// Disposes this route entry and its [route] immediately.
///
/// This method does not wait for the widget subtree of the [route] to unmount
/// before disposing.
void forcedDispose() {
assert(currentState.index < _RouteLifecycle.disposed.index);
// TODO(polina-c): stop duplicating code across disposables
// https://github.com/flutter/flutter/issues/137435
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this);
}
currentState = _RouteLifecycle.disposed;
route.dispose();
}
/// Disposes this route entry and its [route].
///
/// This method waits for the widget subtree of the [route] to unmount before
/// disposing. If subtree is already unmounted, this method calls
/// [forcedDispose] immediately.
///
/// Use [forcedDispose] if the [route] need to be disposed immediately.
void dispose() {
assert(currentState.index < _RouteLifecycle.disposing.index);
currentState = _RouteLifecycle.disposing;
// If the overlay entries are still mounted, widgets in the route's subtree
// may still reference resources from the route and we delay disposal of
// the route until the overlay entries are no longer mounted.
// Since the overlay entry is the root of the route's subtree it will only
// get unmounted after every other widget in the subtree has been unmounted.
final Iterable<OverlayEntry> mountedEntries = route.overlayEntries.where((OverlayEntry e) => e.mounted);
if (mountedEntries.isEmpty) {
forcedDispose();
return;
}
int mounted = mountedEntries.length;
assert(mounted > 0);
final NavigatorState navigator = route._navigator!;
navigator._entryWaitingForSubTreeDisposal.add(this);
for (final OverlayEntry entry in mountedEntries) {
late VoidCallback listener;
listener = () {
assert(mounted > 0);
assert(!entry.mounted);
mounted--;
entry.removeListener(listener);
if (mounted == 0) {
assert(route.overlayEntries.every((OverlayEntry e) => !e.mounted));
// This is a listener callback of one of the overlayEntries in this
// route. Disposing the route also disposes its overlayEntries and
// violates the rule that a change notifier can't be disposed during
// its notifying callback.
//
// Use a microtask to ensure the overlayEntries have finished
// notifying their listeners before disposing.
return scheduleMicrotask(() {
if (!navigator._entryWaitingForSubTreeDisposal.remove(this)) {
// This route must have been destroyed as a result of navigator
// force dispose.
assert(route._navigator == null && !navigator.mounted);
return;
}
assert(currentState == _RouteLifecycle.disposing);
forcedDispose();
});
}
};
entry.addListener(listener);
}
}
bool get willBePresent {
return currentState.index <= _RouteLifecycle.idle.index &&
currentState.index >= _RouteLifecycle.add.index;
}
bool get isPresent {
return currentState.index <= _RouteLifecycle.remove.index &&
currentState.index >= _RouteLifecycle.add.index;
}
bool get isPresentForRestoration => currentState.index <= _RouteLifecycle.idle.index;
bool get suitableForAnnouncement {
return currentState.index <= _RouteLifecycle.removing.index &&
currentState.index >= _RouteLifecycle.push.index;
}
bool get suitableForTransitionAnimation {
return currentState.index <= _RouteLifecycle.remove.index &&
currentState.index >= _RouteLifecycle.push.index;
}
bool shouldAnnounceChangeToNext(Route<dynamic>? nextRoute) {
assert(nextRoute != lastAnnouncedNextRoute);
// Do not announce if `next` changes from a just popped route to null. We
// already announced this change by calling didPopNext.
return !(
nextRoute == null &&
lastAnnouncedPoppedNextRoute.target == lastAnnouncedNextRoute
);
}
static bool isPresentPredicate(_RouteEntry entry) => entry.isPresent;
static bool suitableForTransitionAnimationPredicate(_RouteEntry entry) => entry.suitableForTransitionAnimation;
static bool willBePresentPredicate(_RouteEntry entry) => entry.willBePresent;
static _RouteEntryPredicate isRoutePredicate(Route<dynamic> route) {
return (_RouteEntry entry) => entry.route == route;
}
@override
bool get isWaitingForEnteringDecision => currentState == _RouteLifecycle.staging;
@override
bool get isWaitingForExitingDecision => _isWaitingForExitingDecision;
bool _isWaitingForExitingDecision = false;
void markNeedsExitingDecision() => _isWaitingForExitingDecision = true;
@override
void markForPush() {
assert(
isWaitingForEnteringDecision && !isWaitingForExitingDecision,
'This route cannot be marked for push. Either a decision has already been '
'made or it does not require an explicit decision on how to transition in.',
);
currentState = _RouteLifecycle.push;
}
@override
void markForAdd() {
assert(
isWaitingForEnteringDecision && !isWaitingForExitingDecision,
'This route cannot be marked for add. Either a decision has already been '
'made or it does not require an explicit decision on how to transition in.',
);
currentState = _RouteLifecycle.add;
}
@override
void markForPop([dynamic result]) {
assert(
!isWaitingForEnteringDecision && isWaitingForExitingDecision && isPresent,
'This route cannot be marked for pop. Either a decision has already been '
'made or it does not require an explicit decision on how to transition out.',
);
// Remove state that prevents a pop, e.g. LocalHistoryEntry[s].
int attempt = 0;
while (route.willHandlePopInternally) {
assert(
() {
attempt += 1;
return attempt < kDebugPopAttemptLimit;
}(),
'Attempted to pop $route $kDebugPopAttemptLimit times, but still failed',
);
final bool popResult = route.didPop(result);
assert(!popResult);
}
pop<dynamic>(result);
_isWaitingForExitingDecision = false;
}
@override
void markForComplete([dynamic result]) {
assert(
!isWaitingForEnteringDecision && isWaitingForExitingDecision && isPresent,
'This route cannot be marked for complete. Either a decision has already '
'been made or it does not require an explicit decision on how to transition '
'out.',
);
complete<dynamic>(result);
_isWaitingForExitingDecision = false;
}
@override
void markForRemove() {
assert(
!isWaitingForEnteringDecision && isWaitingForExitingDecision && isPresent,
'This route cannot be marked for remove. Either a decision has already '
'been made or it does not require an explicit decision on how to transition '
'out.',
);
remove();
_isWaitingForExitingDecision = false;
}
bool get restorationEnabled => route.restorationScopeId.value != null;
set restorationEnabled(bool value) {
assert(!value || restorationId != null);
route._updateRestorationId(value ? restorationId : null);
}
}
abstract class _NavigatorObservation {
_NavigatorObservation(
this.primaryRoute,
this.secondaryRoute,
);
final Route<dynamic> primaryRoute;
final Route<dynamic>? secondaryRoute;
void notify(NavigatorObserver observer);
}
class _NavigatorPushObservation extends _NavigatorObservation {
_NavigatorPushObservation(
super.primaryRoute,
super.secondaryRoute,
);
@override
void notify(NavigatorObserver observer) {
observer.didPush(primaryRoute, secondaryRoute);
}
}
class _NavigatorPopObservation extends _NavigatorObservation {
_NavigatorPopObservation(
super.primaryRoute,
super.secondaryRoute,
);
@override
void notify(NavigatorObserver observer) {
observer.didPop(primaryRoute, secondaryRoute);
}
}
class _NavigatorRemoveObservation extends _NavigatorObservation {
_NavigatorRemoveObservation(
super.primaryRoute,
super.secondaryRoute,
);
@override
void notify(NavigatorObserver observer) {
observer.didRemove(primaryRoute, secondaryRoute);
}
}
class _NavigatorReplaceObservation extends _NavigatorObservation {
_NavigatorReplaceObservation(
super.primaryRoute,
super.secondaryRoute,
);
@override
void notify(NavigatorObserver observer) {
observer.didReplace(newRoute: primaryRoute, oldRoute: secondaryRoute);
}
}
typedef _IndexWhereCallback = bool Function(_RouteEntry element);
/// A collection of _RouteEntries representing a navigation history.
///
/// Acts as a ChangeNotifier and notifies after its List of _RouteEntries is
/// mutated.
class _History extends Iterable<_RouteEntry> with ChangeNotifier {
/// Creates an instance of [_History].
_History() {
if (kFlutterMemoryAllocationsEnabled) {
ChangeNotifier.maybeDispatchObjectCreation(this);
}
}
final List<_RouteEntry> _value = <_RouteEntry>[];
int indexWhere(_IndexWhereCallback test, [int start = 0]) {
return _value.indexWhere(test, start);
}
void add(_RouteEntry element) {
_value.add(element);
notifyListeners();
}
void addAll(Iterable<_RouteEntry> elements) {
_value.addAll(elements);
if (elements.isNotEmpty) {
notifyListeners();
}
}
void clear() {
final bool valueWasEmpty = _value.isEmpty;
_value.clear();
if (!valueWasEmpty) {
notifyListeners();
}
}
void insert(int index, _RouteEntry element) {
_value.insert(index, element);
notifyListeners();
}
_RouteEntry removeAt(int index) {
final _RouteEntry entry = _value.removeAt(index);
notifyListeners();
return entry;
}
_RouteEntry removeLast() {
final _RouteEntry entry = _value.removeLast();
notifyListeners();
return entry;
}
_RouteEntry operator [](int index) {
return _value[index];
}
@override
Iterator<_RouteEntry> get iterator {
return _value.iterator;
}
@override
String toString() {
return _value.toString();
}
}
/// The state for a [Navigator] widget.
///
/// A reference to this class can be obtained by calling [Navigator.of].
class NavigatorState extends State<Navigator> with TickerProviderStateMixin, RestorationMixin {
late GlobalKey<OverlayState> _overlayKey;
final _History _history = _History();
/// A set for entries that are waiting to dispose until their subtrees are
/// disposed.
///
/// These entries are not considered to be in the _history and will usually
/// remove themselves from this set once they can dispose.
///
/// The navigator keep track of these entries so that, in case the navigator
/// itself is disposed, it can dispose these entries immediately.
final Set<_RouteEntry> _entryWaitingForSubTreeDisposal = <_RouteEntry>{};
final _HistoryProperty _serializableHistory = _HistoryProperty();
final Queue<_NavigatorObservation> _observedRouteAdditions = Queue<_NavigatorObservation>();
final Queue<_NavigatorObservation> _observedRouteDeletions = Queue<_NavigatorObservation>();
/// The [FocusNode] for the [Focus] that encloses the routes.
final FocusNode focusNode = FocusNode(debugLabel: 'Navigator');
bool _debugLocked = false; // used to prevent re-entrant calls to push, pop, and friends
HeroController? _heroControllerFromScope;
late List<NavigatorObserver> _effectiveObservers;
bool get _usingPagesAPI => widget.pages != const <Page<dynamic>>[];
void _handleHistoryChanged() {
final bool navigatorCanPop = canPop();
late final bool routeBlocksPop;
if (!navigatorCanPop) {
final _RouteEntry? lastEntry = _lastRouteEntryWhereOrNull(_RouteEntry.isPresentPredicate);
routeBlocksPop = lastEntry != null
&& lastEntry.route.popDisposition == RoutePopDisposition.doNotPop;
} else {
routeBlocksPop = false;
}
final NavigationNotification notification = NavigationNotification(
canHandlePop: navigatorCanPop || routeBlocksPop,
);
// Avoid dispatching a notification in the middle of a build.
switch (SchedulerBinding.instance.schedulerPhase) {
case SchedulerPhase.postFrameCallbacks:
notification.dispatch(context);
case SchedulerPhase.idle:
case SchedulerPhase.midFrameMicrotasks:
case SchedulerPhase.persistentCallbacks:
case SchedulerPhase.transientCallbacks:
SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) {
if (!mounted) {
return;
}
notification.dispatch(context);
}, debugLabel: 'Navigator.dispatchNotification');
}
}
@override
void initState() {
super.initState();
assert(() {
if (_usingPagesAPI) {
if (widget.pages.isEmpty) {
FlutterError.reportError(
FlutterErrorDetails(
exception: FlutterError(
'The Navigator.pages must not be empty to use the '
'Navigator.pages API',
),
library: 'widget library',
stack: StackTrace.current,
),
);
} else if (widget.onPopPage == null) {
FlutterError.reportError(
FlutterErrorDetails(
exception: FlutterError(
'The Navigator.onPopPage must be provided to use the '
'Navigator.pages API',
),
library: 'widget library',
stack: StackTrace.current,
),
);
}
}
return true;
}());
for (final NavigatorObserver observer in widget.observers) {
assert(observer.navigator == null);
NavigatorObserver._navigators[observer] = this;
}
_effectiveObservers = widget.observers;
// We have to manually extract the inherited widget in initState because
// the current context is not fully initialized.
final HeroControllerScope? heroControllerScope = context
.getElementForInheritedWidgetOfExactType<HeroControllerScope>()
?.widget as HeroControllerScope?;
_updateHeroController(heroControllerScope?.controller);
if (widget.reportsRouteUpdateToEngine) {
SystemNavigator.selectSingleEntryHistory();
}
ServicesBinding.instance.accessibilityFocus.addListener(_recordLastFocus);
_history.addListener(_handleHistoryChanged);
}
// Record the last focused node in route entry.
void _recordLastFocus(){
final _RouteEntry? entry = _history.where(_RouteEntry.isPresentPredicate).lastOrNull;
entry?.lastFocusNode = ServicesBinding.instance.accessibilityFocus.value;
}
// Use [_nextPagelessRestorationScopeId] to get the next id.
final RestorableNum<int> _rawNextPagelessRestorationScopeId = RestorableNum<int>(0);
int get _nextPagelessRestorationScopeId => _rawNextPagelessRestorationScopeId.value++;
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
registerForRestoration(_rawNextPagelessRestorationScopeId, 'id');
registerForRestoration(_serializableHistory, 'history');
// Delete everything in the old history and clear the overlay.
_forcedDisposeAllRouteEntries();
assert(_history.isEmpty);
_overlayKey = GlobalKey<OverlayState>();
// Populate the new history from restoration data.
_history.addAll(_serializableHistory.restoreEntriesForPage(null, this));
for (final Page<dynamic> page in widget.pages) {
final _RouteEntry entry = _RouteEntry(
page.createRoute(context),
pageBased: true,
initialState: _RouteLifecycle.add,
);
assert(
entry.route.settings == page,
'The settings getter of a page-based Route must return a Page object. '
'Please set the settings to the Page in the Page.createRoute method.',
);
_history.add(entry);
_history.addAll(_serializableHistory.restoreEntriesForPage(entry, this));
}
// If there was nothing to restore, we need to process the initial route.
if (!_serializableHistory.hasData) {
String? initialRoute = widget.initialRoute;
if (widget.pages.isEmpty) {
initialRoute = initialRoute ?? Navigator.defaultRouteName;
}
if (initialRoute != null) {
_history.addAll(
widget.onGenerateInitialRoutes(
this,
widget.initialRoute ?? Navigator.defaultRouteName,
).map((Route<dynamic> route) => _RouteEntry(
route,
pageBased: false,
initialState: _RouteLifecycle.add,
restorationInformation: route.settings.name != null
? _RestorationInformation.named(
name: route.settings.name!,
arguments: null,
restorationScopeId: _nextPagelessRestorationScopeId,
)
: null,
),
),
);
}
}
assert(
_history.isNotEmpty,
'All routes returned by onGenerateInitialRoutes are not restorable. '
'Please make sure that all routes returned by onGenerateInitialRoutes '
'have their RouteSettings defined with names that are defined in the '
"app's routes table.",
);
assert(!_debugLocked);
assert(() { _debugLocked = true; return true; }());
_flushHistoryUpdates();
assert(() { _debugLocked = false; return true; }());
}
@override
void didToggleBucket(RestorationBucket? oldBucket) {
super.didToggleBucket(oldBucket);
if (bucket != null) {
_serializableHistory.update(_history);
} else {
_serializableHistory.clear();
}
}
@override
String? get restorationId => widget.restorationScopeId;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_updateHeroController(HeroControllerScope.maybeOf(context));
for (final _RouteEntry entry in _history) {
entry.route.changedExternalState();
}
}
/// Dispose all lingering router entries immediately.
void _forcedDisposeAllRouteEntries() {
_entryWaitingForSubTreeDisposal.removeWhere((_RouteEntry entry) {
entry.forcedDispose();
return true;
});
while (_history.isNotEmpty) {
_disposeRouteEntry(_history.removeLast(), graceful: false);
}
}
static void _disposeRouteEntry(_RouteEntry entry, {required bool graceful}) {
for (final OverlayEntry overlayEntry in entry.route.overlayEntries) {
overlayEntry.remove();
}
if (graceful) {
entry.dispose();
} else {
entry.forcedDispose();
}
}
void _updateHeroController(HeroController? newHeroController) {
if (_heroControllerFromScope != newHeroController) {
if (newHeroController != null) {
// Makes sure the same hero controller is not shared between two navigators.
assert(() {
// It is possible that the hero controller subscribes to an existing
// navigator. We are fine as long as that navigator gives up the hero
// controller at the end of the build.
if (newHeroController.navigator != null) {
final NavigatorState previousOwner = newHeroController.navigator!;
ServicesBinding.instance.addPostFrameCallback((Duration timestamp) {
// We only check if this navigator still owns the hero controller.
if (_heroControllerFromScope == newHeroController) {
final bool hasHeroControllerOwnerShip = _heroControllerFromScope!.navigator == this;
if (!hasHeroControllerOwnerShip ||
previousOwner._heroControllerFromScope == newHeroController) {
final NavigatorState otherOwner = hasHeroControllerOwnerShip
? previousOwner
: _heroControllerFromScope!.navigator!;
FlutterError.reportError(
FlutterErrorDetails(
exception: FlutterError(
'A HeroController can not be shared by multiple Navigators. '
'The Navigators that share the same HeroController are:\n'
'- $this\n'
'- $otherOwner\n'
'Please create a HeroControllerScope for each Navigator or '
'use a HeroControllerScope.none to prevent subtree from '
'receiving a HeroController.',
),
library: 'widget library',
stack: StackTrace.current,
),
);
}
}
}, debugLabel: 'Navigator.checkHeroControllerOwnership');
}
return true;
}());
NavigatorObserver._navigators[newHeroController] = this;
}
// Only unsubscribe the hero controller when it is currently subscribe to
// this navigator.
if (_heroControllerFromScope?.navigator == this) {
NavigatorObserver._navigators[_heroControllerFromScope!] = null;
}
_heroControllerFromScope = newHeroController;
_updateEffectiveObservers();
}
}
void _updateEffectiveObservers() {
if (_heroControllerFromScope != null) {
_effectiveObservers = widget.observers + <NavigatorObserver>[_heroControllerFromScope!];
} else {
_effectiveObservers = widget.observers;
}
}
@override
void didUpdateWidget(Navigator oldWidget) {
super.didUpdateWidget(oldWidget);
assert(() {
if (_usingPagesAPI) {
// This navigator uses page API.
if (widget.pages.isEmpty) {
FlutterError.reportError(
FlutterErrorDetails(
exception: FlutterError(
'The Navigator.pages must not be empty to use the '
'Navigator.pages API',
),
library: 'widget library',
stack: StackTrace.current,
),
);
} else if (widget.onPopPage == null) {
FlutterError.reportError(
FlutterErrorDetails(
exception: FlutterError(
'The Navigator.onPopPage must be provided to use the '
'Navigator.pages API',
),
library: 'widget library',
stack: StackTrace.current,
),
);
}
}
return true;
}());
if (oldWidget.observers != widget.observers) {
for (final NavigatorObserver observer in oldWidget.observers) {
NavigatorObserver._navigators[observer] = null;
}
for (final NavigatorObserver observer in widget.observers) {
assert(observer.navigator == null);
NavigatorObserver._navigators[observer] = this;
}
_updateEffectiveObservers();
}
if (oldWidget.pages != widget.pages && !restorePending) {
assert(() {
if (widget.pages.isEmpty) {
FlutterError.reportError(
FlutterErrorDetails(
exception: FlutterError(
'The Navigator.pages must not be empty to use the '
'Navigator.pages API',
),
library: 'widget library',
stack: StackTrace.current,
),
);
}
return true;
}());
_updatePages();
}
for (final _RouteEntry entry in _history) {
entry.route.changedExternalState();
}
}
void _debugCheckDuplicatedPageKeys() {
assert(() {
final Set<Key> keyReservation = <Key>{};
for (final Page<dynamic> page in widget.pages) {
final LocalKey? key = page.key;
if (key != null) {
assert(!keyReservation.contains(key));
keyReservation.add(key);
}
}
return true;
}());
}
@override
void deactivate() {
for (final NavigatorObserver observer in _effectiveObservers) {
NavigatorObserver._navigators[observer] = null;
}
super.deactivate();
}
@override
void activate() {
super.activate();
for (final NavigatorObserver observer in _effectiveObservers) {
assert(observer.navigator == null);
NavigatorObserver._navigators[observer] = this;
}
}
@override
void dispose() {
assert(!_debugLocked);
assert(() {
_debugLocked = true;
return true;
}());
assert(() {
for (final NavigatorObserver observer in _effectiveObservers) {
assert(observer.navigator != this);
}
return true;
}());
_updateHeroController(null);
focusNode.dispose();
_forcedDisposeAllRouteEntries();
_rawNextPagelessRestorationScopeId.dispose();
_serializableHistory.dispose();
userGestureInProgressNotifier.dispose();
ServicesBinding.instance.accessibilityFocus.removeListener(_recordLastFocus);
_history.removeListener(_handleHistoryChanged);
_history.dispose();
super.dispose();
// don't unlock, so that the object becomes unusable
assert(_debugLocked);
}
/// The overlay this navigator uses for its visual presentation.
OverlayState? get overlay => _overlayKey.currentState;
Iterable<OverlayEntry> get _allRouteOverlayEntries {
return <OverlayEntry>[
for (final _RouteEntry entry in _history)
...entry.route.overlayEntries,
];
}
String? _lastAnnouncedRouteName;
bool _debugUpdatingPage = false;
void _updatePages() {
assert(() {
assert(!_debugUpdatingPage);
_debugCheckDuplicatedPageKeys();
_debugUpdatingPage = true;
return true;
}());
// This attempts to diff the new pages list (widget.pages) with
// the old _RouteEntry(s) list (_history), and produces a new list of
// _RouteEntry(s) to be the new list of _history. This method roughly
// follows the same outline of RenderObjectElement.updateChildren.
//
// The cases it tries to optimize for are:
// - the old list is empty
// - All the pages in the new list can match the page-based routes in the old
// list, and their orders are the same.
// - there is an insertion or removal of one or more page-based route in
// only one place in the list
// If a page-based route with a key is in both lists, it will be synced.
// Page-based routes without keys might be synced but there is no guarantee.
// The general approach is to sync the entire new list backwards, as follows:
// 1. Walk the lists from the bottom, syncing nodes, and record pageless routes,
// until you no longer have matching nodes.
// 2. Walk the lists from the top, without syncing nodes, until you no
// longer have matching nodes. We'll sync these nodes at the end. We
// don't sync them now because we want to sync all the nodes in order
// from beginning to end.
// At this point we narrowed the old and new lists to the point
// where the nodes no longer match.
// 3. Walk the narrowed part of the old list to get the list of
// keys.
// 4. Walk the narrowed part of the new list forwards:
// * Create a new _RouteEntry for non-keyed items and record them for
// transitionDelegate.
// * Sync keyed items with the source if it exists.
// 5. Walk the narrowed part of the old list again to records the
// _RouteEntry(s), as well as pageless routes, needed to be removed for
// transitionDelegate.
// 5. Walk the top of the list again, syncing the nodes and recording
// pageless routes.
// 6. Use transitionDelegate for explicit decisions on how _RouteEntry(s)
// transition in or off the screens.
// 7. Fill pageless routes back into the new history.
bool needsExplicitDecision = false;
int newPagesBottom = 0;
int oldEntriesBottom = 0;
int newPagesTop = widget.pages.length - 1;
int oldEntriesTop = _history.length - 1;
final List<_RouteEntry> newHistory = <_RouteEntry>[];
final Map<_RouteEntry?, List<_RouteEntry>> pageRouteToPagelessRoutes = <_RouteEntry?, List<_RouteEntry>>{};
// Updates the bottom of the list.
_RouteEntry? previousOldPageRouteEntry;
while (oldEntriesBottom <= oldEntriesTop) {
final _RouteEntry oldEntry = _history[oldEntriesBottom];
assert(oldEntry.currentState != _RouteLifecycle.disposed);
// Records pageless route. The bottom most pageless routes will be
// stored in key = null.
if (!oldEntry.pageBased) {
final List<_RouteEntry> pagelessRoutes = pageRouteToPagelessRoutes.putIfAbsent(
previousOldPageRouteEntry,
() => <_RouteEntry>[],
);
pagelessRoutes.add(oldEntry);
oldEntriesBottom += 1;
continue;
}
if (newPagesBottom > newPagesTop) {
break;
}
final Page<dynamic> newPage = widget.pages[newPagesBottom];
if (!oldEntry.canUpdateFrom(newPage)) {
break;
}
previousOldPageRouteEntry = oldEntry;
oldEntry.route._updateSettings(newPage);
newHistory.add(oldEntry);
newPagesBottom += 1;
oldEntriesBottom += 1;
}
final List<_RouteEntry> unattachedPagelessRoutes=<_RouteEntry>[];
// Scans the top of the list until we found a page-based route that cannot be
// updated.
while ((oldEntriesBottom <= oldEntriesTop) && (newPagesBottom <= newPagesTop)) {
final _RouteEntry oldEntry = _history[oldEntriesTop];
assert(oldEntry.currentState != _RouteLifecycle.disposed);
if (!oldEntry.pageBased) {
unattachedPagelessRoutes.add(oldEntry);
oldEntriesTop -= 1;
continue;
}
final Page<dynamic> newPage = widget.pages[newPagesTop];
if (!oldEntry.canUpdateFrom(newPage)) {
break;
}
// We found the page for all the consecutive pageless routes below. Attach these
// pageless routes to the page.
if (unattachedPagelessRoutes.isNotEmpty) {
pageRouteToPagelessRoutes.putIfAbsent(
oldEntry,
() => List<_RouteEntry>.from(unattachedPagelessRoutes),
);
unattachedPagelessRoutes.clear();
}
oldEntriesTop -= 1;
newPagesTop -= 1;
}
// Reverts the pageless routes that cannot be updated.
oldEntriesTop += unattachedPagelessRoutes.length;
// Scans middle of the old entries and records the page key to old entry map.
int oldEntriesBottomToScan = oldEntriesBottom;
final Map<LocalKey, _RouteEntry> pageKeyToOldEntry = <LocalKey, _RouteEntry>{};
// This set contains entries that are transitioning out but are still in
// the route stack.
final Set<_RouteEntry> phantomEntries = <_RouteEntry>{};
while (oldEntriesBottomToScan <= oldEntriesTop) {
final _RouteEntry oldEntry = _history[oldEntriesBottomToScan];
oldEntriesBottomToScan += 1;
assert(
oldEntry.currentState != _RouteLifecycle.disposed,
);
// Pageless routes will be recorded when we update the middle of the old
// list.
if (!oldEntry.pageBased) {
continue;
}
final Page<dynamic> page = oldEntry.route.settings as Page<dynamic>;
if (page.key == null) {
continue;
}
if (!oldEntry.willBePresent) {
phantomEntries.add(oldEntry);
continue;
}
assert(!pageKeyToOldEntry.containsKey(page.key));
pageKeyToOldEntry[page.key!] = oldEntry;
}
// Updates the middle of the list.
while (newPagesBottom <= newPagesTop) {
final Page<dynamic> nextPage = widget.pages[newPagesBottom];
newPagesBottom += 1;
if (
nextPage.key == null ||
!pageKeyToOldEntry.containsKey(nextPage.key) ||
!pageKeyToOldEntry[nextPage.key]!.canUpdateFrom(nextPage)
) {
// There is no matching key in the old history, we need to create a new
// route and wait for the transition delegate to decide how to add
// it into the history.
final _RouteEntry newEntry = _RouteEntry(
nextPage.createRoute(context),
pageBased: true,
initialState: _RouteLifecycle.staging,
);
needsExplicitDecision = true;
assert(
newEntry.route.settings == nextPage,
'The settings getter of a page-based Route must return a Page object. '
'Please set the settings to the Page in the Page.createRoute method.',
);
newHistory.add(newEntry);
} else {
// Removes the key from pageKeyToOldEntry to indicate it is taken.
final _RouteEntry matchingEntry = pageKeyToOldEntry.remove(nextPage.key)!;
assert(matchingEntry.canUpdateFrom(nextPage));
matchingEntry.route._updateSettings(nextPage);
newHistory.add(matchingEntry);
}
}
// Any remaining old routes that do not have a match will need to be removed.
final Map<RouteTransitionRecord?, RouteTransitionRecord> locationToExitingPageRoute = <RouteTransitionRecord?, RouteTransitionRecord>{};
while (oldEntriesBottom <= oldEntriesTop) {
final _RouteEntry potentialEntryToRemove = _history[oldEntriesBottom];
oldEntriesBottom += 1;
if (!potentialEntryToRemove.pageBased) {
assert(previousOldPageRouteEntry != null);
final List<_RouteEntry> pagelessRoutes = pageRouteToPagelessRoutes
.putIfAbsent(
previousOldPageRouteEntry,
() => <_RouteEntry>[],
);
pagelessRoutes.add(potentialEntryToRemove);
if (previousOldPageRouteEntry!.isWaitingForExitingDecision && potentialEntryToRemove.willBePresent) {
potentialEntryToRemove.markNeedsExitingDecision();
}
continue;
}
final Page<dynamic> potentialPageToRemove = potentialEntryToRemove.route.settings as Page<dynamic>;
// Marks for transition delegate to remove if this old page does not have
// a key, was not taken during updating the middle of new page, or is
// already transitioning out.
if (potentialPageToRemove.key == null ||
pageKeyToOldEntry.containsKey(potentialPageToRemove.key) ||
phantomEntries.contains(potentialEntryToRemove)) {
locationToExitingPageRoute[previousOldPageRouteEntry] = potentialEntryToRemove;
// We only need a decision if it has not already been popped.
if (potentialEntryToRemove.willBePresent) {
potentialEntryToRemove.markNeedsExitingDecision();
}
}
previousOldPageRouteEntry = potentialEntryToRemove;
}
// We've scanned the whole list.
assert(oldEntriesBottom == oldEntriesTop + 1);
assert(newPagesBottom == newPagesTop + 1);
newPagesTop = widget.pages.length - 1;
oldEntriesTop = _history.length - 1;
// Verifies we either reach the bottom or the oldEntriesBottom must be updatable
// by newPagesBottom.
assert(() {
if (oldEntriesBottom <= oldEntriesTop) {
return newPagesBottom <= newPagesTop &&
_history[oldEntriesBottom].pageBased &&
_history[oldEntriesBottom].canUpdateFrom(widget.pages[newPagesBottom]);
} else {
return newPagesBottom > newPagesTop;
}
}());
// Updates the top of the list.
while ((oldEntriesBottom <= oldEntriesTop) && (newPagesBottom <= newPagesTop)) {
final _RouteEntry oldEntry = _history[oldEntriesBottom];
assert(oldEntry.currentState != _RouteLifecycle.disposed);
if (!oldEntry.pageBased) {
assert(previousOldPageRouteEntry != null);
final List<_RouteEntry> pagelessRoutes = pageRouteToPagelessRoutes
.putIfAbsent(
previousOldPageRouteEntry,
() => <_RouteEntry>[],
);
pagelessRoutes.add(oldEntry);
continue;
}
previousOldPageRouteEntry = oldEntry;
final Page<dynamic> newPage = widget.pages[newPagesBottom];
assert(oldEntry.canUpdateFrom(newPage));
oldEntry.route._updateSettings(newPage);
newHistory.add(oldEntry);
oldEntriesBottom += 1;
newPagesBottom += 1;
}
// Finally, uses transition delegate to make explicit decision if needed.
needsExplicitDecision = needsExplicitDecision || locationToExitingPageRoute.isNotEmpty;
Iterable<_RouteEntry> results = newHistory;
if (needsExplicitDecision) {
results = widget.transitionDelegate._transition(
newPageRouteHistory: newHistory,
locationToExitingPageRoute: locationToExitingPageRoute,
pageRouteToPagelessRoutes: pageRouteToPagelessRoutes,
).cast<_RouteEntry>();
}
_history.clear();
// Adds the leading pageless routes if there is any.
if (pageRouteToPagelessRoutes.containsKey(null)) {
_history.addAll(pageRouteToPagelessRoutes[null]!);
}
for (final _RouteEntry result in results) {
_history.add(result);
if (pageRouteToPagelessRoutes.containsKey(result)) {
_history.addAll(pageRouteToPagelessRoutes[result]!);
}
}
assert(() {_debugUpdatingPage = false; return true;}());
assert(() { _debugLocked = true; return true; }());
_flushHistoryUpdates();
assert(() { _debugLocked = false; return true; }());
}
bool _flushingHistory = false;
void _flushHistoryUpdates({bool rearrangeOverlay = true}) {
assert(_debugLocked && !_debugUpdatingPage);
_flushingHistory = true;
// Clean up the list, sending updates to the routes that changed. Notably,
// we don't send the didChangePrevious/didChangeNext updates to those that
// did not change at this point, because we're not yet sure exactly what the
// routes will be at the end of the day (some might get disposed).
int index = _history.length - 1;
_RouteEntry? next;
_RouteEntry? entry = _history[index];
_RouteEntry? previous = index > 0 ? _history[index - 1] : null;
bool canRemoveOrAdd = false; // Whether there is a fully opaque route on top to silently remove or add route underneath.
Route<dynamic>? poppedRoute; // The route that should trigger didPopNext on the top active route.
bool seenTopActiveRoute = false; // Whether we've seen the route that would get didPopNext.
final List<_RouteEntry> toBeDisposed = <_RouteEntry>[];
while (index >= 0) {
switch (entry!.currentState) {
case _RouteLifecycle.add:
assert(rearrangeOverlay);
entry.handleAdd(
navigator: this,
previousPresent: _getRouteBefore(index - 1, _RouteEntry.isPresentPredicate)?.route,
);
assert(entry.currentState == _RouteLifecycle.adding);
continue;
case _RouteLifecycle.adding:
if (canRemoveOrAdd || next == null) {
entry.didAdd(
navigator: this,
isNewFirst: next == null,
);
assert(entry.currentState == _RouteLifecycle.idle);
continue;
}
case _RouteLifecycle.push:
case _RouteLifecycle.pushReplace:
case _RouteLifecycle.replace:
assert(rearrangeOverlay);
entry.handlePush(
navigator: this,
previous: previous?.route,
previousPresent: _getRouteBefore(index - 1, _RouteEntry.isPresentPredicate)?.route,
isNewFirst: next == null,
);
assert(entry.currentState != _RouteLifecycle.push);
assert(entry.currentState != _RouteLifecycle.pushReplace);
assert(entry.currentState != _RouteLifecycle.replace);
if (entry.currentState == _RouteLifecycle.idle) {
continue;
}
case _RouteLifecycle.pushing: // Will exit this state when animation completes.
if (!seenTopActiveRoute && poppedRoute != null) {
entry.handleDidPopNext(poppedRoute);
}
seenTopActiveRoute = true;
case _RouteLifecycle.idle:
if (!seenTopActiveRoute && poppedRoute != null) {
entry.handleDidPopNext(poppedRoute);
}
seenTopActiveRoute = true;
// This route is idle, so we are allowed to remove subsequent (earlier)
// routes that are waiting to be removed silently:
canRemoveOrAdd = true;
case _RouteLifecycle.pop:
if (!entry.handlePop(
navigator: this,
previousPresent: _getRouteBefore(index, _RouteEntry.willBePresentPredicate)?.route)){
assert(entry.currentState == _RouteLifecycle.idle);
continue;
}
if (!seenTopActiveRoute) {
if (poppedRoute != null) {
entry.handleDidPopNext(poppedRoute);
}
poppedRoute = entry.route;
}
_observedRouteDeletions.add(
_NavigatorPopObservation(entry.route, _getRouteBefore(index, _RouteEntry.willBePresentPredicate)?.route),
);
if (entry.currentState == _RouteLifecycle.dispose) {
// The pop finished synchronously. This can happen if transition
// duration is zero.
continue;
}
assert(entry.currentState == _RouteLifecycle.popping);
canRemoveOrAdd = true;
case _RouteLifecycle.popping:
// Will exit this state when animation completes.
break;
case _RouteLifecycle.complete:
entry.handleComplete();
assert(entry.currentState == _RouteLifecycle.remove);
continue;
case _RouteLifecycle.remove:
if (!seenTopActiveRoute) {
if (poppedRoute != null) {
entry.route.didPopNext(poppedRoute);
}
poppedRoute = null;
}
entry.handleRemoval(
navigator: this,
previousPresent: _getRouteBefore(index, _RouteEntry.willBePresentPredicate)?.route,
);
assert(entry.currentState == _RouteLifecycle.removing);
continue;
case _RouteLifecycle.removing:
if (!canRemoveOrAdd && next != null) {
// We aren't allowed to remove this route yet.
break;
}
entry.currentState = _RouteLifecycle.dispose;
continue;
case _RouteLifecycle.dispose:
// Delay disposal until didChangeNext/didChangePrevious have been sent.
toBeDisposed.add(_history.removeAt(index));
entry = next;
case _RouteLifecycle.disposing:
case _RouteLifecycle.disposed:
case _RouteLifecycle.staging:
assert(false);
}
index -= 1;
next = entry;
entry = previous;
previous = index > 0 ? _history[index - 1] : null;
}
// Informs navigator observers about route changes.
_flushObserverNotifications();
// Now that the list is clean, send the didChangeNext/didChangePrevious
// notifications.
_flushRouteAnnouncement();
// Announce route name changes.
if (widget.reportsRouteUpdateToEngine) {
final _RouteEntry? lastEntry = _lastRouteEntryWhereOrNull(_RouteEntry.isPresentPredicate);
final String? routeName = lastEntry?.route.settings.name;
if (routeName != null && routeName != _lastAnnouncedRouteName) {
SystemNavigator.routeInformationUpdated(uri: Uri.parse(routeName));
_lastAnnouncedRouteName = routeName;
}
}
// Lastly, removes the overlay entries of all marked entries and disposes
// them.
for (final _RouteEntry entry in toBeDisposed) {
_disposeRouteEntry(entry, graceful: true);
}
if (rearrangeOverlay) {
overlay?.rearrange(_allRouteOverlayEntries);
}
if (bucket != null) {
_serializableHistory.update(_history);
}
_flushingHistory = false;
}
void _flushObserverNotifications() {
if (_effectiveObservers.isEmpty) {
_observedRouteDeletions.clear();
_observedRouteAdditions.clear();
return;
}
while (_observedRouteAdditions.isNotEmpty) {
final _NavigatorObservation observation = _observedRouteAdditions.removeLast();
_effectiveObservers.forEach(observation.notify);
}
while (_observedRouteDeletions.isNotEmpty) {
final _NavigatorObservation observation = _observedRouteDeletions.removeFirst();
_effectiveObservers.forEach(observation.notify);
}
}
void _flushRouteAnnouncement() {
int index = _history.length - 1;
while (index >= 0) {
final _RouteEntry entry = _history[index];
if (!entry.suitableForAnnouncement) {
index -= 1;
continue;
}
final _RouteEntry? next = _getRouteAfter(index + 1, _RouteEntry.suitableForTransitionAnimationPredicate);
if (next?.route != entry.lastAnnouncedNextRoute) {
if (entry.shouldAnnounceChangeToNext(next?.route)) {
entry.route.didChangeNext(next?.route);
}
entry.lastAnnouncedNextRoute = next?.route;
}
final _RouteEntry? previous = _getRouteBefore(index - 1, _RouteEntry.suitableForTransitionAnimationPredicate);
if (previous?.route != entry.lastAnnouncedPreviousRoute) {
entry.route.didChangePrevious(previous?.route);
entry.lastAnnouncedPreviousRoute = previous?.route;
}
index -= 1;
}
}
_RouteEntry? _getRouteBefore(int index, _RouteEntryPredicate predicate) {
index = _getIndexBefore(index, predicate);
return index >= 0 ? _history[index] : null;
}
int _getIndexBefore(int index, _RouteEntryPredicate predicate) {
while (index >= 0 && !predicate(_history[index])) {
index -= 1;
}
return index;
}
_RouteEntry? _getRouteAfter(int index, _RouteEntryPredicate predicate) {
while (index < _history.length && !predicate(_history[index])) {
index += 1;
}
return index < _history.length ? _history[index] : null;
}
Route<T?>? _routeNamed<T>(String name, { required Object? arguments, bool allowNull = false }) {
assert(!_debugLocked);
if (allowNull && widget.onGenerateRoute == null) {
return null;
}
assert(() {
if (widget.onGenerateRoute == null) {
throw FlutterError(
'Navigator.onGenerateRoute was null, but the route named "$name" was referenced.\n'
'To use the Navigator API with named routes (pushNamed, pushReplacementNamed, or '
'pushNamedAndRemoveUntil), the Navigator must be provided with an '
'onGenerateRoute handler.\n'
'The Navigator was:\n'
' $this',
);
}
return true;
}());
final RouteSettings settings = RouteSettings(
name: name,
arguments: arguments,
);
Route<T?>? route = widget.onGenerateRoute!(settings) as Route<T?>?;
if (route == null && !allowNull) {
assert(() {
if (widget.onUnknownRoute == null) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Navigator.onGenerateRoute returned null when requested to build route "$name".'),
ErrorDescription(
'The onGenerateRoute callback must never return null, unless an onUnknownRoute '
'callback is provided as well.',
),
DiagnosticsProperty<NavigatorState>('The Navigator was', this, style: DiagnosticsTreeStyle.errorProperty),
]);
}
return true;
}());
route = widget.onUnknownRoute!(settings) as Route<T?>?;
assert(() {
if (route == null) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Navigator.onUnknownRoute returned null when requested to build route "$name".'),
ErrorDescription('The onUnknownRoute callback must never return null.'),
DiagnosticsProperty<NavigatorState>('The Navigator was', this, style: DiagnosticsTreeStyle.errorProperty),
]);
}
return true;
}());
}
assert(route != null || allowNull);
return route;
}
/// Push a named route onto the navigator.
///
/// {@macro flutter.widgets.navigator.pushNamed}
///
/// {@macro flutter.widgets.navigator.pushNamed.returnValue}
///
/// {@macro flutter.widgets.Navigator.pushNamed}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _aaronBurrSir() {
/// navigator.pushNamed('/nyc/1776');
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePushNamed], which pushes a route that can be restored
/// during state restoration.
@optionalTypeArgs
Future<T?> pushNamed<T extends Object?>(
String routeName, {
Object? arguments,
}) {
return push<T?>(_routeNamed<T>(routeName, arguments: arguments)!);
}
/// Push a named route onto the navigator.
///
/// {@macro flutter.widgets.navigator.restorablePushNamed}
///
/// {@macro flutter.widgets.navigator.pushNamed}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.arguments}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _openDetails() {
/// navigator.restorablePushNamed('/nyc/1776');
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
String restorablePushNamed<T extends Object?>(
String routeName, {
Object? arguments,
}) {
assert(debugIsSerializableForRestoration(arguments), 'The arguments object must be serializable via the StandardMessageCodec.');
final _RouteEntry entry = _RestorationInformation.named(
name: routeName,
arguments: arguments,
restorationScopeId: _nextPagelessRestorationScopeId,
).toRouteEntry(this, initialState: _RouteLifecycle.push);
_pushEntry(entry);
return entry.restorationId!;
}
/// Replace the current route of the navigator by pushing the route named
/// [routeName] and then disposing the previous route once the new route has
/// finished animating in.
///
/// {@macro flutter.widgets.navigator.pushReplacementNamed}
///
/// {@macro flutter.widgets.navigator.pushNamed.returnValue}
///
/// {@macro flutter.widgets.Navigator.pushNamed}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _startBike() {
/// navigator.pushReplacementNamed('/jouett/1781');
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePushReplacementNamed], which pushes a replacement route that
/// can be restored during state restoration.
@optionalTypeArgs
Future<T?> pushReplacementNamed<T extends Object?, TO extends Object?>(
String routeName, {
TO? result,
Object? arguments,
}) {
return pushReplacement<T?, TO>(_routeNamed<T>(routeName, arguments: arguments)!, result: result);
}
/// Replace the current route of the navigator by pushing the route named
/// [routeName] and then disposing the previous route once the new route has
/// finished animating in.
///
/// {@macro flutter.widgets.navigator.restorablePushReplacementNamed}
///
/// {@macro flutter.widgets.navigator.pushReplacementNamed}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.arguments}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _startCar() {
/// navigator.restorablePushReplacementNamed('/jouett/1781');
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
String restorablePushReplacementNamed<T extends Object?, TO extends Object?>(
String routeName, {
TO? result,
Object? arguments,
}) {
assert(debugIsSerializableForRestoration(arguments), 'The arguments object must be serializable via the StandardMessageCodec.');
final _RouteEntry entry = _RestorationInformation.named(
name: routeName,
arguments: arguments,
restorationScopeId: _nextPagelessRestorationScopeId,
).toRouteEntry(this, initialState: _RouteLifecycle.pushReplace);
_pushReplacementEntry(entry, result);
return entry.restorationId!;
}
/// Pop the current route off the navigator and push a named route in its
/// place.
///
/// {@macro flutter.widgets.navigator.popAndPushNamed}
///
/// {@macro flutter.widgets.navigator.pushNamed.returnValue}
///
/// {@macro flutter.widgets.Navigator.pushNamed}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _begin() {
/// navigator.popAndPushNamed('/nyc/1776');
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePopAndPushNamed], which pushes a new route that can be
/// restored during state restoration.
@optionalTypeArgs
Future<T?> popAndPushNamed<T extends Object?, TO extends Object?>(
String routeName, {
TO? result,
Object? arguments,
}) {
pop<TO>(result);
return pushNamed<T>(routeName, arguments: arguments);
}
/// Pop the current route off the navigator and push a named route in its
/// place.
///
/// {@macro flutter.widgets.navigator.restorablePopAndPushNamed}
///
/// {@macro flutter.widgets.navigator.popAndPushNamed}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.arguments}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _end() {
/// navigator.restorablePopAndPushNamed('/nyc/1776');
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
String restorablePopAndPushNamed<T extends Object?, TO extends Object?>(
String routeName, {
TO? result,
Object? arguments,
}) {
pop<TO>(result);
return restorablePushNamed(routeName, arguments: arguments);
}
/// Push the route with the given name onto the navigator, and then remove all
/// the previous routes until the `predicate` returns true.
///
/// {@macro flutter.widgets.navigator.pushNamedAndRemoveUntil}
///
/// {@macro flutter.widgets.navigator.pushNamed.returnValue}
///
/// {@macro flutter.widgets.Navigator.pushNamed}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _handleOpenCalendar() {
/// navigator.pushNamedAndRemoveUntil('/calendar', ModalRoute.withName('/'));
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePushNamedAndRemoveUntil], which pushes a new route that can
/// be restored during state restoration.
@optionalTypeArgs
Future<T?> pushNamedAndRemoveUntil<T extends Object?>(
String newRouteName,
RoutePredicate predicate, {
Object? arguments,
}) {
return pushAndRemoveUntil<T?>(_routeNamed<T>(newRouteName, arguments: arguments)!, predicate);
}
/// Push the route with the given name onto the navigator, and then remove all
/// the previous routes until the `predicate` returns true.
///
/// {@macro flutter.widgets.navigator.restorablePushNamedAndRemoveUntil}
///
/// {@macro flutter.widgets.navigator.pushNamedAndRemoveUntil}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.arguments}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _openCalendar() {
/// navigator.restorablePushNamedAndRemoveUntil('/calendar', ModalRoute.withName('/'));
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
String restorablePushNamedAndRemoveUntil<T extends Object?>(
String newRouteName,
RoutePredicate predicate, {
Object? arguments,
}) {
assert(debugIsSerializableForRestoration(arguments), 'The arguments object must be serializable via the StandardMessageCodec.');
final _RouteEntry entry = _RestorationInformation.named(
name: newRouteName,
arguments: arguments,
restorationScopeId: _nextPagelessRestorationScopeId,
).toRouteEntry(this, initialState: _RouteLifecycle.push);
_pushEntryAndRemoveUntil(entry, predicate);
return entry.restorationId!;
}
/// Push the given route onto the navigator.
///
/// {@macro flutter.widgets.navigator.push}
///
/// {@macro flutter.widgets.navigator.pushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _openPage() {
/// navigator.push<void>(
/// MaterialPageRoute<void>(
/// builder: (BuildContext context) => const MyPage(),
/// ),
/// );
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePush], which pushes a route that can be restored during
/// state restoration.
@optionalTypeArgs
Future<T?> push<T extends Object?>(Route<T> route) {
_pushEntry(_RouteEntry(route, pageBased: false, initialState: _RouteLifecycle.push));
return route.popped;
}
bool _debugIsStaticCallback(Function callback) {
bool result = false;
assert(() {
// TODO(goderbauer): remove the kIsWeb check when https://github.com/flutter/flutter/issues/33615 is resolved.
result = kIsWeb || ui.PluginUtilities.getCallbackHandle(callback) != null;
return true;
}());
return result;
}
/// Push a new route onto the navigator.
///
/// {@macro flutter.widgets.navigator.restorablePush}
///
/// {@macro flutter.widgets.navigator.push}
///
/// {@macro flutter.widgets.Navigator.restorablePush}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool dartpad}
/// Typical usage is as follows:
///
/// ** See code in examples/api/lib/widgets/navigator/navigator_state.restorable_push.0.dart **
/// {@end-tool}
@optionalTypeArgs
String restorablePush<T extends Object?>(RestorableRouteBuilder<T> routeBuilder, {Object? arguments}) {
assert(_debugIsStaticCallback(routeBuilder), 'The provided routeBuilder must be a static function.');
assert(debugIsSerializableForRestoration(arguments), 'The arguments object must be serializable via the StandardMessageCodec.');
final _RouteEntry entry = _RestorationInformation.anonymous(
routeBuilder: routeBuilder,
arguments: arguments,
restorationScopeId: _nextPagelessRestorationScopeId,
).toRouteEntry(this, initialState: _RouteLifecycle.push);
_pushEntry(entry);
return entry.restorationId!;
}
void _pushEntry(_RouteEntry entry) {
assert(!_debugLocked);
assert(() {
_debugLocked = true;
return true;
}());
assert(entry.route._navigator == null);
assert(entry.currentState == _RouteLifecycle.push);
_history.add(entry);
_flushHistoryUpdates();
assert(() {
_debugLocked = false;
return true;
}());
_afterNavigation(entry.route);
}
void _afterNavigation(Route<dynamic>? route) {
if (!kReleaseMode) {
// Among other uses, performance tools use this event to ensure that perf
// stats reflect the time interval since the last navigation event
// occurred, ensuring that stats only reflect the current page.
Map<String, dynamic>? routeJsonable;
if (route != null) {
routeJsonable = <String, dynamic>{};
final String description;
if (route is TransitionRoute<dynamic>) {
final TransitionRoute<dynamic> transitionRoute = route;
description = transitionRoute.debugLabel;
} else {
description = '$route';
}
routeJsonable['description'] = description;
final RouteSettings settings = route.settings;
final Map<String, dynamic> settingsJsonable = <String, dynamic> {
'name': settings.name,
};
if (settings.arguments != null) {
settingsJsonable['arguments'] = jsonEncode(
settings.arguments,
toEncodable: (Object? object) => '$object',
);
}
routeJsonable['settings'] = settingsJsonable;
}
developer.postEvent('Flutter.Navigation', <String, dynamic>{
'route': routeJsonable,
});
}
_cancelActivePointers();
}
/// Replace the current route of the navigator by pushing the given route and
/// then disposing the previous route once the new route has finished
/// animating in.
///
/// {@macro flutter.widgets.navigator.pushReplacement}
///
/// {@macro flutter.widgets.navigator.pushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _doOpenPage() {
/// navigator.pushReplacement<void, void>(
/// MaterialPageRoute<void>(
/// builder: (BuildContext context) => const MyHomePage(),
/// ),
/// );
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [restorablePushReplacement], which pushes a replacement route that can
/// be restored during state restoration.
@optionalTypeArgs
Future<T?> pushReplacement<T extends Object?, TO extends Object?>(Route<T> newRoute, { TO? result }) {
assert(newRoute._navigator == null);
_pushReplacementEntry(_RouteEntry(newRoute, pageBased: false, initialState: _RouteLifecycle.pushReplace), result);
return newRoute.popped;
}
/// Replace the current route of the navigator by pushing a new route and
/// then disposing the previous route once the new route has finished
/// animating in.
///
/// {@macro flutter.widgets.navigator.restorablePushReplacement}
///
/// {@macro flutter.widgets.navigator.pushReplacement}
///
/// {@macro flutter.widgets.Navigator.restorablePush}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool dartpad}
/// Typical usage is as follows:
///
/// ** See code in examples/api/lib/widgets/navigator/navigator_state.restorable_push_replacement.0.dart **
/// {@end-tool}
@optionalTypeArgs
String restorablePushReplacement<T extends Object?, TO extends Object?>(RestorableRouteBuilder<T> routeBuilder, { TO? result, Object? arguments }) {
assert(_debugIsStaticCallback(routeBuilder), 'The provided routeBuilder must be a static function.');
assert(debugIsSerializableForRestoration(arguments), 'The arguments object must be serializable via the StandardMessageCodec.');
final _RouteEntry entry = _RestorationInformation.anonymous(
routeBuilder: routeBuilder,
arguments: arguments,
restorationScopeId: _nextPagelessRestorationScopeId,
).toRouteEntry(this, initialState: _RouteLifecycle.pushReplace);
_pushReplacementEntry(entry, result);
return entry.restorationId!;
}
void _pushReplacementEntry<TO extends Object?>(_RouteEntry entry, TO? result) {
assert(!_debugLocked);
assert(() {
_debugLocked = true;
return true;
}());
assert(entry.route._navigator == null);
assert(_history.isNotEmpty);
assert(_history.any(_RouteEntry.isPresentPredicate), 'Navigator has no active routes to replace.');
assert(entry.currentState == _RouteLifecycle.pushReplace);
_history.lastWhere(_RouteEntry.isPresentPredicate).complete(result, isReplaced: true);
_history.add(entry);
_flushHistoryUpdates();
assert(() {
_debugLocked = false;
return true;
}());
_afterNavigation(entry.route);
}
/// Push the given route onto the navigator, and then remove all the previous
/// routes until the `predicate` returns true.
///
/// {@macro flutter.widgets.navigator.pushAndRemoveUntil}
///
/// {@macro flutter.widgets.navigator.pushNamed.returnValue}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _resetAndOpenPage() {
/// navigator.pushAndRemoveUntil<void>(
/// MaterialPageRoute<void>(builder: (BuildContext context) => const MyHomePage()),
/// ModalRoute.withName('/'),
/// );
/// }
/// ```
/// {@end-tool}
///
///
/// See also:
///
/// * [restorablePushAndRemoveUntil], which pushes a route that can be
/// restored during state restoration.
@optionalTypeArgs
Future<T?> pushAndRemoveUntil<T extends Object?>(Route<T> newRoute, RoutePredicate predicate) {
assert(newRoute._navigator == null);
assert(newRoute.overlayEntries.isEmpty);
_pushEntryAndRemoveUntil(_RouteEntry(newRoute, pageBased: false, initialState: _RouteLifecycle.push), predicate);
return newRoute.popped;
}
/// Push a new route onto the navigator, and then remove all the previous
/// routes until the `predicate` returns true.
///
/// {@macro flutter.widgets.navigator.restorablePushAndRemoveUntil}
///
/// {@macro flutter.widgets.navigator.pushAndRemoveUntil}
///
/// {@macro flutter.widgets.Navigator.restorablePush}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
///
/// {@tool dartpad}
/// Typical usage is as follows:
///
/// ** See code in examples/api/lib/widgets/navigator/navigator_state.restorable_push_and_remove_until.0.dart **
/// {@end-tool}
@optionalTypeArgs
String restorablePushAndRemoveUntil<T extends Object?>(RestorableRouteBuilder<T> newRouteBuilder, RoutePredicate predicate, {Object? arguments}) {
assert(_debugIsStaticCallback(newRouteBuilder), 'The provided routeBuilder must be a static function.');
assert(debugIsSerializableForRestoration(arguments), 'The arguments object must be serializable via the StandardMessageCodec.');
final _RouteEntry entry = _RestorationInformation.anonymous(
routeBuilder: newRouteBuilder,
arguments: arguments,
restorationScopeId: _nextPagelessRestorationScopeId,
).toRouteEntry(this, initialState: _RouteLifecycle.push);
_pushEntryAndRemoveUntil(entry, predicate);
return entry.restorationId!;
}
void _pushEntryAndRemoveUntil(_RouteEntry entry, RoutePredicate predicate) {
assert(!_debugLocked);
assert(() {
_debugLocked = true;
return true;
}());
assert(entry.route._navigator == null);
assert(entry.route.overlayEntries.isEmpty);
assert(entry.currentState == _RouteLifecycle.push);
int index = _history.length - 1;
_history.add(entry);
while (index >= 0 && !predicate(_history[index].route)) {
if (_history[index].isPresent) {
_history[index].remove();
}
index -= 1;
}
_flushHistoryUpdates();
assert(() {
_debugLocked = false;
return true;
}());
_afterNavigation(entry.route);
}
/// Replaces a route on the navigator with a new route.
///
/// {@macro flutter.widgets.navigator.replace}
///
/// See also:
///
/// * [replaceRouteBelow], which is the same but identifies the route to be
/// removed by reference to the route above it, rather than directly.
/// * [restorableReplace], which adds a replacement route that can be
/// restored during state restoration.
@optionalTypeArgs
void replace<T extends Object?>({ required Route<dynamic> oldRoute, required Route<T> newRoute }) {
assert(!_debugLocked);
assert(oldRoute._navigator == this);
_replaceEntry(_RouteEntry(newRoute, pageBased: false, initialState: _RouteLifecycle.replace), oldRoute);
}
/// Replaces a route on the navigator with a new route.
///
/// {@macro flutter.widgets.navigator.restorableReplace}
///
/// {@macro flutter.widgets.navigator.replace}
///
/// {@macro flutter.widgets.Navigator.restorablePush}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
@optionalTypeArgs
String restorableReplace<T extends Object?>({ required Route<dynamic> oldRoute, required RestorableRouteBuilder<T> newRouteBuilder, Object? arguments }) {
assert(oldRoute._navigator == this);
assert(_debugIsStaticCallback(newRouteBuilder), 'The provided routeBuilder must be a static function.');
assert(debugIsSerializableForRestoration(arguments), 'The arguments object must be serializable via the StandardMessageCodec.');
final _RouteEntry entry = _RestorationInformation.anonymous(
routeBuilder: newRouteBuilder,
arguments: arguments,
restorationScopeId: _nextPagelessRestorationScopeId,
).toRouteEntry(this, initialState: _RouteLifecycle.replace);
_replaceEntry(entry, oldRoute);
return entry.restorationId!;
}
void _replaceEntry(_RouteEntry entry, Route<dynamic> oldRoute) {
assert(!_debugLocked);
if (oldRoute == entry.route) {
return;
}
assert(() {
_debugLocked = true;
return true;
}());
assert(entry.currentState == _RouteLifecycle.replace);
assert(entry.route._navigator == null);
final int index = _history.indexWhere(_RouteEntry.isRoutePredicate(oldRoute));
assert(index >= 0, 'This Navigator does not contain the specified oldRoute.');
assert(_history[index].isPresent, 'The specified oldRoute has already been removed from the Navigator.');
final bool wasCurrent = oldRoute.isCurrent;
_history.insert(index + 1, entry);
_history[index].remove(isReplaced: true);
_flushHistoryUpdates();
assert(() {
_debugLocked = false;
return true;
}());
if (wasCurrent) {
_afterNavigation(entry.route);
}
}
/// Replaces a route on the navigator with a new route. The route to be
/// replaced is the one below the given `anchorRoute`.
///
/// {@macro flutter.widgets.navigator.replaceRouteBelow}
///
/// See also:
///
/// * [replace], which is the same but identifies the route to be removed
/// directly.
/// * [restorableReplaceRouteBelow], which adds a replacement route that can
/// be restored during state restoration.
@optionalTypeArgs
void replaceRouteBelow<T extends Object?>({ required Route<dynamic> anchorRoute, required Route<T> newRoute }) {
assert(newRoute._navigator == null);
assert(anchorRoute._navigator == this);
_replaceEntryBelow(_RouteEntry(newRoute, pageBased: false, initialState: _RouteLifecycle.replace), anchorRoute);
}
/// Replaces a route on the navigator with a new route. The route to be
/// replaced is the one below the given `anchorRoute`.
///
/// {@macro flutter.widgets.navigator.restorableReplaceRouteBelow}
///
/// {@macro flutter.widgets.navigator.replaceRouteBelow}
///
/// {@macro flutter.widgets.Navigator.restorablePush}
///
/// {@macro flutter.widgets.Navigator.restorablePushNamed.returnValue}
@optionalTypeArgs
String restorableReplaceRouteBelow<T extends Object?>({ required Route<dynamic> anchorRoute, required RestorableRouteBuilder<T> newRouteBuilder, Object? arguments }) {
assert(anchorRoute._navigator == this);
assert(_debugIsStaticCallback(newRouteBuilder), 'The provided routeBuilder must be a static function.');
assert(debugIsSerializableForRestoration(arguments), 'The arguments object must be serializable via the StandardMessageCodec.');
final _RouteEntry entry = _RestorationInformation.anonymous(
routeBuilder: newRouteBuilder,
arguments: arguments,
restorationScopeId: _nextPagelessRestorationScopeId,
).toRouteEntry(this, initialState: _RouteLifecycle.replace);
_replaceEntryBelow(entry, anchorRoute);
return entry.restorationId!;
}
void _replaceEntryBelow(_RouteEntry entry, Route<dynamic> anchorRoute) {
assert(!_debugLocked);
assert(() { _debugLocked = true; return true; }());
final int anchorIndex = _history.indexWhere(_RouteEntry.isRoutePredicate(anchorRoute));
assert(anchorIndex >= 0, 'This Navigator does not contain the specified anchorRoute.');
assert(_history[anchorIndex].isPresent, 'The specified anchorRoute has already been removed from the Navigator.');
int index = anchorIndex - 1;
while (index >= 0) {
if (_history[index].isPresent) {
break;
}
index -= 1;
}
assert(index >= 0, 'There are no routes below the specified anchorRoute.');
_history.insert(index + 1, entry);
_history[index].remove(isReplaced: true);
_flushHistoryUpdates();
assert(() { _debugLocked = false; return true; }());
}
/// Whether the navigator can be popped.
///
/// {@macro flutter.widgets.navigator.canPop}
///
/// See also:
///
/// * [Route.isFirst], which returns true for routes for which [canPop]
/// returns false.
bool canPop() {
final Iterator<_RouteEntry> iterator = _history.where(_RouteEntry.isPresentPredicate).iterator;
if (!iterator.moveNext()) {
// We have no active routes, so we can't pop.
return false;
}
if (iterator.current.route.willHandlePopInternally) {
// The first route can handle pops itself, so we can pop.
return true;
}
if (!iterator.moveNext()) {
// There's only one route, so we can't pop.
return false;
}
return true; // there's at least two routes, so we can pop
}
/// Consults the current route's [Route.popDisposition] method, and acts
/// accordingly, potentially popping the route as a result; returns whether
/// the pop request should be considered handled.
///
/// {@macro flutter.widgets.navigator.maybePop}
///
/// See also:
///
/// * [Form], which provides a [Form.canPop] boolean that enables the
/// form to prevent any [pop]s initiated by the app's back button.
/// * [ModalRoute], which provides a `scopedOnPopCallback` that can be used
/// to define the route's `willPop` method.
@optionalTypeArgs
Future<bool> maybePop<T extends Object?>([ T? result ]) async {
final _RouteEntry? lastEntry = _lastRouteEntryWhereOrNull(_RouteEntry.isPresentPredicate);
if (lastEntry == null) {
return false;
}
assert(lastEntry.route._navigator == this);
// TODO(justinmc): When the deprecated willPop method is removed, delete
// this code and use only popDisposition, below.
final RoutePopDisposition willPopDisposition = await lastEntry.route.willPop();
if (!mounted) {
// Forget about this pop, we were disposed in the meantime.
return true;
}
if (willPopDisposition == RoutePopDisposition.doNotPop) {
return true;
}
final _RouteEntry? newLastEntry = _lastRouteEntryWhereOrNull(_RouteEntry.isPresentPredicate);
if (lastEntry != newLastEntry) {
// Forget about this pop, something happened to our history in the meantime.
return true;
}
switch (lastEntry.route.popDisposition) {
case RoutePopDisposition.bubble:
return false;
case RoutePopDisposition.pop:
pop(result);
return true;
case RoutePopDisposition.doNotPop:
lastEntry.route.onPopInvoked(false);
return true;
}
}
/// Pop the top-most route off the navigator.
///
/// {@macro flutter.widgets.navigator.pop}
///
/// {@tool snippet}
///
/// Typical usage for closing a route is as follows:
///
/// ```dart
/// void _handleClose() {
/// navigator.pop();
/// }
/// ```
/// {@end-tool}
/// {@tool snippet}
///
/// A dialog box might be closed with a result:
///
/// ```dart
/// void _handleAccept() {
/// navigator.pop(true); // dialog returns true
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
void pop<T extends Object?>([ T? result ]) {
assert(!_debugLocked);
assert(() {
_debugLocked = true;
return true;
}());
final _RouteEntry entry = _history.lastWhere(_RouteEntry.isPresentPredicate);
if (entry.pageBased) {
if (widget.onPopPage!(entry.route, result) && entry.currentState == _RouteLifecycle.idle) {
// The entry may have been disposed if the pop finishes synchronously.
assert(entry.route._popCompleter.isCompleted);
entry.currentState = _RouteLifecycle.pop;
}
entry.route.onPopInvoked(true);
} else {
entry.pop<T>(result);
assert (entry.currentState == _RouteLifecycle.pop);
}
if (entry.currentState == _RouteLifecycle.pop) {
_flushHistoryUpdates(rearrangeOverlay: false);
}
assert(entry.currentState == _RouteLifecycle.idle || entry.route._popCompleter.isCompleted);
assert(() {
_debugLocked = false;
return true;
}());
_afterNavigation(entry.route);
}
/// Calls [pop] repeatedly until the predicate returns true.
///
/// {@macro flutter.widgets.navigator.popUntil}
///
/// {@tool snippet}
///
/// Typical usage is as follows:
///
/// ```dart
/// void _doLogout() {
/// navigator.popUntil(ModalRoute.withName('/login'));
/// }
/// ```
/// {@end-tool}
void popUntil(RoutePredicate predicate) {
_RouteEntry? candidate = _lastRouteEntryWhereOrNull(_RouteEntry.isPresentPredicate);
while (candidate != null) {
if (predicate(candidate.route)) {
return;
}
pop();
candidate = _lastRouteEntryWhereOrNull(_RouteEntry.isPresentPredicate);
}
}
/// Immediately remove `route` from the navigator, and [Route.dispose] it.
///
/// {@macro flutter.widgets.navigator.removeRoute}
void removeRoute(Route<dynamic> route) {
assert(!_debugLocked);
assert(() {
_debugLocked = true;
return true;
}());
assert(route._navigator == this);
final bool wasCurrent = route.isCurrent;
final _RouteEntry entry = _history.firstWhere(_RouteEntry.isRoutePredicate(route));
entry.remove();
_flushHistoryUpdates(rearrangeOverlay: false);
assert(() {
_debugLocked = false;
return true;
}());
if (wasCurrent) {
_afterNavigation(
_lastRouteEntryWhereOrNull(_RouteEntry.isPresentPredicate)?.route,
);
}
}
/// Immediately remove a route from the navigator, and [Route.dispose] it. The
/// route to be removed is the one below the given `anchorRoute`.
///
/// {@macro flutter.widgets.navigator.removeRouteBelow}
void removeRouteBelow(Route<dynamic> anchorRoute) {
assert(!_debugLocked);
assert(() {
_debugLocked = true;
return true;
}());
assert(anchorRoute._navigator == this);
final int anchorIndex = _history.indexWhere(_RouteEntry.isRoutePredicate(anchorRoute));
assert(anchorIndex >= 0, 'This Navigator does not contain the specified anchorRoute.');
assert(_history[anchorIndex].isPresent, 'The specified anchorRoute has already been removed from the Navigator.');
int index = anchorIndex - 1;
while (index >= 0) {
if (_history[index].isPresent) {
break;
}
index -= 1;
}
assert(index >= 0, 'There are no routes below the specified anchorRoute.');
_history[index].remove();
_flushHistoryUpdates(rearrangeOverlay: false);
assert(() {
_debugLocked = false;
return true;
}());
}
/// Complete the lifecycle for a route that has been popped off the navigator.
///
/// When the navigator pops a route, the navigator retains a reference to the
/// route in order to call [Route.dispose] if the navigator itself is removed
/// from the tree. When the route is finished with any exit animation, the
/// route should call this function to complete its lifecycle (e.g., to
/// receive a call to [Route.dispose]).
///
/// The given `route` must have already received a call to [Route.didPop].
/// This function may be called directly from [Route.didPop] if [Route.didPop]
/// will return true.
void finalizeRoute(Route<dynamic> route) {
// FinalizeRoute may have been called while we were already locked as a
// responds to route.didPop(). Make sure to leave in the state we were in
// before the call.
bool? wasDebugLocked;
assert(() { wasDebugLocked = _debugLocked; _debugLocked = true; return true; }());
assert(_history.where(_RouteEntry.isRoutePredicate(route)).length == 1);
final int index = _history.indexWhere(_RouteEntry.isRoutePredicate(route));
final _RouteEntry entry = _history[index];
// For page-based route with zero transition, the finalizeRoute can be
// called on any life cycle above pop.
if (entry.pageBased && entry.currentState.index < _RouteLifecycle.pop.index) {
_observedRouteDeletions.add(_NavigatorPopObservation(route, _getRouteBefore(index - 1, _RouteEntry.willBePresentPredicate)?.route));
} else {
assert(entry.currentState == _RouteLifecycle.popping);
}
entry.finalize();
// finalizeRoute can be called during _flushHistoryUpdates if a pop
// finishes synchronously.
if (!_flushingHistory) {
_flushHistoryUpdates(rearrangeOverlay: false);
}
assert(() { _debugLocked = wasDebugLocked!; return true; }());
}
@optionalTypeArgs
Route<T>? _getRouteById<T>(String id) {
return _firstRouteEntryWhereOrNull((_RouteEntry entry) => entry.restorationId == id)?.route as Route<T>?;
}
int get _userGesturesInProgress => _userGesturesInProgressCount;
int _userGesturesInProgressCount = 0;
set _userGesturesInProgress(int value) {
_userGesturesInProgressCount = value;
userGestureInProgressNotifier.value = _userGesturesInProgress > 0;
}
/// Whether a route is currently being manipulated by the user, e.g.
/// as during an iOS back gesture.
///
/// See also:
///
/// * [userGestureInProgressNotifier], which notifies its listeners if
/// the value of [userGestureInProgress] changes.
bool get userGestureInProgress => userGestureInProgressNotifier.value;
/// Notifies its listeners if the value of [userGestureInProgress] changes.
final ValueNotifier<bool> userGestureInProgressNotifier = ValueNotifier<bool>(false);
/// The navigator is being controlled by a user gesture.
///
/// For example, called when the user beings an iOS back gesture.
///
/// When the gesture finishes, call [didStopUserGesture].
void didStartUserGesture() {
_userGesturesInProgress += 1;
if (_userGesturesInProgress == 1) {
final int routeIndex = _getIndexBefore(
_history.length - 1,
_RouteEntry.willBePresentPredicate,
);
final Route<dynamic> route = _history[routeIndex].route;
Route<dynamic>? previousRoute;
if (!route.willHandlePopInternally && routeIndex > 0) {
previousRoute = _getRouteBefore(
routeIndex - 1,
_RouteEntry.willBePresentPredicate,
)!.route;
}
for (final NavigatorObserver observer in _effectiveObservers) {
observer.didStartUserGesture(route, previousRoute);
}
}
}
/// A user gesture completed.
///
/// Notifies the navigator that a gesture regarding which the navigator was
/// previously notified with [didStartUserGesture] has completed.
void didStopUserGesture() {
assert(_userGesturesInProgress > 0);
_userGesturesInProgress -= 1;
if (_userGesturesInProgress == 0) {
for (final NavigatorObserver observer in _effectiveObservers) {
observer.didStopUserGesture();
}
}
}
final Set<int> _activePointers = <int>{};
void _handlePointerDown(PointerDownEvent event) {
_activePointers.add(event.pointer);
}
void _handlePointerUpOrCancel(PointerEvent event) {
_activePointers.remove(event.pointer);
}
void _cancelActivePointers() {
// TODO(abarth): This mechanism is far from perfect. See https://github.com/flutter/flutter/issues/4770
if (SchedulerBinding.instance.schedulerPhase == SchedulerPhase.idle) {
// If we're between frames (SchedulerPhase.idle) then absorb any
// subsequent pointers from this frame. The absorbing flag will be
// reset in the next frame, see build().
final RenderAbsorbPointer? absorber = _overlayKey.currentContext?.findAncestorRenderObjectOfType<RenderAbsorbPointer>();
setState(() {
absorber?.absorbing = true;
// We do this in setState so that we'll reset the absorbing value back
// to false on the next frame.
});
}
_activePointers.toList().forEach(WidgetsBinding.instance.cancelPointer);
}
/// Gets first route entry satisfying the predicate, or null if not found.
_RouteEntry? _firstRouteEntryWhereOrNull(_RouteEntryPredicate test) {
for (final _RouteEntry element in _history) {
if (test(element)) {
return element;
}
}
return null;
}
/// Gets last route entry satisfying the predicate, or null if not found.
_RouteEntry? _lastRouteEntryWhereOrNull(_RouteEntryPredicate test) {
_RouteEntry? result;
for (final _RouteEntry element in _history) {
if (test(element)) {
result = element;
}
}
return result;
}
@override
Widget build(BuildContext context) {
assert(!_debugLocked);
assert(_history.isNotEmpty);
// Hides the HeroControllerScope for the widget subtree so that the other
// nested navigator underneath will not pick up the hero controller above
// this level.
return HeroControllerScope.none(
child: NotificationListener<NavigationNotification>(
onNotification: (NavigationNotification notification) {
// If the state of this Navigator does not change whether or not the
// whole framework can pop, propagate the Notification as-is.
if (notification.canHandlePop || !canPop()) {
return false;
}
// Otherwise, dispatch a new Notification with the correct canPop and
// stop the propagation of the old Notification.
const NavigationNotification nextNotification = NavigationNotification(
canHandlePop: true,
);
nextNotification.dispatch(context);
return true;
},
child: Listener(
onPointerDown: _handlePointerDown,
onPointerUp: _handlePointerUpOrCancel,
onPointerCancel: _handlePointerUpOrCancel,
child: AbsorbPointer(
absorbing: false, // it's mutated directly by _cancelActivePointers above
child: FocusTraversalGroup(
policy: FocusTraversalGroup.maybeOf(context),
child: Focus(
focusNode: focusNode,
autofocus: true,
skipTraversal: true,
includeSemantics: false,
child: UnmanagedRestorationScope(
bucket: bucket,
child: Overlay(
key: _overlayKey,
clipBehavior: widget.clipBehavior,
initialEntries: overlay == null ? _allRouteOverlayEntries.toList(growable: false) : const <OverlayEntry>[],
),
),
),
),
),
),
),
);
}
}
enum _RouteRestorationType {
named,
anonymous,
}
abstract class _RestorationInformation {
_RestorationInformation(this.type);
factory _RestorationInformation.named({
required String name,
required Object? arguments,
required int restorationScopeId,
}) = _NamedRestorationInformation;
factory _RestorationInformation.anonymous({
required RestorableRouteBuilder<Object?> routeBuilder,
required Object? arguments,
required int restorationScopeId,
}) = _AnonymousRestorationInformation;
factory _RestorationInformation.fromSerializableData(Object data) {
final List<Object?> casted = data as List<Object?>;
assert(casted.isNotEmpty);
final _RouteRestorationType type = _RouteRestorationType.values[casted[0]! as int];
switch (type) {
case _RouteRestorationType.named:
return _NamedRestorationInformation.fromSerializableData(casted.sublist(1));
case _RouteRestorationType.anonymous:
return _AnonymousRestorationInformation.fromSerializableData(casted.sublist(1));
}
}
final _RouteRestorationType type;
int get restorationScopeId;
Object? _serializableData;
bool get isRestorable => true;
Object getSerializableData() {
_serializableData ??= computeSerializableData();
return _serializableData!;
}
@mustCallSuper
List<Object> computeSerializableData() {
return <Object>[type.index];
}
@protected
Route<dynamic> createRoute(NavigatorState navigator);
_RouteEntry toRouteEntry(NavigatorState navigator, {_RouteLifecycle initialState = _RouteLifecycle.add}) {
final Route<Object?> route = createRoute(navigator);
return _RouteEntry(
route,
pageBased: false,
initialState: initialState,
restorationInformation: this,
);
}
}
class _NamedRestorationInformation extends _RestorationInformation {
_NamedRestorationInformation({
required this.name,
required this.arguments,
required this.restorationScopeId,
}) : super(_RouteRestorationType.named);
_NamedRestorationInformation.fromSerializableData(List<Object?> data)
: assert(data.length > 1),
restorationScopeId = data[0]! as int,
name = data[1]! as String,
arguments = data.elementAtOrNull(2),
super(_RouteRestorationType.named);
@override
List<Object> computeSerializableData() {
return super.computeSerializableData()..addAll(<Object>[
restorationScopeId,
name,
if (arguments != null)
arguments!,
]);
}
@override
final int restorationScopeId;
final String name;
final Object? arguments;
@override
Route<dynamic> createRoute(NavigatorState navigator) {
final Route<dynamic> route = navigator._routeNamed<dynamic>(name, arguments: arguments)!;
return route;
}
}
class _AnonymousRestorationInformation extends _RestorationInformation {
_AnonymousRestorationInformation({
required this.routeBuilder,
required this.arguments,
required this.restorationScopeId,
}) : super(_RouteRestorationType.anonymous);
_AnonymousRestorationInformation.fromSerializableData(List<Object?> data)
: assert(data.length > 1),
restorationScopeId = data[0]! as int,
routeBuilder = ui.PluginUtilities.getCallbackFromHandle(ui.CallbackHandle.fromRawHandle(data[1]! as int))! as RestorableRouteBuilder,
arguments = data.elementAtOrNull(2),
super(_RouteRestorationType.anonymous);
@override
// TODO(goderbauer): remove the kIsWeb check when https://github.com/flutter/flutter/issues/33615 is resolved.
bool get isRestorable => !kIsWeb;
@override
List<Object> computeSerializableData() {
assert(isRestorable);
final ui.CallbackHandle? handle = ui.PluginUtilities.getCallbackHandle(routeBuilder);
assert(handle != null);
return super.computeSerializableData()..addAll(<Object>[
restorationScopeId,
handle!.toRawHandle(),
if (arguments != null)
arguments!,
]);
}
@override
final int restorationScopeId;
final RestorableRouteBuilder<Object?> routeBuilder;
final Object? arguments;
@override
Route<dynamic> createRoute(NavigatorState navigator) {
final Route<dynamic> result = routeBuilder(navigator.context, arguments);
return result;
}
}
class _HistoryProperty extends RestorableProperty<Map<String?, List<Object>>?> {
// Routes not associated with a page are stored under key 'null'.
Map<String?, List<Object>>? _pageToPagelessRoutes;
// Updating.
void update(_History history) {
assert(isRegistered);
final bool wasUninitialized = _pageToPagelessRoutes == null;
bool needsSerialization = wasUninitialized;
_pageToPagelessRoutes ??= <String, List<Object>>{};
_RouteEntry? currentPage;
List<Object> newRoutesForCurrentPage = <Object>[];
List<Object> oldRoutesForCurrentPage = _pageToPagelessRoutes![null] ?? const <Object>[];
bool restorationEnabled = true;
final Map<String?, List<Object>> newMap = <String?, List<Object>>{};
final Set<String?> removedPages = _pageToPagelessRoutes!.keys.toSet();
for (final _RouteEntry entry in history) {
if (!entry.isPresentForRestoration) {
entry.restorationEnabled = false;
continue;
}
assert(entry.isPresentForRestoration);
if (entry.pageBased) {
needsSerialization = needsSerialization || newRoutesForCurrentPage.length != oldRoutesForCurrentPage.length;
_finalizeEntry(newRoutesForCurrentPage, currentPage, newMap, removedPages);
currentPage = entry;
restorationEnabled = entry.restorationId != null;
entry.restorationEnabled = restorationEnabled;
if (restorationEnabled) {
assert(entry.restorationId != null);
newRoutesForCurrentPage = <Object>[];
oldRoutesForCurrentPage = _pageToPagelessRoutes![entry.restorationId] ?? const <Object>[];
} else {
newRoutesForCurrentPage = const <Object>[];
oldRoutesForCurrentPage = const <Object>[];
}
continue;
}
assert(!entry.pageBased);
restorationEnabled = restorationEnabled && (entry.restorationInformation?.isRestorable ?? false);
entry.restorationEnabled = restorationEnabled;
if (restorationEnabled) {
assert(entry.restorationId != null);
assert(currentPage == null || currentPage.restorationId != null);
assert(entry.restorationInformation != null);
final Object serializedData = entry.restorationInformation!.getSerializableData();
needsSerialization = needsSerialization
|| oldRoutesForCurrentPage.length <= newRoutesForCurrentPage.length
|| oldRoutesForCurrentPage[newRoutesForCurrentPage.length] != serializedData;
newRoutesForCurrentPage.add(serializedData);
}
}
needsSerialization = needsSerialization || newRoutesForCurrentPage.length != oldRoutesForCurrentPage.length;
_finalizeEntry(newRoutesForCurrentPage, currentPage, newMap, removedPages);
needsSerialization = needsSerialization || removedPages.isNotEmpty;
assert(wasUninitialized || _debugMapsEqual(_pageToPagelessRoutes!, newMap) != needsSerialization);
if (needsSerialization) {
_pageToPagelessRoutes = newMap;
notifyListeners();
}
}
void _finalizeEntry(
List<Object> routes,
_RouteEntry? page,
Map<String?, List<Object>> pageToRoutes,
Set<String?> pagesToRemove,
) {
assert(page == null || page.pageBased);
assert(!pageToRoutes.containsKey(page?.restorationId));
if (routes.isNotEmpty) {
assert(page == null || page.restorationId != null);
final String? restorationId = page?.restorationId;
pageToRoutes[restorationId] = routes;
pagesToRemove.remove(restorationId);
}
}
bool _debugMapsEqual(Map<String?, List<Object>> a, Map<String?, List<Object>> b) {
if (!setEquals(a.keys.toSet(), b.keys.toSet())) {
return false;
}
for (final String? key in a.keys) {
if (!listEquals(a[key], b[key])) {
return false;
}
}
return true;
}
void clear() {
assert(isRegistered);
if (_pageToPagelessRoutes == null) {
return;
}
_pageToPagelessRoutes = null;
notifyListeners();
}
// Restoration.
bool get hasData => _pageToPagelessRoutes != null;
List<_RouteEntry> restoreEntriesForPage(_RouteEntry? page, NavigatorState navigator) {
assert(isRegistered);
assert(page == null || page.pageBased);
final List<_RouteEntry> result = <_RouteEntry>[];
if (_pageToPagelessRoutes == null || (page != null && page.restorationId == null)) {
return result;
}
final List<Object>? serializedData = _pageToPagelessRoutes![page?.restorationId];
if (serializedData == null) {
return result;
}
for (final Object data in serializedData) {
result.add(_RestorationInformation.fromSerializableData(data).toRouteEntry(navigator));
}
return result;
}
// RestorableProperty overrides.
@override
Map<String?, List<Object>>? createDefaultValue() {
return null;
}
@override
Map<String?, List<Object>>? fromPrimitives(Object? data) {
final Map<dynamic, dynamic> casted = data! as Map<dynamic, dynamic>;
return casted.map<String?, List<Object>>((dynamic key, dynamic value) => MapEntry<String?, List<Object>>(
key as String?,
List<Object>.from(value as List<dynamic>),
));
}
@override
void initWithValue(Map<String?, List<Object>>? value) {
_pageToPagelessRoutes = value;
}
@override
Object? toPrimitives() {
return _pageToPagelessRoutes;
}
@override
bool get enabled => hasData;
}
/// A callback that given a [BuildContext] finds a [NavigatorState].
///
/// Used by [RestorableRouteFuture.navigatorFinder] to determine the navigator
/// to which a new route should be added.
typedef NavigatorFinderCallback = NavigatorState Function(BuildContext context);
/// A callback that given some `arguments` and a `navigator` adds a new
/// restorable route to that `navigator` and returns the opaque ID of that
/// new route.
///
/// Usually, this callback calls one of the imperative methods on the Navigator
/// that have "restorable" in the name and returns their return value.
///
/// Used by [RestorableRouteFuture.onPresent].
typedef RoutePresentationCallback = String Function(NavigatorState navigator, Object? arguments);
/// A callback to handle the result of a completed [Route].
///
/// The return value of the route (which can be null for e.g. void routes) is
/// passed to the callback.
///
/// Used by [RestorableRouteFuture.onComplete].
typedef RouteCompletionCallback<T> = void Function(T result);
/// Gives access to a [Route] object and its return value that was added to a
/// navigator via one of its "restorable" API methods.
///
/// When a [State] object wants access to the return value of a [Route] object
/// it has pushed onto the [Navigator], a [RestorableRouteFuture] ensures that
/// it will also have access to that value after state restoration.
///
/// To show a new route on the navigator defined by the [navigatorFinder], call
/// [present], which will invoke the [onPresent] callback. The [onPresent]
/// callback must add a new route to the navigator provided to it using one
/// of the "restorable" API methods. When the newly added route completes, the
/// [onComplete] callback executes. It is given the return value of the route,
/// which may be null.
///
/// While the route added via [present] is shown on the navigator, it can be
/// accessed via the [route] getter.
///
/// If the property is restored to a state in which [present] had been called on
/// it, but the route has not completed yet, the [RestorableRouteFuture] will
/// obtain the restored route object from the navigator again and call
/// [onComplete] once it completes.
///
/// The [RestorableRouteFuture] can only keep track of one active [route].
/// When [present] has been called to add a route, it may only be called again
/// after the previously added route has completed.
///
/// {@tool dartpad}
/// This example uses a [RestorableRouteFuture] in the `_MyHomeState` to push a
/// new `MyCounter` route and to retrieve its return value.
///
/// ** See code in examples/api/lib/widgets/navigator/restorable_route_future.0.dart **
/// {@end-tool}
class RestorableRouteFuture<T> extends RestorableProperty<String?> {
/// Creates a [RestorableRouteFuture].
RestorableRouteFuture({
this.navigatorFinder = _defaultNavigatorFinder,
required this.onPresent,
this.onComplete,
});
/// A callback that given the [BuildContext] of the [State] object to which
/// this property is registered returns the [NavigatorState] of the navigator
/// to which the route instantiated in [onPresent] is added.
final NavigatorFinderCallback navigatorFinder;
/// A callback that add a new [Route] to the provided navigator.
///
/// The callback must use one of the API methods on the [NavigatorState] that
/// have "restorable" in their name (e.g. [NavigatorState.restorablePush],
/// [NavigatorState.restorablePushNamed], etc.) and return the opaque ID
/// returned by those methods.
///
/// This callback is invoked when [present] is called with the `arguments`
/// Object that was passed to that method and the [NavigatorState] obtained
/// from [navigatorFinder].
final RoutePresentationCallback onPresent;
/// A callback that is invoked when the [Route] added via [onPresent]
/// completes.
///
/// The return value of that route is passed to this method.
final RouteCompletionCallback<T>? onComplete;
/// Shows the route created by [onPresent] and invoke [onComplete] when it
/// completes.
///
/// The `arguments` object is passed to [onPresent] and can be used to
/// customize the route. It must be serializable via the
/// [StandardMessageCodec]. Often, a [Map] is used to pass key-value pairs.
void present([Object? arguments]) {
assert(!isPresent);
assert(isRegistered);
final String routeId = onPresent(_navigator, arguments);
_hookOntoRouteFuture(routeId);
notifyListeners();
}
/// Whether the [Route] created by [present] is currently shown.
///
/// Returns true after [present] has been called until the [Route] completes.
bool get isPresent => route != null;
/// The route that [present] added to the Navigator.
///
/// Returns null when currently no route is shown
Route<T>? get route => _route;
Route<T>? _route;
@override
String? createDefaultValue() => null;
@override
void initWithValue(String? value) {
if (value != null) {
_hookOntoRouteFuture(value);
}
}
@override
Object? toPrimitives() {
assert(route != null);
assert(enabled);
return route?.restorationScopeId.value;
}
@override
String fromPrimitives(Object? data) {
assert(data != null);
return data! as String;
}
bool _disposed = false;
@override
void dispose() {
super.dispose();
_route?.restorationScopeId.removeListener(notifyListeners);
_disposed = true;
}
@override
bool get enabled => route?.restorationScopeId.value != null;
NavigatorState get _navigator {
final NavigatorState navigator = navigatorFinder(state.context);
return navigator;
}
void _hookOntoRouteFuture(String id) {
_route = _navigator._getRouteById<T>(id);
assert(_route != null);
route!.restorationScopeId.addListener(notifyListeners);
route!.popped.then((dynamic result) {
if (_disposed) {
return;
}
_route?.restorationScopeId.removeListener(notifyListeners);
_route = null;
notifyListeners();
onComplete?.call(result as T);
});
}
static NavigatorState _defaultNavigatorFinder(BuildContext context) => Navigator.of(context);
}
/// A notification that a change in navigation has taken place.
///
/// Specifically, this notification indicates that at least one of the following
/// has occurred:
///
/// * That route stack of a [Navigator] has changed in any way.
/// * The ability to pop has changed, such as controlled by [PopScope].
class NavigationNotification extends Notification {
/// Creates a notification that some change in navigation has happened.
const NavigationNotification({
required this.canHandlePop,
});
/// Indicates that the originator of this [Notification] is capable of
/// handling a navigation pop.
final bool canHandlePop;
@override
String toString() {
return 'NavigationNotification canHandlePop: $canHandlePop';
}
}
| flutter/packages/flutter/lib/src/widgets/navigator.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/navigator.dart",
"repo_id": "flutter",
"token_count": 76949
} | 821 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'framework.dart';
import 'navigator.dart';
import 'routes.dart';
/// Manages back navigation gestures.
///
/// The [canPop] parameter disables back gestures when set to `false`.
///
/// The [onPopInvoked] parameter reports when pop navigation was attempted, and
/// `didPop` indicates whether or not the navigation was successful.
///
/// Android has a system back gesture that is a swipe inward from near the edge
/// of the screen. It is recognized by Android before being passed to Flutter.
/// iOS has a similar gesture that is recognized in Flutter by
/// [CupertinoRouteTransitionMixin], not by iOS, and is therefore not a system
/// back gesture.
///
/// If [canPop] is false, then a system back gesture will not pop the route off
/// of the enclosing [Navigator]. [onPopInvoked] will still be called, and
/// `didPop` will be `false`. On iOS when using [CupertinoRouteTransitionMixin]
/// with [canPop] set to false, no gesture will be detected at all, so
/// [onPopInvoked] will not be called. Programmatically attempting pop
/// navigation will also result in a call to [onPopInvoked], with `didPop`
/// indicating success or failure.
///
/// If [canPop] is true, then a system back gesture will cause the enclosing
/// [Navigator] to receive a pop as usual. [onPopInvoked] will be called with
/// `didPop` as true, unless the pop failed for reasons unrelated to
/// [PopScope], in which case it will be false.
///
/// {@tool dartpad}
/// This sample demonstrates showing a confirmation dialog before navigating
/// away from a page.
///
/// ** See code in examples/api/lib/widgets/pop_scope/pop_scope.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [NavigatorPopHandler], which is a less verbose way to handle system back
/// gestures in simple cases of nested [Navigator]s.
/// * [Form.canPop] and [Form.onPopInvoked], which can be used to handle system
/// back gestures in the case of a form with unsaved data.
/// * [ModalRoute.registerPopEntry] and [ModalRoute.unregisterPopEntry],
/// which this widget uses to integrate with Flutter's navigation system.
class PopScope extends StatefulWidget {
/// Creates a widget that registers a callback to veto attempts by the user to
/// dismiss the enclosing [ModalRoute].
const PopScope({
super.key,
required this.child,
this.canPop = true,
this.onPopInvoked,
});
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
/// {@template flutter.widgets.PopScope.onPopInvoked}
/// Called after a route pop was handled.
/// {@endtemplate}
///
/// It's not possible to prevent the pop from happening at the time that this
/// method is called; the pop has already happened. Use [canPop] to
/// disable pops in advance.
///
/// This will still be called even when the pop is canceled. A pop is canceled
/// when the relevant [Route.popDisposition] returns false, such as when
/// [canPop] is set to false on a [PopScope]. The `didPop` parameter
/// indicates whether or not the back navigation actually happened
/// successfully.
///
/// See also:
///
/// * [Route.onPopInvoked], which is similar.
final PopInvokedCallback? onPopInvoked;
/// {@template flutter.widgets.PopScope.canPop}
/// When false, blocks the current route from being popped.
///
/// This includes the root route, where upon popping, the Flutter app would
/// exit.
///
/// If multiple [PopScope] widgets appear in a route's widget subtree, then
/// each and every `canPop` must be `true` in order for the route to be
/// able to pop.
///
/// [Android's predictive back](https://developer.android.com/guide/navigation/predictive-back-gesture)
/// feature will not animate when this boolean is false.
/// {@endtemplate}
final bool canPop;
@override
State<PopScope> createState() => _PopScopeState();
}
class _PopScopeState extends State<PopScope> implements PopEntry {
ModalRoute<dynamic>? _route;
@override
PopInvokedCallback? get onPopInvoked => widget.onPopInvoked;
@override
late final ValueNotifier<bool> canPopNotifier;
@override
void initState() {
super.initState();
canPopNotifier = ValueNotifier<bool>(widget.canPop);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final ModalRoute<dynamic>? nextRoute = ModalRoute.of(context);
if (nextRoute != _route) {
_route?.unregisterPopEntry(this);
_route = nextRoute;
_route?.registerPopEntry(this);
}
}
@override
void didUpdateWidget(PopScope oldWidget) {
super.didUpdateWidget(oldWidget);
canPopNotifier.value = widget.canPop;
}
@override
void dispose() {
_route?.unregisterPopEntry(this);
canPopNotifier.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => widget.child;
}
| flutter/packages/flutter/lib/src/widgets/pop_scope.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/pop_scope.dart",
"repo_id": "flutter",
"token_count": 1526
} | 822 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
/// A description of a [Scrollable]'s contents, useful for modeling the state
/// of its viewport.
///
/// This class defines a current position, [pixels], and a range of values
/// considered "in bounds" for that position. The range has a minimum value at
/// [minScrollExtent] and a maximum value at [maxScrollExtent] (inclusive). The
/// viewport scrolls in the direction and axis described by [axisDirection]
/// and [axis].
///
/// The [outOfRange] getter will return true if [pixels] is outside this defined
/// range. The [atEdge] getter will return true if the [pixels] position equals
/// either the [minScrollExtent] or the [maxScrollExtent].
///
/// The dimensions of the viewport in the given [axis] are described by
/// [viewportDimension].
///
/// The above values are also exposed in terms of [extentBefore],
/// [extentInside], and [extentAfter], which may be more useful for use cases
/// such as scroll bars; for example, see [Scrollbar].
///
/// {@tool dartpad}
/// This sample shows how a [ScrollMetricsNotification] is dispatched when
/// the [ScrollMetrics] changed as a result of resizing the [Viewport].
/// Press the floating action button to increase the scrollable window's size.
///
/// ** See code in examples/api/lib/widgets/scroll_position/scroll_metrics_notification.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [FixedScrollMetrics], which is an immutable object that implements this
/// interface.
mixin ScrollMetrics {
/// Creates a [ScrollMetrics] that has the same properties as this object.
///
/// This is useful if this object is mutable, but you want to get a snapshot
/// of the current state.
///
/// The named arguments allow the values to be adjusted in the process. This
/// is useful to examine hypothetical situations, for example "would applying
/// this delta unmodified take the position [outOfRange]?".
ScrollMetrics copyWith({
double? minScrollExtent,
double? maxScrollExtent,
double? pixels,
double? viewportDimension,
AxisDirection? axisDirection,
double? devicePixelRatio,
}) {
return FixedScrollMetrics(
minScrollExtent: minScrollExtent ?? (hasContentDimensions ? this.minScrollExtent : null),
maxScrollExtent: maxScrollExtent ?? (hasContentDimensions ? this.maxScrollExtent : null),
pixels: pixels ?? (hasPixels ? this.pixels : null),
viewportDimension: viewportDimension ?? (hasViewportDimension ? this.viewportDimension : null),
axisDirection: axisDirection ?? this.axisDirection,
devicePixelRatio: devicePixelRatio ?? this.devicePixelRatio,
);
}
/// The minimum in-range value for [pixels].
///
/// The actual [pixels] value might be [outOfRange].
///
/// This value is typically less than or equal to
/// [maxScrollExtent]. It can be negative infinity, if the scroll is unbounded.
double get minScrollExtent;
/// The maximum in-range value for [pixels].
///
/// The actual [pixels] value might be [outOfRange].
///
/// This value is typically greater than or equal to
/// [minScrollExtent]. It can be infinity, if the scroll is unbounded.
double get maxScrollExtent;
/// Whether the [minScrollExtent] and the [maxScrollExtent] properties are available.
bool get hasContentDimensions;
/// The current scroll position, in logical pixels along the [axisDirection].
double get pixels;
/// Whether the [pixels] property is available.
bool get hasPixels;
/// The extent of the viewport along the [axisDirection].
double get viewportDimension;
/// Whether the [viewportDimension] property is available.
bool get hasViewportDimension;
/// The direction in which the scroll view scrolls.
AxisDirection get axisDirection;
/// The axis in which the scroll view scrolls.
Axis get axis => axisDirectionToAxis(axisDirection);
/// Whether the [pixels] value is outside the [minScrollExtent] and
/// [maxScrollExtent].
bool get outOfRange => pixels < minScrollExtent || pixels > maxScrollExtent;
/// Whether the [pixels] value is exactly at the [minScrollExtent] or the
/// [maxScrollExtent].
bool get atEdge => pixels == minScrollExtent || pixels == maxScrollExtent;
/// The quantity of content conceptually "above" the viewport in the scrollable.
/// This is the content above the content described by [extentInside].
double get extentBefore => math.max(pixels - minScrollExtent, 0.0);
/// The quantity of content conceptually "inside" the viewport in the
/// scrollable (including empty space if the total amount of content is less
/// than the [viewportDimension]).
///
/// The value is typically the extent of the viewport ([viewportDimension])
/// when [outOfRange] is false. It can be less when overscrolling.
///
/// The value is always non-negative, and less than or equal to [viewportDimension].
double get extentInside {
assert(minScrollExtent <= maxScrollExtent);
return viewportDimension
// "above" overscroll value
- clampDouble(minScrollExtent - pixels, 0, viewportDimension)
// "below" overscroll value
- clampDouble(pixels - maxScrollExtent, 0, viewportDimension);
}
/// The quantity of content conceptually "below" the viewport in the scrollable.
/// This is the content below the content described by [extentInside].
double get extentAfter => math.max(maxScrollExtent - pixels, 0.0);
/// The total quantity of content available.
///
/// This is the sum of [extentBefore], [extentInside], and [extentAfter], modulo
/// any rounding errors.
double get extentTotal => maxScrollExtent - minScrollExtent + viewportDimension;
/// The [FlutterView.devicePixelRatio] of the view that the [Scrollable]
/// associated with this metrics object is drawn into.
double get devicePixelRatio;
}
/// An immutable snapshot of values associated with a [Scrollable] viewport.
///
/// For details, see [ScrollMetrics], which defines this object's interfaces.
///
/// {@tool dartpad}
/// This sample shows how a [ScrollMetricsNotification] is dispatched when
/// the [ScrollMetrics] changed as a result of resizing the [Viewport].
/// Press the floating action button to increase the scrollable window's size.
///
/// ** See code in examples/api/lib/widgets/scroll_position/scroll_metrics_notification.0.dart **
/// {@end-tool}
class FixedScrollMetrics with ScrollMetrics {
/// Creates an immutable snapshot of values associated with a [Scrollable] viewport.
FixedScrollMetrics({
required double? minScrollExtent,
required double? maxScrollExtent,
required double? pixels,
required double? viewportDimension,
required this.axisDirection,
required this.devicePixelRatio,
}) : _minScrollExtent = minScrollExtent,
_maxScrollExtent = maxScrollExtent,
_pixels = pixels,
_viewportDimension = viewportDimension;
@override
double get minScrollExtent => _minScrollExtent!;
final double? _minScrollExtent;
@override
double get maxScrollExtent => _maxScrollExtent!;
final double? _maxScrollExtent;
@override
bool get hasContentDimensions => _minScrollExtent != null && _maxScrollExtent != null;
@override
double get pixels => _pixels!;
final double? _pixels;
@override
bool get hasPixels => _pixels != null;
@override
double get viewportDimension => _viewportDimension!;
final double? _viewportDimension;
@override
bool get hasViewportDimension => _viewportDimension != null;
@override
final AxisDirection axisDirection;
@override
final double devicePixelRatio;
@override
String toString() {
return '${objectRuntimeType(this, 'FixedScrollMetrics')}(${extentBefore.toStringAsFixed(1)}..[${extentInside.toStringAsFixed(1)}]..${extentAfter.toStringAsFixed(1)})';
}
}
| flutter/packages/flutter/lib/src/widgets/scroll_metrics.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/scroll_metrics.dart",
"repo_id": "flutter",
"token_count": 2350
} | 823 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:collection';
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'actions.dart';
import 'focus_manager.dart';
import 'focus_scope.dart';
import 'framework.dart';
import 'platform_menu_bar.dart';
final Set<LogicalKeyboardKey> _controlSynonyms = LogicalKeyboardKey.expandSynonyms(<LogicalKeyboardKey>{LogicalKeyboardKey.control});
final Set<LogicalKeyboardKey> _shiftSynonyms = LogicalKeyboardKey.expandSynonyms(<LogicalKeyboardKey>{LogicalKeyboardKey.shift});
final Set<LogicalKeyboardKey> _altSynonyms = LogicalKeyboardKey.expandSynonyms(<LogicalKeyboardKey>{LogicalKeyboardKey.alt});
final Set<LogicalKeyboardKey> _metaSynonyms = LogicalKeyboardKey.expandSynonyms(<LogicalKeyboardKey>{LogicalKeyboardKey.meta});
/// A set of [KeyboardKey]s that can be used as the keys in a [Map].
///
/// A key set contains the keys that are down simultaneously to represent a
/// shortcut.
///
/// This is a thin wrapper around a [Set], but changes the equality comparison
/// from an identity comparison to a contents comparison so that non-identical
/// sets with the same keys in them will compare as equal.
///
/// See also:
///
/// * [ShortcutManager], which uses [LogicalKeySet] (a [KeySet] subclass) to
/// define its key map.
@immutable
class KeySet<T extends KeyboardKey> {
/// A constructor for making a [KeySet] of up to four keys.
///
/// If you need a set of more than four keys, use [KeySet.fromSet].
///
/// The same [KeyboardKey] may not be appear more than once in the set.
KeySet(
T key1, [
T? key2,
T? key3,
T? key4,
]) : _keys = HashSet<T>()..add(key1) {
int count = 1;
if (key2 != null) {
_keys.add(key2);
assert(() {
count++;
return true;
}());
}
if (key3 != null) {
_keys.add(key3);
assert(() {
count++;
return true;
}());
}
if (key4 != null) {
_keys.add(key4);
assert(() {
count++;
return true;
}());
}
assert(_keys.length == count, 'Two or more provided keys are identical. Each key must appear only once.');
}
/// Create a [KeySet] from a set of [KeyboardKey]s.
///
/// Do not mutate the `keys` set after passing it to this object.
///
/// The `keys` set must not be empty.
KeySet.fromSet(Set<T> keys)
: assert(keys.isNotEmpty),
assert(!keys.contains(null)),
_keys = HashSet<T>.of(keys);
/// Returns a copy of the [KeyboardKey]s in this [KeySet].
Set<T> get keys => _keys.toSet();
final HashSet<T> _keys;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is KeySet<T>
&& setEquals<T>(other._keys, _keys);
}
// Cached hash code value. Improves [hashCode] performance by 27%-900%,
// depending on key set size and read/write ratio.
@override
late final int hashCode = _computeHashCode(_keys);
// Arrays used to temporarily store hash codes for sorting.
static final List<int> _tempHashStore3 = <int>[0, 0, 0]; // used to sort exactly 3 keys
static final List<int> _tempHashStore4 = <int>[0, 0, 0, 0]; // used to sort exactly 4 keys
static int _computeHashCode<T>(Set<T> keys) {
// Compute order-independent hash and cache it.
final int length = keys.length;
final Iterator<T> iterator = keys.iterator;
// There's always at least one key. Just extract it.
iterator.moveNext();
final int h1 = iterator.current.hashCode;
if (length == 1) {
// Don't do anything fancy if there's exactly one key.
return h1;
}
iterator.moveNext();
final int h2 = iterator.current.hashCode;
if (length == 2) {
// No need to sort if there's two keys, just compare them.
return h1 < h2
? Object.hash(h1, h2)
: Object.hash(h2, h1);
}
// Sort key hash codes and feed to Object.hashAll to ensure the aggregate
// hash code does not depend on the key order.
final List<int> sortedHashes = length == 3
? _tempHashStore3
: _tempHashStore4;
sortedHashes[0] = h1;
sortedHashes[1] = h2;
iterator.moveNext();
sortedHashes[2] = iterator.current.hashCode;
if (length == 4) {
iterator.moveNext();
sortedHashes[3] = iterator.current.hashCode;
}
sortedHashes.sort();
return Object.hashAll(sortedHashes);
}
}
/// Determines how the state of a lock key is used to accept a shortcut.
enum LockState {
/// The lock key state is not used to determine [SingleActivator.accepts] result.
ignored,
/// The lock key must be locked to trigger the shortcut.
locked,
/// The lock key must be unlocked to trigger the shortcut.
unlocked,
}
/// An interface to define the keyboard key combination to trigger a shortcut.
///
/// [ShortcutActivator]s are used by [Shortcuts] widgets, and are mapped to
/// [Intent]s, the intended behavior that the key combination should trigger.
/// When a [Shortcuts] widget receives a key event, its [ShortcutManager] looks
/// up the first matching [ShortcutActivator], and signals the corresponding
/// [Intent], which might trigger an action as defined by a hierarchy of
/// [Actions] widgets. For a detailed introduction on the mechanism and use of
/// the shortcut-action system, see [Actions].
///
/// The matching [ShortcutActivator] is looked up in the following way:
///
/// * Find the registered [ShortcutActivator]s whose [triggers] contain the
/// incoming event.
/// * Of the previous list, finds the first activator whose [accepts] returns
/// true in the order of insertion.
///
/// See also:
///
/// * [SingleActivator], an implementation that represents a single key combined
/// with modifiers (control, shift, alt, meta).
/// * [CharacterActivator], an implementation that represents key combinations
/// that result in the specified character, such as question mark.
/// * [LogicalKeySet], an implementation that requires one or more
/// [LogicalKeyboardKey]s to be pressed at the same time. Prefer
/// [SingleActivator] when possible.
abstract class ShortcutActivator {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const ShortcutActivator();
/// An optional property to provide all the keys that might be the final event
/// to trigger this shortcut.
///
/// For example, for `Ctrl-A`, [LogicalKeyboardKey.keyA] is the only trigger,
/// while [LogicalKeyboardKey.control] is not, because the shortcut should
/// only work by pressing KeyA *after* Ctrl, but not before. For `Ctrl-A-E`,
/// on the other hand, both KeyA and KeyE should be triggers, since either of
/// them is allowed to trigger.
///
/// If provided, trigger keys can be used as a first-pass filter for incoming
/// events in order to optimize lookups, as [Intent]s are stored in a [Map]
/// and indexed by trigger keys. It is up to the individual implementors of
/// this interface to decide if they ignore triggers or not.
///
/// Subclasses should make sure that the return value of this method does not
/// change throughout the lifespan of this object.
///
/// This method might also return null, which means this activator declares
/// all keys as trigger keys. Activators whose [triggers] return null will be
/// tested with [accepts] on every event. Since this becomes a linear search,
/// and having too many might impact performance, it is preferred to return
/// non-null [triggers] whenever possible.
Iterable<LogicalKeyboardKey>? get triggers => null;
/// Whether the triggering `event` and the keyboard `state` at the time of the
/// event meet required conditions, providing that the event is a triggering
/// event.
///
/// For example, for `Ctrl-A`, it has to check if the event is a
/// [KeyDownEvent], if either side of the Ctrl key is pressed, and none of the
/// Shift keys, Alt keys, or Meta keys are pressed; it doesn't have to check
/// if KeyA is pressed, since it's already guaranteed.
///
/// As a possible performance improvement, implementers of this function are
/// encouraged (but not required) to check the [triggers] member, if it is
/// non-null, to see if it contains the event's logical key before doing more
/// complicated work.
///
/// This method must not cause any side effects for the `state`. Typically
/// this is only used to query whether [HardwareKeyboard.logicalKeysPressed]
/// contains a key.
///
/// See also:
///
/// * [LogicalKeyboardKey.collapseSynonyms], which helps deciding whether a
/// modifier key is pressed when the side variation is not important.
bool accepts(KeyEvent event, HardwareKeyboard state);
/// Returns true if the event and current [HardwareKeyboard] state would cause
/// this [ShortcutActivator] to be activated.
@Deprecated(
'Call accepts on the activator instead. '
'This feature was deprecated after v3.16.0-15.0.pre.',
)
static bool isActivatedBy(ShortcutActivator activator, KeyEvent event) {
return activator.accepts(event, HardwareKeyboard.instance);
}
/// Returns a description of the key set that is short and readable.
///
/// Intended to be used in debug mode for logging purposes.
String debugDescribeKeys();
}
/// A set of [LogicalKeyboardKey]s that can be used as the keys in a map.
///
/// [LogicalKeySet] can be used as a [ShortcutActivator]. It is not recommended
/// to use [LogicalKeySet] for a common shortcut such as `Delete` or `Ctrl+C`,
/// prefer [SingleActivator] when possible, whose behavior more closely resembles
/// that of typical platforms.
///
/// When used as a [ShortcutActivator], [LogicalKeySet] will activate the intent
/// when all [keys] are pressed, and no others, except that modifier keys are
/// considered without considering sides (e.g. control left and control right are
/// considered the same).
///
/// {@tool dartpad}
/// In the following example, the counter is increased when the following key
/// sequences are pressed:
///
/// * Control left, then C.
/// * Control right, then C.
/// * C, then Control left.
///
/// But not when:
///
/// * Control left, then A, then C.
///
/// ** See code in examples/api/lib/widgets/shortcuts/logical_key_set.0.dart **
/// {@end-tool}
///
/// This is also a thin wrapper around a [Set], but changes the equality
/// comparison from an identity comparison to a contents comparison so that
/// non-identical sets with the same keys in them will compare as equal.
class LogicalKeySet extends KeySet<LogicalKeyboardKey> with Diagnosticable
implements ShortcutActivator {
/// A constructor for making a [LogicalKeySet] of up to four keys.
///
/// If you need a set of more than four keys, use [LogicalKeySet.fromSet].
///
/// The same [LogicalKeyboardKey] may not be appear more than once in the set.
LogicalKeySet(
super.key1, [
super.key2,
super.key3,
super.key4,
]);
/// Create a [LogicalKeySet] from a set of [LogicalKeyboardKey]s.
///
/// Do not mutate the `keys` set after passing it to this object.
LogicalKeySet.fromSet(super.keys) : super.fromSet();
@override
Iterable<LogicalKeyboardKey> get triggers => _triggers;
late final Set<LogicalKeyboardKey> _triggers = keys.expand(
(LogicalKeyboardKey key) => _unmapSynonyms[key] ?? <LogicalKeyboardKey>[key],
).toSet();
bool _checkKeyRequirements(Set<LogicalKeyboardKey> pressed) {
final Set<LogicalKeyboardKey> collapsedRequired = LogicalKeyboardKey.collapseSynonyms(keys);
final Set<LogicalKeyboardKey> collapsedPressed = LogicalKeyboardKey.collapseSynonyms(pressed);
return collapsedRequired.length == collapsedPressed.length
&& collapsedRequired.difference(collapsedPressed).isEmpty;
}
@override
bool accepts(KeyEvent event, HardwareKeyboard state) {
if (event is! KeyDownEvent && event is! KeyRepeatEvent) {
return false;
}
return triggers.contains(event.logicalKey)
&& _checkKeyRequirements(state.logicalKeysPressed);
}
static final Set<LogicalKeyboardKey> _modifiers = <LogicalKeyboardKey>{
LogicalKeyboardKey.alt,
LogicalKeyboardKey.control,
LogicalKeyboardKey.meta,
LogicalKeyboardKey.shift,
};
static final Map<LogicalKeyboardKey, List<LogicalKeyboardKey>> _unmapSynonyms = <LogicalKeyboardKey, List<LogicalKeyboardKey>>{
LogicalKeyboardKey.control: <LogicalKeyboardKey>[LogicalKeyboardKey.controlLeft, LogicalKeyboardKey.controlRight],
LogicalKeyboardKey.shift: <LogicalKeyboardKey>[LogicalKeyboardKey.shiftLeft, LogicalKeyboardKey.shiftRight],
LogicalKeyboardKey.alt: <LogicalKeyboardKey>[LogicalKeyboardKey.altLeft, LogicalKeyboardKey.altRight],
LogicalKeyboardKey.meta: <LogicalKeyboardKey>[LogicalKeyboardKey.metaLeft, LogicalKeyboardKey.metaRight],
};
@override
String debugDescribeKeys() {
final List<LogicalKeyboardKey> sortedKeys = keys.toList()
..sort((LogicalKeyboardKey a, LogicalKeyboardKey b) {
// Put the modifiers first. If it has a synonym, then it's something
// like shiftLeft, altRight, etc.
final bool aIsModifier = a.synonyms.isNotEmpty || _modifiers.contains(a);
final bool bIsModifier = b.synonyms.isNotEmpty || _modifiers.contains(b);
if (aIsModifier && !bIsModifier) {
return -1;
} else if (bIsModifier && !aIsModifier) {
return 1;
}
return a.debugName!.compareTo(b.debugName!);
});
return sortedKeys.map<String>((LogicalKeyboardKey key) => key.debugName.toString()).join(' + ');
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Set<LogicalKeyboardKey>>('keys', _keys, description: debugDescribeKeys()));
}
}
/// A [DiagnosticsProperty] which handles formatting a `Map<LogicalKeySet, Intent>`
/// (the same type as the [Shortcuts.shortcuts] property) so that its
/// diagnostic output is human-readable.
class ShortcutMapProperty extends DiagnosticsProperty<Map<ShortcutActivator, Intent>> {
/// Create a diagnostics property for `Map<ShortcutActivator, Intent>` objects,
/// which are the same type as the [Shortcuts.shortcuts] property.
ShortcutMapProperty(
String super.name,
Map<ShortcutActivator, Intent> super.value, {
super.showName,
Object super.defaultValue,
super.level,
super.description,
});
@override
Map<ShortcutActivator, Intent> get value => super.value!;
@override
String valueToString({TextTreeConfiguration? parentConfiguration}) {
return '{${value.keys.map<String>((ShortcutActivator keySet) => '{${keySet.debugDescribeKeys()}}: ${value[keySet]}').join(', ')}}';
}
}
/// A shortcut key combination of a single key and modifiers.
///
/// The [SingleActivator] implements typical shortcuts such as:
///
/// * ArrowLeft
/// * Shift + Delete
/// * Control + Alt + Meta + Shift + A
///
/// More specifically, it creates shortcut key combinations that are composed of a
/// [trigger] key, and zero, some, or all of the four modifiers (control, shift,
/// alt, meta). The shortcut is activated when the following conditions are met:
///
/// * The incoming event is a down event for a [trigger] key.
/// * If [control] is true, then at least one control key must be held.
/// Otherwise, no control keys must be held.
/// * Similar conditions apply for the [alt], [shift], and [meta] keys.
///
/// This resembles the typical behavior of most operating systems, and handles
/// modifier keys differently from [LogicalKeySet] in the following way:
///
/// * [SingleActivator]s allow additional non-modifier keys being pressed in
/// order to activate the shortcut. For example, pressing key X while holding
/// ControlLeft *and key A* will be accepted by
/// `SingleActivator(LogicalKeyboardKey.keyX, control: true)`.
/// * [SingleActivator]s do not consider modifiers to be a trigger key. For
/// example, pressing ControlLeft while holding key X *will not* activate a
/// `SingleActivator(LogicalKeyboardKey.keyX, control: true)`.
///
/// See also:
///
/// * [CharacterActivator], an activator that represents key combinations
/// that result in the specified character, such as question mark.
class SingleActivator with Diagnosticable, MenuSerializableShortcut implements ShortcutActivator {
/// Triggered when the [trigger] key is pressed while the modifiers are held.
///
/// The [trigger] should be the non-modifier key that is pressed after all the
/// modifiers, such as [LogicalKeyboardKey.keyC] as in `Ctrl+C`. It must not
/// be a modifier key (sided or unsided).
///
/// The [control], [shift], [alt], and [meta] flags represent whether the
/// respective modifier keys should be held (true) or released (false). They
/// default to false.
///
/// By default, the activator is checked on all [KeyDownEvent] events for the
/// [trigger] key. If [includeRepeats] is false, only [trigger] key events
/// which are not [KeyRepeatEvent]s will be considered.
///
/// {@tool dartpad}
/// In the following example, the shortcut `Control + C` increases the
/// counter:
///
/// ** See code in examples/api/lib/widgets/shortcuts/single_activator.single_activator.0.dart **
/// {@end-tool}
const SingleActivator(
this.trigger, {
this.control = false,
this.shift = false,
this.alt = false,
this.meta = false,
this.numLock = LockState.ignored,
this.includeRepeats = true,
}) : // The enumerated check with `identical` is cumbersome but the only way
// since const constructors can not call functions such as `==` or
// `Set.contains`. Checking with `identical` might not work when the
// key object is created from ID, but it covers common cases.
assert(
!identical(trigger, LogicalKeyboardKey.control) &&
!identical(trigger, LogicalKeyboardKey.controlLeft) &&
!identical(trigger, LogicalKeyboardKey.controlRight) &&
!identical(trigger, LogicalKeyboardKey.shift) &&
!identical(trigger, LogicalKeyboardKey.shiftLeft) &&
!identical(trigger, LogicalKeyboardKey.shiftRight) &&
!identical(trigger, LogicalKeyboardKey.alt) &&
!identical(trigger, LogicalKeyboardKey.altLeft) &&
!identical(trigger, LogicalKeyboardKey.altRight) &&
!identical(trigger, LogicalKeyboardKey.meta) &&
!identical(trigger, LogicalKeyboardKey.metaLeft) &&
!identical(trigger, LogicalKeyboardKey.metaRight),
);
/// The non-modifier key of the shortcut that is pressed after all modifiers
/// to activate the shortcut.
///
/// For example, for `Control + C`, [trigger] should be
/// [LogicalKeyboardKey.keyC].
final LogicalKeyboardKey trigger;
/// Whether either (or both) control keys should be held for [trigger] to
/// activate the shortcut.
///
/// It defaults to false, meaning all Control keys must be released when the
/// event is received in order to activate the shortcut. If it's true, then
/// either or both Control keys must be pressed.
///
/// See also:
///
/// * [LogicalKeyboardKey.controlLeft], [LogicalKeyboardKey.controlRight].
final bool control;
/// Whether either (or both) shift keys should be held for [trigger] to
/// activate the shortcut.
///
/// It defaults to false, meaning all Shift keys must be released when the
/// event is received in order to activate the shortcut. If it's true, then
/// either or both Shift keys must be pressed.
///
/// See also:
///
/// * [LogicalKeyboardKey.shiftLeft], [LogicalKeyboardKey.shiftRight].
final bool shift;
/// Whether either (or both) alt keys should be held for [trigger] to
/// activate the shortcut.
///
/// It defaults to false, meaning all Alt keys must be released when the
/// event is received in order to activate the shortcut. If it's true, then
/// either or both Alt keys must be pressed.
///
/// See also:
///
/// * [LogicalKeyboardKey.altLeft], [LogicalKeyboardKey.altRight].
final bool alt;
/// Whether either (or both) meta keys should be held for [trigger] to
/// activate the shortcut.
///
/// It defaults to false, meaning all Meta keys must be released when the
/// event is received in order to activate the shortcut. If it's true, then
/// either or both Meta keys must be pressed.
///
/// See also:
///
/// * [LogicalKeyboardKey.metaLeft], [LogicalKeyboardKey.metaRight].
final bool meta;
/// Whether the NumLock key state should be checked for [trigger] to activate
/// the shortcut.
///
/// It defaults to [LockState.ignored], meaning the NumLock state is ignored
/// when the event is received in order to activate the shortcut.
/// If it's [LockState.locked], then the NumLock key must be locked.
/// If it's [LockState.unlocked], then the NumLock key must be unlocked.
///
/// See also:
///
/// * [LogicalKeyboardKey.numLock].
final LockState numLock;
/// Whether this activator accepts repeat events of the [trigger] key.
///
/// If [includeRepeats] is true, the activator is checked on all
/// [KeyDownEvent] or [KeyRepeatEvent]s for the [trigger] key. If
/// [includeRepeats] is false, only [trigger] key events which are
/// [KeyDownEvent]s will be considered.
final bool includeRepeats;
@override
Iterable<LogicalKeyboardKey> get triggers {
return <LogicalKeyboardKey>[trigger];
}
bool _shouldAcceptModifiers(Set<LogicalKeyboardKey> pressed) {
return control == pressed.intersection(_controlSynonyms).isNotEmpty
&& shift == pressed.intersection(_shiftSynonyms).isNotEmpty
&& alt == pressed.intersection(_altSynonyms).isNotEmpty
&& meta == pressed.intersection(_metaSynonyms).isNotEmpty;
}
bool _shouldAcceptNumLock(HardwareKeyboard state) {
return switch (numLock) {
LockState.ignored => true,
LockState.locked => state.lockModesEnabled.contains(KeyboardLockMode.numLock),
LockState.unlocked => !state.lockModesEnabled.contains(KeyboardLockMode.numLock),
};
}
@override
bool accepts(KeyEvent event, HardwareKeyboard state) {
return (event is KeyDownEvent || (includeRepeats && event is KeyRepeatEvent))
&& triggers.contains(event.logicalKey)
&& _shouldAcceptModifiers(state.logicalKeysPressed)
&& _shouldAcceptNumLock(state);
}
@override
ShortcutSerialization serializeForMenu() {
return ShortcutSerialization.modifier(
trigger,
shift: shift,
alt: alt,
meta: meta,
control: control,
);
}
/// Returns a short and readable description of the key combination.
///
/// Intended to be used in debug mode for logging purposes. In release mode,
/// [debugDescribeKeys] returns an empty string.
@override
String debugDescribeKeys() {
String result = '';
assert(() {
final List<String> keys = <String>[
if (control) 'Control',
if (alt) 'Alt',
if (meta) 'Meta',
if (shift) 'Shift',
trigger.debugName ?? trigger.toStringShort(),
];
result = keys.join(' + ');
return true;
}());
return result;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(MessageProperty('keys', debugDescribeKeys()));
properties.add(FlagProperty('includeRepeats', value: includeRepeats, ifFalse: 'excluding repeats'));
}
}
/// A shortcut combination that is triggered by a key event that produces a
/// specific character.
///
/// Keys often produce different characters when combined with modifiers. For
/// example, it might be helpful for the user to bring up a help menu by
/// pressing the question mark ('?'). However, there is no logical key that
/// directly represents a question mark. Although 'Shift+Slash' produces a '?'
/// character on a US keyboard, its logical key is still considered a Slash key,
/// and hard-coding 'Shift+Slash' in this situation is unfriendly to other
/// keyboard layouts.
///
/// For example, `CharacterActivator('?')` is triggered when a key combination
/// results in a question mark, which is 'Shift+Slash' on a US keyboard, but
/// 'Shift+Comma' on a French keyboard.
///
/// {@tool dartpad}
/// In the following example, when a key combination results in a question mark,
/// the counter is increased:
///
/// ** See code in examples/api/lib/widgets/shortcuts/character_activator.0.dart **
/// {@end-tool}
///
/// The [alt], [control], and [meta] flags represent whether the respective
/// modifier keys should be held (true) or released (false). They default to
/// false. [CharacterActivator] cannot check shifted keys, since the Shift key
/// affects the resulting character, and will accept whether either of the
/// Shift keys are pressed or not, as long as the key event produces the
/// correct character.
///
/// By default, the activator is checked on all [KeyDownEvent] or
/// [KeyRepeatEvent]s for the [character] in combination with the requested
/// modifier keys. If `includeRepeats` is false, only the [character] events
/// with that are [KeyDownEvent]s will be considered.
///
/// {@template flutter.widgets.shortcuts.CharacterActivator.alt}
/// On macOS and iOS, the [alt] flag indicates that the Option key (⌥) is
/// pressed. Because the Option key affects the character generated on these
/// platforms, it can be unintuitive to define [CharacterActivator]s for them.
///
/// For instance, if you want the shortcut to trigger when Option+s (⌥-s) is
/// pressed, and what you intend is to trigger whenever the character 'ß' is
/// produced, you would use `CharacterActivator('ß')` or
/// `CharacterActivator('ß', alt: true)` instead of `CharacterActivator('s',
/// alt: true)`. This is because `CharacterActivator('s', alt: true)` will
/// never trigger, since the 's' character can't be produced when the Option
/// key is held down.
///
/// If what is intended is that the shortcut is triggered when Option+s (⌥-s)
/// is pressed, regardless of which character is produced, it is better to use
/// [SingleActivator], as in `SingleActivator(LogicalKeyboardKey.keyS, alt:
/// true)`.
/// {@endtemplate}
///
/// See also:
///
/// * [SingleActivator], an activator that represents a single key combined
/// with modifiers, such as `Ctrl+C` or `Ctrl-Right Arrow`.
class CharacterActivator with Diagnosticable, MenuSerializableShortcut implements ShortcutActivator {
/// Triggered when the key event yields the given character.
const CharacterActivator(this.character, {
this.alt = false,
this.control = false,
this.meta = false,
this.includeRepeats = true,
});
/// Whether either (or both) Alt keys should be held for the [character] to
/// activate the shortcut.
///
/// It defaults to false, meaning all Alt keys must be released when the event
/// is received in order to activate the shortcut. If it's true, then either
/// one or both Alt keys must be pressed.
///
/// {@macro flutter.widgets.shortcuts.CharacterActivator.alt}
///
/// See also:
///
/// * [LogicalKeyboardKey.altLeft], [LogicalKeyboardKey.altRight].
final bool alt;
/// Whether either (or both) Control keys should be held for the [character]
/// to activate the shortcut.
///
/// It defaults to false, meaning all Control keys must be released when the
/// event is received in order to activate the shortcut. If it's true, then
/// either one or both Control keys must be pressed.
///
/// See also:
///
/// * [LogicalKeyboardKey.controlLeft], [LogicalKeyboardKey.controlRight].
final bool control;
/// Whether either (or both) Meta keys should be held for the [character] to
/// activate the shortcut.
///
/// It defaults to false, meaning all Meta keys must be released when the
/// event is received in order to activate the shortcut. If it's true, then
/// either one or both Meta keys must be pressed.
///
/// See also:
///
/// * [LogicalKeyboardKey.metaLeft], [LogicalKeyboardKey.metaRight].
final bool meta;
/// Whether this activator accepts repeat events of the [character].
///
/// If [includeRepeats] is true, the activator is checked on all
/// [KeyDownEvent] and [KeyRepeatEvent]s for the [character]. If
/// [includeRepeats] is false, only the [character] events that are
/// [KeyDownEvent]s will be considered.
final bool includeRepeats;
/// The character which triggers the shortcut.
///
/// This is typically a single-character string, such as '?' or 'œ', although
/// [CharacterActivator] doesn't check the length of [character] or whether it
/// can be matched by any key combination at all. It is case-sensitive, since
/// the [character] is directly compared by `==` to the character reported by
/// the platform.
///
/// See also:
///
/// * [KeyEvent.character], the character of a key event.
final String character;
@override
Iterable<LogicalKeyboardKey>? get triggers => null;
bool _shouldAcceptModifiers(Set<LogicalKeyboardKey> pressed) {
// Doesn't look for shift, since the character will encode that.
return control == pressed.intersection(_controlSynonyms).isNotEmpty
&& alt == pressed.intersection(_altSynonyms).isNotEmpty
&& meta == pressed.intersection(_metaSynonyms).isNotEmpty;
}
@override
bool accepts(KeyEvent event, HardwareKeyboard state) {
// Ignore triggers, since we're only interested in the character.
return event.character == character
&& (event is KeyDownEvent || (includeRepeats && event is KeyRepeatEvent))
&& _shouldAcceptModifiers(state.logicalKeysPressed);
}
@override
String debugDescribeKeys() {
String result = '';
assert(() {
final List<String> keys = <String>[
if (alt) 'Alt',
if (control) 'Control',
if (meta) 'Meta',
"'$character'",
];
result = keys.join(' + ');
return true;
}());
return result;
}
@override
ShortcutSerialization serializeForMenu() {
return ShortcutSerialization.character(character, alt: alt, control: control, meta: meta);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(MessageProperty('character', debugDescribeKeys()));
properties.add(FlagProperty('includeRepeats', value: includeRepeats, ifFalse: 'excluding repeats'));
}
}
class _ActivatorIntentPair with Diagnosticable {
const _ActivatorIntentPair(this.activator, this.intent);
final ShortcutActivator activator;
final Intent intent;
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<String>('activator', activator.debugDescribeKeys()));
properties.add(DiagnosticsProperty<Intent>('intent', intent));
}
}
/// A manager of keyboard shortcut bindings used by [Shortcuts] to handle key
/// events.
///
/// The manager may be listened to (with [addListener]/[removeListener]) for
/// change notifications when the shortcuts change.
///
/// Typically, a [Shortcuts] widget supplies its own manager, but in uncommon
/// cases where overriding the usual shortcut manager behavior is desired, a
/// subclassed [ShortcutManager] may be supplied.
class ShortcutManager with Diagnosticable, ChangeNotifier {
/// Constructs a [ShortcutManager].
ShortcutManager({
Map<ShortcutActivator, Intent> shortcuts = const <ShortcutActivator, Intent>{},
this.modal = false,
}) : _shortcuts = shortcuts {
if (kFlutterMemoryAllocationsEnabled) {
ChangeNotifier.maybeDispatchObjectCreation(this);
}
}
/// True if the [ShortcutManager] should not pass on keys that it doesn't
/// handle to any key-handling widgets that are ancestors to this one.
///
/// Setting [modal] to true will prevent any key event given to this manager
/// from being given to any ancestor managers, even if that key doesn't appear
/// in the [shortcuts] map.
///
/// The net effect of setting [modal] to true is to return
/// [KeyEventResult.skipRemainingHandlers] from [handleKeypress] if it does
/// not exist in the shortcut map, instead of returning
/// [KeyEventResult.ignored].
final bool modal;
/// Returns the shortcut map.
///
/// When the map is changed, listeners to this manager will be notified.
///
/// The returned map should not be modified.
Map<ShortcutActivator, Intent> get shortcuts => _shortcuts;
Map<ShortcutActivator, Intent> _shortcuts = <ShortcutActivator, Intent>{};
set shortcuts(Map<ShortcutActivator, Intent> value) {
if (!mapEquals<ShortcutActivator, Intent>(_shortcuts, value)) {
_shortcuts = value;
_indexedShortcutsCache = null;
notifyListeners();
}
}
static Map<LogicalKeyboardKey?, List<_ActivatorIntentPair>> _indexShortcuts(Map<ShortcutActivator, Intent> source) {
final Map<LogicalKeyboardKey?, List<_ActivatorIntentPair>> result = <LogicalKeyboardKey?, List<_ActivatorIntentPair>>{};
source.forEach((ShortcutActivator activator, Intent intent) {
// This intermediate variable is necessary to comply with Dart analyzer.
final Iterable<LogicalKeyboardKey?>? nullableTriggers = activator.triggers;
for (final LogicalKeyboardKey? trigger in nullableTriggers ?? <LogicalKeyboardKey?>[null]) {
result.putIfAbsent(trigger, () => <_ActivatorIntentPair>[])
.add(_ActivatorIntentPair(activator, intent));
}
});
return result;
}
Map<LogicalKeyboardKey?, List<_ActivatorIntentPair>> get _indexedShortcuts {
return _indexedShortcutsCache ??= _indexShortcuts(shortcuts);
}
Map<LogicalKeyboardKey?, List<_ActivatorIntentPair>>? _indexedShortcutsCache;
Iterable<_ActivatorIntentPair> _getCandidates(LogicalKeyboardKey key) {
return <_ActivatorIntentPair>[
... _indexedShortcuts[key] ?? <_ActivatorIntentPair>[],
... _indexedShortcuts[null] ?? <_ActivatorIntentPair>[],
];
}
/// Returns the [Intent], if any, that matches the current set of pressed
/// keys.
///
/// Returns null if no intent matches the current set of pressed keys.
Intent? _find(KeyEvent event, HardwareKeyboard state) {
for (final _ActivatorIntentPair activatorIntent in _getCandidates(event.logicalKey)) {
if (activatorIntent.activator.accepts(event, state)) {
return activatorIntent.intent;
}
}
return null;
}
/// Handles a key press `event` in the given `context`.
///
/// If a key mapping is found, then the associated action will be invoked
/// using the [Intent] activated by the [ShortcutActivator] in the [shortcuts]
/// map, and the currently focused widget's context (from
/// [FocusManager.primaryFocus]).
///
/// Returns a [KeyEventResult.handled] if an action was invoked, otherwise a
/// [KeyEventResult.skipRemainingHandlers] if [modal] is true, or if it maps
/// to a [DoNothingAction] with [DoNothingAction.consumesKey] set to false,
/// and in all other cases returns [KeyEventResult.ignored].
///
/// In order for an action to be invoked (and [KeyEventResult.handled]
/// returned), a [ShortcutActivator] must accept the given [KeyEvent], be
/// mapped to an [Intent], the [Intent] must be mapped to an [Action], and the
/// [Action] must be enabled.
@protected
KeyEventResult handleKeypress(BuildContext context, KeyEvent event) {
final Intent? matchedIntent = _find(event, HardwareKeyboard.instance);
if (matchedIntent != null) {
final BuildContext? primaryContext = primaryFocus?.context;
if (primaryContext != null) {
final Action<Intent>? action = Actions.maybeFind<Intent>(
primaryContext,
intent: matchedIntent,
);
if (action != null) {
final (bool enabled, Object? invokeResult) = Actions.of(primaryContext).invokeActionIfEnabled(
action, matchedIntent, primaryContext,
);
if (enabled) {
return action.toKeyEventResult(matchedIntent, invokeResult);
}
}
}
}
return modal ? KeyEventResult.skipRemainingHandlers : KeyEventResult.ignored;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Map<ShortcutActivator, Intent>>('shortcuts', shortcuts));
properties.add(FlagProperty('modal', value: modal, ifTrue: 'modal', defaultValue: false));
}
}
/// A widget that creates key bindings to specific actions for its
/// descendants.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=6ZcQmdoz9N8}
///
/// This widget establishes a [ShortcutManager] to be used by its descendants
/// when invoking an [Action] via a keyboard key combination that maps to an
/// [Intent].
///
/// This is similar to but more powerful than the [CallbackShortcuts] widget.
/// Unlike [CallbackShortcuts], this widget separates key bindings and their
/// implementations. This separation allows [Shortcuts] to have key bindings
/// that adapt to the focused context. For example, the desired action for a
/// deletion intent may be to delete a character in a text input, or to delete
/// a file in a file menu.
///
/// See the article on [Using Actions and
/// Shortcuts](https://docs.flutter.dev/development/ui/advanced/actions_and_shortcuts)
/// for a detailed explanation.
///
/// {@tool dartpad}
/// Here, we will use the [Shortcuts] and [Actions] widgets to add and subtract
/// from a counter. When the child widget has keyboard focus, and a user presses
/// the keys that have been defined in [Shortcuts], the action that is bound
/// to the appropriate [Intent] for the key is invoked.
///
/// It also shows the use of a [CallbackAction] to avoid creating a new [Action]
/// subclass.
///
/// ** See code in examples/api/lib/widgets/shortcuts/shortcuts.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This slightly more complicated, but more flexible, example creates a custom
/// [Action] subclass to increment and decrement within a widget (a [Column])
/// that has keyboard focus. When the user presses the up and down arrow keys,
/// the counter will increment and decrement a data model using the custom
/// actions.
///
/// One thing that this demonstrates is passing arguments to the [Intent] to be
/// carried to the [Action]. This shows how actions can get data either from
/// their own construction (like the `model` in this example), or from the
/// intent passed to them when invoked (like the increment `amount` in this
/// example).
///
/// ** See code in examples/api/lib/widgets/shortcuts/shortcuts.1.dart **
/// {@end-tool}
///
/// See also:
///
/// * [CallbackShortcuts], a simpler but less flexible widget that defines key
/// bindings that invoke callbacks.
/// * [Intent], a class for containing a description of a user action to be
/// invoked.
/// * [Action], a class for defining an invocation of a user action.
/// * [CallbackAction], a class for creating an action from a callback.
class Shortcuts extends StatefulWidget {
/// Creates a const [Shortcuts] widget that owns the map of shortcuts and
/// creates its own manager.
///
/// When using this constructor, [manager] will return null.
///
/// The [child] and [shortcuts] arguments are required.
///
/// See also:
///
/// * [Shortcuts.manager], a constructor that uses a [ShortcutManager] to
/// manage the shortcuts list instead.
const Shortcuts({
super.key,
required Map<ShortcutActivator, Intent> shortcuts,
required this.child,
this.debugLabel,
}) : _shortcuts = shortcuts,
manager = null;
/// Creates a const [Shortcuts] widget that uses the [manager] to
/// manage the map of shortcuts.
///
/// If this constructor is used, [shortcuts] will return the contents of
/// [ShortcutManager.shortcuts].
///
/// The [child] and [manager] arguments are required.
const Shortcuts.manager({
super.key,
required ShortcutManager this.manager,
required this.child,
this.debugLabel,
}) : _shortcuts = const <ShortcutActivator, Intent>{};
/// The [ShortcutManager] that will manage the mapping between key
/// combinations and [Action]s.
///
/// If this widget was created with [Shortcuts.manager], then
/// [ShortcutManager.shortcuts] will be used as the source for shortcuts. If
/// the unnamed constructor is used, this manager will be null, and a
/// default-constructed [ShortcutManager] will be used.
final ShortcutManager? manager;
/// {@template flutter.widgets.shortcuts.shortcuts}
/// The map of shortcuts that describes the mapping between a key sequence
/// defined by a [ShortcutActivator] and the [Intent] that will be emitted
/// when that key sequence is pressed.
/// {@endtemplate}
Map<ShortcutActivator, Intent> get shortcuts {
return manager == null ? _shortcuts : manager!.shortcuts;
}
final Map<ShortcutActivator, Intent> _shortcuts;
/// The child widget for this [Shortcuts] widget.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
/// The debug label that is printed for this node when logged.
///
/// If this label is set, then it will be displayed instead of the shortcut
/// map when logged.
///
/// This allows simplifying the diagnostic output to avoid cluttering it
/// unnecessarily with large default shortcut maps.
final String? debugLabel;
@override
State<Shortcuts> createState() => _ShortcutsState();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<ShortcutManager>('manager', manager, defaultValue: null));
properties.add(ShortcutMapProperty('shortcuts', shortcuts, description: debugLabel?.isNotEmpty ?? false ? debugLabel : null));
}
}
class _ShortcutsState extends State<Shortcuts> {
ShortcutManager? _internalManager;
ShortcutManager get manager => widget.manager ?? _internalManager!;
@override
void dispose() {
_internalManager?.dispose();
super.dispose();
}
@override
void initState() {
super.initState();
if (widget.manager == null) {
_internalManager = ShortcutManager();
_internalManager!.shortcuts = widget.shortcuts;
}
}
@override
void didUpdateWidget(Shortcuts oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.manager != oldWidget.manager) {
if (widget.manager != null) {
_internalManager?.dispose();
_internalManager = null;
} else {
_internalManager ??= ShortcutManager();
}
}
_internalManager?.shortcuts = widget.shortcuts;
}
KeyEventResult _handleOnKeyEvent(FocusNode node, KeyEvent event) {
if (node.context == null) {
return KeyEventResult.ignored;
}
return manager.handleKeypress(node.context!, event);
}
@override
Widget build(BuildContext context) {
return Focus(
debugLabel: '$Shortcuts',
canRequestFocus: false,
onKeyEvent: _handleOnKeyEvent,
child: widget.child,
);
}
}
/// A widget that binds key combinations to specific callbacks.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=VcQQ1ns_qNY}
///
/// This is similar to but simpler than the [Shortcuts] widget as it doesn't
/// require [Intent]s and [Actions] widgets. Instead, it accepts a map
/// of [ShortcutActivator]s to [VoidCallback]s.
///
/// Unlike [Shortcuts], this widget does not separate key bindings and their
/// implementations. This separation allows [Shortcuts] to have key bindings
/// that adapt to the focused context. For example, the desired action for a
/// deletion intent may be to delete a character in a text input, or to delete
/// a file in a file menu.
///
/// {@tool dartpad}
/// This example uses the [CallbackShortcuts] widget to add and subtract
/// from a counter when the up or down arrow keys are pressed.
///
/// ** See code in examples/api/lib/widgets/shortcuts/callback_shortcuts.0.dart **
/// {@end-tool}
///
/// [Shortcuts] and [CallbackShortcuts] can both be used in the same app. As
/// with any key handling widget, if this widget handles a key event then
/// widgets above it in the focus chain will not receive the event. This means
/// that if this widget handles a key, then an ancestor [Shortcuts] widget (or
/// any other key handling widget) will not receive that key. Similarly, if
/// a descendant of this widget handles the key, then the key event will not
/// reach this widget for handling.
///
/// See the article on [Using Actions and
/// Shortcuts](https://docs.flutter.dev/development/ui/advanced/actions_and_shortcuts)
/// for a detailed explanation.
///
/// See also:
/// * [Shortcuts], a more powerful widget for defining key bindings.
/// * [Focus], a widget that defines which widgets can receive keyboard focus.
class CallbackShortcuts extends StatelessWidget {
/// Creates a const [CallbackShortcuts] widget.
const CallbackShortcuts({
super.key,
required this.bindings,
required this.child,
});
/// A map of key combinations to callbacks used to define the shortcut
/// bindings.
///
/// If a descendant of this widget has focus, and a key is pressed, the
/// activator keys of this map will be asked if they accept the key event. If
/// they do, then the corresponding callback is invoked, and the key event
/// propagation is halted. If none of the activators accept the key event,
/// then the key event continues to be propagated up the focus chain.
///
/// If more than one activator accepts the key event, then all of the
/// callbacks associated with activators that accept the key event are
/// invoked.
///
/// Some examples of [ShortcutActivator] subclasses that can be used to define
/// the key combinations here are [SingleActivator], [CharacterActivator], and
/// [LogicalKeySet].
final Map<ShortcutActivator, VoidCallback> bindings;
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
// A helper function to make the stack trace more useful if the callback
// throws, by providing the activator and event as arguments that will appear
// in the stack trace.
bool _applyKeyEventBinding(ShortcutActivator activator, KeyEvent event) {
if (activator.accepts(event, HardwareKeyboard.instance)) {
bindings[activator]!.call();
return true;
}
return false;
}
@override
Widget build(BuildContext context) {
return Focus(
canRequestFocus: false,
skipTraversal: true,
onKeyEvent: (FocusNode node, KeyEvent event) {
KeyEventResult result = KeyEventResult.ignored;
// Activates all key bindings that match, returns "handled" if any handle it.
for (final ShortcutActivator activator in bindings.keys) {
result = _applyKeyEventBinding(activator, event) ? KeyEventResult.handled : result;
}
return result;
},
child: child,
);
}
}
/// A entry returned by [ShortcutRegistry.addAll] that allows the caller to
/// identify the shortcuts they registered with the [ShortcutRegistry] through
/// the [ShortcutRegistrar].
///
/// When the entry is no longer needed, [dispose] should be called, and the
/// entry should no longer be used.
class ShortcutRegistryEntry {
// Tokens can only be created by the ShortcutRegistry.
const ShortcutRegistryEntry._(this.registry);
/// The [ShortcutRegistry] that this entry was issued by.
final ShortcutRegistry registry;
/// Replaces the given shortcut bindings in the [ShortcutRegistry] that this
/// entry was created from.
///
/// This method will assert in debug mode if another [ShortcutRegistryEntry]
/// exists (i.e. hasn't been disposed of) that has already added a given
/// shortcut.
///
/// It will also assert if this entry has already been disposed.
///
/// If two equivalent, but different, [ShortcutActivator]s are added, all of
/// them will be executed when triggered. For example, if both
/// `SingleActivator(LogicalKeyboardKey.keyA)` and `CharacterActivator('a')`
/// are added, then both will be executed when an "a" key is pressed.
void replaceAll(Map<ShortcutActivator, Intent> value) {
registry._replaceAll(this, value);
}
/// Called when the entry is no longer needed.
///
/// Call this will remove all shortcuts associated with this
/// [ShortcutRegistryEntry] from the [registry].
@mustCallSuper
void dispose() {
registry._disposeEntry(this);
}
}
/// A class used by [ShortcutRegistrar] that allows adding or removing shortcut
/// bindings by descendants of the [ShortcutRegistrar].
///
/// You can reach the nearest [ShortcutRegistry] using [of] and [maybeOf].
///
/// The registry may be listened to (with [addListener]/[removeListener]) for
/// change notifications when the registered shortcuts change. Change
/// notifications take place after the current frame is drawn, so that
/// widgets that are not descendants of the registry can listen to it (e.g. in
/// overlays).
class ShortcutRegistry with ChangeNotifier {
/// Creates an instance of [ShortcutRegistry].
ShortcutRegistry() {
if (kFlutterMemoryAllocationsEnabled) {
ChangeNotifier.maybeDispatchObjectCreation(this);
}
}
bool _notificationScheduled = false;
bool _disposed = false;
@override
void dispose() {
super.dispose();
_disposed = true;
}
/// Gets the combined shortcut bindings from all contexts that are registered
/// with this [ShortcutRegistry].
///
/// Listeners will be notified when the value returned by this getter changes.
///
/// Returns a copy: modifying the returned map will have no effect.
Map<ShortcutActivator, Intent> get shortcuts {
assert(ChangeNotifier.debugAssertNotDisposed(this));
return <ShortcutActivator, Intent>{
for (final MapEntry<ShortcutRegistryEntry, Map<ShortcutActivator, Intent>> entry in _registeredShortcuts.entries)
...entry.value,
};
}
final Map<ShortcutRegistryEntry, Map<ShortcutActivator, Intent>> _registeredShortcuts =
<ShortcutRegistryEntry, Map<ShortcutActivator, Intent>>{};
/// Adds all the given shortcut bindings to this [ShortcutRegistry], and
/// returns a entry for managing those bindings.
///
/// The entry should have [ShortcutRegistryEntry.dispose] called on it when
/// these shortcuts are no longer needed. This will remove them from the
/// registry, and invalidate the entry.
///
/// This method will assert in debug mode if another entry exists (i.e. hasn't
/// been disposed of) that has already added a given shortcut.
///
/// If two equivalent, but different, [ShortcutActivator]s are added, all of
/// them will be executed when triggered. For example, if both
/// `SingleActivator(LogicalKeyboardKey.keyA)` and `CharacterActivator('a')`
/// are added, then both will be executed when an "a" key is pressed.
///
/// See also:
///
/// * [ShortcutRegistryEntry.replaceAll], a function used to replace the set of
/// shortcuts associated with a particular entry.
/// * [ShortcutRegistryEntry.dispose], a function used to remove the set of
/// shortcuts associated with a particular entry.
ShortcutRegistryEntry addAll(Map<ShortcutActivator, Intent> value) {
assert(ChangeNotifier.debugAssertNotDisposed(this));
assert(value.isNotEmpty, 'Cannot register an empty map of shortcuts');
final ShortcutRegistryEntry entry = ShortcutRegistryEntry._(this);
_registeredShortcuts[entry] = value;
assert(_debugCheckForDuplicates());
_notifyListenersNextFrame();
return entry;
}
// Subscriber notification has to happen in the next frame because shortcuts
// are often registered that affect things in the overlay or different parts
// of the tree, and so can cause build ordering issues if notifications happen
// during the build. The _notificationScheduled check makes sure we only
// notify once per frame.
void _notifyListenersNextFrame() {
if (!_notificationScheduled) {
SchedulerBinding.instance.addPostFrameCallback((Duration _) {
_notificationScheduled = false;
if (!_disposed) {
notifyListeners();
}
}, debugLabel: 'ShortcutRegistry.notifyListeners');
_notificationScheduled = true;
}
}
/// Returns the [ShortcutRegistry] that belongs to the [ShortcutRegistrar]
/// which most tightly encloses the given [BuildContext].
///
/// If no [ShortcutRegistrar] widget encloses the context given, [of] will
/// throw an exception in debug mode.
///
/// There is a default [ShortcutRegistrar] instance in [WidgetsApp], so if
/// [WidgetsApp], [MaterialApp] or [CupertinoApp] are used, an additional
/// [ShortcutRegistrar] isn't needed.
///
/// See also:
///
/// * [maybeOf], which is similar to this function, but will return null if
/// it doesn't find a [ShortcutRegistrar] ancestor.
static ShortcutRegistry of(BuildContext context) {
final _ShortcutRegistrarScope? inherited =
context.dependOnInheritedWidgetOfExactType<_ShortcutRegistrarScope>();
assert(() {
if (inherited == null) {
throw FlutterError(
'Unable to find a $ShortcutRegistrar widget in the context.\n'
'$ShortcutRegistrar.of() was called with a context that does not contain a '
'$ShortcutRegistrar widget.\n'
'No $ShortcutRegistrar ancestor could be found starting from the context that was '
'passed to $ShortcutRegistrar.of().\n'
'The context used was:\n'
' $context',
);
}
return true;
}());
return inherited!.registry;
}
/// Returns [ShortcutRegistry] of the [ShortcutRegistrar] that most tightly
/// encloses the given [BuildContext].
///
/// If no [ShortcutRegistrar] widget encloses the given context, [maybeOf]
/// will return null.
///
/// There is a default [ShortcutRegistrar] instance in [WidgetsApp], so if
/// [WidgetsApp], [MaterialApp] or [CupertinoApp] are used, an additional
/// [ShortcutRegistrar] isn't needed.
///
/// See also:
///
/// * [of], which is similar to this function, but returns a non-nullable
/// result, and will throw an exception if it doesn't find a
/// [ShortcutRegistrar] ancestor.
static ShortcutRegistry? maybeOf(BuildContext context) {
final _ShortcutRegistrarScope? inherited =
context.dependOnInheritedWidgetOfExactType<_ShortcutRegistrarScope>();
return inherited?.registry;
}
// Replaces all the shortcuts associated with the given entry from this
// registry.
void _replaceAll(ShortcutRegistryEntry entry, Map<ShortcutActivator, Intent> value) {
assert(ChangeNotifier.debugAssertNotDisposed(this));
assert(_debugCheckEntryIsValid(entry));
_registeredShortcuts[entry] = value;
assert(_debugCheckForDuplicates());
_notifyListenersNextFrame();
}
// Removes all the shortcuts associated with the given entry from this
// registry.
void _disposeEntry(ShortcutRegistryEntry entry) {
assert(_debugCheckEntryIsValid(entry));
final Map<ShortcutActivator, Intent>? removedShortcut = _registeredShortcuts.remove(entry);
if (removedShortcut != null) {
_notifyListenersNextFrame();
}
}
bool _debugCheckEntryIsValid(ShortcutRegistryEntry entry) {
if (!_registeredShortcuts.containsKey(entry)) {
if (entry.registry == this) {
throw FlutterError('entry ${describeIdentity(entry)} is invalid.\n'
'The entry has already been disposed of. Tokens are not valid after '
'dispose is called on them, and should no longer be used.');
} else {
throw FlutterError('Foreign entry ${describeIdentity(entry)} used.\n'
'This entry was not created by this registry, it was created by '
'${describeIdentity(entry.registry)}, and should be used with that '
'registry instead.');
}
}
return true;
}
bool _debugCheckForDuplicates() {
final Map<ShortcutActivator, ShortcutRegistryEntry?> previous = <ShortcutActivator, ShortcutRegistryEntry?>{};
for (final MapEntry<ShortcutRegistryEntry, Map<ShortcutActivator, Intent>> tokenEntry in _registeredShortcuts.entries) {
for (final ShortcutActivator shortcut in tokenEntry.value.keys) {
if (previous.containsKey(shortcut)) {
throw FlutterError(
'$ShortcutRegistry: Received a duplicate registration for the '
'shortcut $shortcut in ${describeIdentity(tokenEntry.key)} and ${previous[shortcut]}.');
}
previous[shortcut] = tokenEntry.key;
}
}
return true;
}
}
/// A widget that holds a [ShortcutRegistry] which allows descendants to add,
/// remove, or replace shortcuts.
///
/// This widget holds a [ShortcutRegistry] so that its descendants can find it
/// with [ShortcutRegistry.of] or [ShortcutRegistry.maybeOf].
///
/// The registered shortcuts are valid whenever a widget below this one in the
/// hierarchy has focus.
///
/// To add shortcuts to the registry, call [ShortcutRegistry.of] or
/// [ShortcutRegistry.maybeOf] to get the [ShortcutRegistry], and then add them
/// using [ShortcutRegistry.addAll], which will return a [ShortcutRegistryEntry]
/// which must be disposed by calling [ShortcutRegistryEntry.dispose] when the
/// shortcuts are no longer needed.
///
/// To replace or update the shortcuts in the registry, call
/// [ShortcutRegistryEntry.replaceAll].
///
/// To remove previously added shortcuts from the registry, call
/// [ShortcutRegistryEntry.dispose] on the entry returned by
/// [ShortcutRegistry.addAll].
class ShortcutRegistrar extends StatefulWidget {
/// Creates a const [ShortcutRegistrar].
///
/// The [child] parameter is required.
const ShortcutRegistrar({super.key, required this.child});
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
@override
State<ShortcutRegistrar> createState() => _ShortcutRegistrarState();
}
class _ShortcutRegistrarState extends State<ShortcutRegistrar> {
final ShortcutRegistry registry = ShortcutRegistry();
final ShortcutManager manager = ShortcutManager();
@override
void initState() {
super.initState();
registry.addListener(_shortcutsChanged);
}
void _shortcutsChanged() {
// This shouldn't need to update the widget, and avoids calling setState
// during build phase.
manager.shortcuts = registry.shortcuts;
}
@override
void dispose() {
registry.removeListener(_shortcutsChanged);
registry.dispose();
manager.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return _ShortcutRegistrarScope(
registry: registry,
child: Shortcuts.manager(
manager: manager,
child: widget.child,
),
);
}
}
class _ShortcutRegistrarScope extends InheritedWidget {
const _ShortcutRegistrarScope({
required this.registry,
required super.child,
});
final ShortcutRegistry registry;
@override
bool updateShouldNotify(covariant _ShortcutRegistrarScope oldWidget) {
return registry != oldWidget.registry;
}
}
| flutter/packages/flutter/lib/src/widgets/shortcuts.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/shortcuts.dart",
"repo_id": "flutter",
"token_count": 18469
} | 824 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui show TextHeightBehavior;
import 'package:flutter/rendering.dart';
import 'basic.dart';
import 'default_selection_style.dart';
import 'framework.dart';
import 'inherited_theme.dart';
import 'media_query.dart';
import 'selection_container.dart';
// Examples can assume:
// late String _name;
// late BuildContext context;
/// The text style to apply to descendant [Text] widgets which don't have an
/// explicit style.
///
/// {@tool dartpad}
/// This example shows how to use [DefaultTextStyle.merge] to create a default
/// text style that inherits styling information from the current default text
/// style and overrides some properties.
///
/// ** See code in examples/api/lib/widgets/text/text.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [AnimatedDefaultTextStyle], which animates changes in the text style
/// smoothly over a given duration.
/// * [DefaultTextStyleTransition], which takes a provided [Animation] to
/// animate changes in text style smoothly over time.
class DefaultTextStyle extends InheritedTheme {
/// Creates a default text style for the given subtree.
///
/// Consider using [DefaultTextStyle.merge] to inherit styling information
/// from the current default text style for a given [BuildContext].
///
/// The [maxLines] property may be null (and indeed defaults to null), but if
/// it is not null, it must be greater than zero.
const DefaultTextStyle({
super.key,
required this.style,
this.textAlign,
this.softWrap = true,
this.overflow = TextOverflow.clip,
this.maxLines,
this.textWidthBasis = TextWidthBasis.parent,
this.textHeightBehavior,
required super.child,
}) : assert(maxLines == null || maxLines > 0);
/// A const-constructable default text style that provides fallback values.
///
/// Returned from [of] when the given [BuildContext] doesn't have an enclosing default text style.
///
/// This constructor creates a [DefaultTextStyle] with an invalid [child], which
/// means the constructed value cannot be incorporated into the tree.
const DefaultTextStyle.fallback({ super.key })
: style = const TextStyle(),
textAlign = null,
softWrap = true,
maxLines = null,
overflow = TextOverflow.clip,
textWidthBasis = TextWidthBasis.parent,
textHeightBehavior = null,
super(child: const _NullWidget());
/// Creates a default text style that overrides the text styles in scope at
/// this point in the widget tree.
///
/// The given [style] is merged with the [style] from the default text style
/// for the [BuildContext] where the widget is inserted, and any of the other
/// arguments that are not null replace the corresponding properties on that
/// same default text style.
///
/// This constructor cannot be used to override the [maxLines] property of the
/// ancestor with the value null, since null here is used to mean "defer to
/// ancestor". To replace a non-null [maxLines] from an ancestor with the null
/// value (to remove the restriction on number of lines), manually obtain the
/// ambient [DefaultTextStyle] using [DefaultTextStyle.of], then create a new
/// [DefaultTextStyle] using the [DefaultTextStyle.new] constructor directly.
/// See the source below for an example of how to do this (since that's
/// essentially what this constructor does).
static Widget merge({
Key? key,
TextStyle? style,
TextAlign? textAlign,
bool? softWrap,
TextOverflow? overflow,
int? maxLines,
TextWidthBasis? textWidthBasis,
required Widget child,
}) {
return Builder(
builder: (BuildContext context) {
final DefaultTextStyle parent = DefaultTextStyle.of(context);
return DefaultTextStyle(
key: key,
style: parent.style.merge(style),
textAlign: textAlign ?? parent.textAlign,
softWrap: softWrap ?? parent.softWrap,
overflow: overflow ?? parent.overflow,
maxLines: maxLines ?? parent.maxLines,
textWidthBasis: textWidthBasis ?? parent.textWidthBasis,
child: child,
);
},
);
}
/// The text style to apply.
final TextStyle style;
/// How each line of text in the Text widget should be aligned horizontally.
final TextAlign? textAlign;
/// Whether the text should break at soft line breaks.
///
/// If false, the glyphs in the text will be positioned as if there was unlimited horizontal space.
///
/// This also decides the [overflow] property's behavior. If this is true or null,
/// the glyph causing overflow, and those that follow, will not be rendered.
final bool softWrap;
/// How visual overflow should be handled.
///
/// If [softWrap] is true or null, the glyph causing overflow, and those that follow,
/// will not be rendered. Otherwise, it will be shown with the given overflow option.
final TextOverflow overflow;
/// An optional maximum number of lines for the text to span, wrapping if necessary.
/// If the text exceeds the given number of lines, it will be truncated according
/// to [overflow].
///
/// If this is 1, text will not wrap. Otherwise, text will be wrapped at the
/// edge of the box.
///
/// If this is non-null, it will override even explicit null values of
/// [Text.maxLines].
final int? maxLines;
/// The strategy to use when calculating the width of the Text.
///
/// See [TextWidthBasis] for possible values and their implications.
final TextWidthBasis textWidthBasis;
/// {@macro dart.ui.textHeightBehavior}
final ui.TextHeightBehavior? textHeightBehavior;
/// The closest instance of this class that encloses the given context.
///
/// If no such instance exists, returns an instance created by
/// [DefaultTextStyle.fallback], which contains fallback values.
///
/// Typical usage is as follows:
///
/// ```dart
/// DefaultTextStyle style = DefaultTextStyle.of(context);
/// ```
static DefaultTextStyle of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<DefaultTextStyle>() ?? const DefaultTextStyle.fallback();
}
@override
bool updateShouldNotify(DefaultTextStyle oldWidget) {
return style != oldWidget.style ||
textAlign != oldWidget.textAlign ||
softWrap != oldWidget.softWrap ||
overflow != oldWidget.overflow ||
maxLines != oldWidget.maxLines ||
textWidthBasis != oldWidget.textWidthBasis ||
textHeightBehavior != oldWidget.textHeightBehavior;
}
@override
Widget wrap(BuildContext context, Widget child) {
return DefaultTextStyle(
style: style,
textAlign: textAlign,
softWrap: softWrap,
overflow: overflow,
maxLines: maxLines,
textWidthBasis: textWidthBasis,
textHeightBehavior: textHeightBehavior,
child: child,
);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
style.debugFillProperties(properties);
properties.add(EnumProperty<TextAlign>('textAlign', textAlign, defaultValue: null));
properties.add(FlagProperty('softWrap', value: softWrap, ifTrue: 'wrapping at box width', ifFalse: 'no wrapping except at line break characters', showName: true));
properties.add(EnumProperty<TextOverflow>('overflow', overflow, defaultValue: null));
properties.add(IntProperty('maxLines', maxLines, defaultValue: null));
properties.add(EnumProperty<TextWidthBasis>('textWidthBasis', textWidthBasis, defaultValue: TextWidthBasis.parent));
properties.add(DiagnosticsProperty<ui.TextHeightBehavior>('textHeightBehavior', textHeightBehavior, defaultValue: null));
}
}
class _NullWidget extends StatelessWidget {
const _NullWidget();
@override
Widget build(BuildContext context) {
throw FlutterError(
'A DefaultTextStyle constructed with DefaultTextStyle.fallback cannot be incorporated into the widget tree, '
'it is meant only to provide a fallback value returned by DefaultTextStyle.of() '
'when no enclosing default text style is present in a BuildContext.',
);
}
}
/// The [TextHeightBehavior] that will apply to descendant [Text] and [EditableText]
/// widgets which have not explicitly set [Text.textHeightBehavior].
///
/// If there is a [DefaultTextStyle] with a non-null [DefaultTextStyle.textHeightBehavior]
/// below this widget, the [DefaultTextStyle.textHeightBehavior] will be used
/// over this widget's [TextHeightBehavior].
///
/// See also:
///
/// * [DefaultTextStyle], which defines a [TextStyle] to apply to descendant
/// [Text] widgets.
class DefaultTextHeightBehavior extends InheritedTheme {
/// Creates a default text height behavior for the given subtree.
const DefaultTextHeightBehavior({
super.key,
required this.textHeightBehavior,
required super.child,
});
/// {@macro dart.ui.textHeightBehavior}
final TextHeightBehavior textHeightBehavior;
/// The closest instance of [DefaultTextHeightBehavior] that encloses the
/// given context, or null if none is found.
///
/// If no such instance exists, this method will return `null`.
///
/// Calling this method will create a dependency on the closest
/// [DefaultTextHeightBehavior] in the [context], if there is one.
///
/// Typical usage is as follows:
///
/// ```dart
/// TextHeightBehavior? defaultTextHeightBehavior = DefaultTextHeightBehavior.of(context);
/// ```
///
/// See also:
///
/// * [DefaultTextHeightBehavior.maybeOf], which is similar to this method,
/// but asserts if no [DefaultTextHeightBehavior] ancestor is found.
static TextHeightBehavior? maybeOf(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<DefaultTextHeightBehavior>()?.textHeightBehavior;
}
/// The closest instance of [DefaultTextHeightBehavior] that encloses the
/// given context.
///
/// If no such instance exists, this method will assert in debug mode, and
/// throw an exception in release mode.
///
/// Typical usage is as follows:
///
/// ```dart
/// TextHeightBehavior defaultTextHeightBehavior = DefaultTextHeightBehavior.of(context);
/// ```
///
/// Calling this method will create a dependency on the closest
/// [DefaultTextHeightBehavior] in the [context].
///
/// See also:
///
/// * [DefaultTextHeightBehavior.maybeOf], which is similar to this method,
/// but returns null if no [DefaultTextHeightBehavior] ancestor is found.
static TextHeightBehavior of(BuildContext context) {
final TextHeightBehavior? behavior = maybeOf(context);
assert(() {
if (behavior == null) {
throw FlutterError(
'DefaultTextHeightBehavior.of() was called with a context that does not contain a '
'DefaultTextHeightBehavior widget.\n'
'No DefaultTextHeightBehavior widget ancestor could be found starting from the '
'context that was passed to DefaultTextHeightBehavior.of(). This can happen '
'because you are using a widget that looks for a DefaultTextHeightBehavior '
'ancestor, but no such ancestor exists.\n'
'The context used was:\n'
' $context',
);
}
return true;
}());
return behavior!;
}
@override
bool updateShouldNotify(DefaultTextHeightBehavior oldWidget) {
return textHeightBehavior != oldWidget.textHeightBehavior;
}
@override
Widget wrap(BuildContext context, Widget child) {
return DefaultTextHeightBehavior(
textHeightBehavior: textHeightBehavior,
child: child,
);
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<ui.TextHeightBehavior>('textHeightBehavior', textHeightBehavior, defaultValue: null));
}
}
/// A run of text with a single style.
///
/// The [Text] widget displays a string of text with single style. The string
/// might break across multiple lines or might all be displayed on the same line
/// depending on the layout constraints.
///
/// The [style] argument is optional. When omitted, the text will use the style
/// from the closest enclosing [DefaultTextStyle]. If the given style's
/// [TextStyle.inherit] property is true (the default), the given style will
/// be merged with the closest enclosing [DefaultTextStyle]. This merging
/// behavior is useful, for example, to make the text bold while using the
/// default font family and size.
///
/// {@tool snippet}
///
/// This example shows how to display text using the [Text] widget with the
/// [overflow] set to [TextOverflow.ellipsis].
///
/// 
///
/// ```dart
/// Container(
/// width: 100,
/// decoration: BoxDecoration(border: Border.all()),
/// child: Text(overflow: TextOverflow.ellipsis, 'Hello $_name, how are you?'))
/// ```
/// {@end-tool}
///
/// {@tool snippet}
///
/// Setting [maxLines] to `1` is not equivalent to disabling soft wrapping with
/// [softWrap]. This is apparent when using [TextOverflow.fade] as the following
/// examples show.
///
/// 
///
/// ```dart
/// Text(
/// overflow: TextOverflow.fade,
/// maxLines: 1,
/// 'Hello $_name, how are you?')
/// ```
///
/// Here soft wrapping is enabled and the [Text] widget tries to wrap the words
/// "how are you?" to a second line. This is prevented by the [maxLines] value
/// of `1`. The result is that a second line overflows and the fade appears in a
/// horizontal direction at the bottom.
///
/// 
///
/// ```dart
/// Text(
/// overflow: TextOverflow.fade,
/// softWrap: false,
/// 'Hello $_name, how are you?')
/// ```
///
/// Here soft wrapping is disabled with `softWrap: false` and the [Text] widget
/// attempts to display its text in a single unbroken line. The result is that
/// the single line overflows and the fade appears in a vertical direction at
/// the right.
///
/// {@end-tool}
///
/// Using the [Text.rich] constructor, the [Text] widget can
/// display a paragraph with differently styled [TextSpan]s. The sample
/// that follows displays "Hello beautiful world" with different styles
/// for each word.
///
/// {@tool snippet}
///
/// 
///
/// ```dart
/// const Text.rich(
/// TextSpan(
/// text: 'Hello', // default text style
/// children: <TextSpan>[
/// TextSpan(text: ' beautiful ', style: TextStyle(fontStyle: FontStyle.italic)),
/// TextSpan(text: 'world', style: TextStyle(fontWeight: FontWeight.bold)),
/// ],
/// ),
/// )
/// ```
/// {@end-tool}
///
/// ## Interactivity
///
/// To make [Text] react to touch events, wrap it in a [GestureDetector] widget
/// with a [GestureDetector.onTap] handler.
///
/// In a Material Design application, consider using a [TextButton] instead, or
/// if that isn't appropriate, at least using an [InkWell] instead of
/// [GestureDetector].
///
/// To make sections of the text interactive, use [RichText] and specify a
/// [TapGestureRecognizer] as the [TextSpan.recognizer] of the relevant part of
/// the text.
///
/// ## Selection
///
/// [Text] is not selectable by default. To make a [Text] selectable, one can
/// wrap a subtree with a [SelectionArea] widget. To exclude a part of a subtree
/// under [SelectionArea] from selection, once can also wrap that part of the
/// subtree with [SelectionContainer.disabled].
///
/// {@tool dartpad}
/// This sample demonstrates how to disable selection for a Text under a
/// SelectionArea.
///
/// ** See code in examples/api/lib/material/selection_container/selection_container_disabled.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [RichText], which gives you more control over the text styles.
/// * [DefaultTextStyle], which sets default styles for [Text] widgets.
/// * [SelectableRegion], which provides an overview of the selection system.
class Text extends StatelessWidget {
/// Creates a text widget.
///
/// If the [style] argument is null, the text will use the style from the
/// closest enclosing [DefaultTextStyle].
///
/// The [overflow] property's behavior is affected by the [softWrap] argument.
/// If the [softWrap] is true or null, the glyph causing overflow, and those
/// that follow, will not be rendered. Otherwise, it will be shown with the
/// given overflow option.
const Text(
String this.data, {
super.key,
this.style,
this.strutStyle,
this.textAlign,
this.textDirection,
this.locale,
this.softWrap,
this.overflow,
@Deprecated(
'Use textScaler instead. '
'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. '
'This feature was deprecated after v3.12.0-2.0.pre.',
)
this.textScaleFactor,
this.textScaler,
this.maxLines,
this.semanticsLabel,
this.textWidthBasis,
this.textHeightBehavior,
this.selectionColor,
}) : textSpan = null,
assert(
textScaler == null || textScaleFactor == null,
'textScaleFactor is deprecated and cannot be specified when textScaler is specified.',
);
/// Creates a text widget with a [InlineSpan].
///
/// The following subclasses of [InlineSpan] may be used to build rich text:
///
/// * [TextSpan]s define text and children [InlineSpan]s.
/// * [WidgetSpan]s define embedded inline widgets.
///
/// See [RichText] which provides a lower-level way to draw text.
const Text.rich(
InlineSpan this.textSpan, {
super.key,
this.style,
this.strutStyle,
this.textAlign,
this.textDirection,
this.locale,
this.softWrap,
this.overflow,
@Deprecated(
'Use textScaler instead. '
'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. '
'This feature was deprecated after v3.12.0-2.0.pre.',
)
this.textScaleFactor,
this.textScaler,
this.maxLines,
this.semanticsLabel,
this.textWidthBasis,
this.textHeightBehavior,
this.selectionColor,
}) : data = null,
assert(
textScaler == null || textScaleFactor == null,
'textScaleFactor is deprecated and cannot be specified when textScaler is specified.',
);
/// The text to display.
///
/// This will be null if a [textSpan] is provided instead.
final String? data;
/// The text to display as a [InlineSpan].
///
/// This will be null if [data] is provided instead.
final InlineSpan? textSpan;
/// If non-null, the style to use for this text.
///
/// If the style's "inherit" property is true, the style will be merged with
/// the closest enclosing [DefaultTextStyle]. Otherwise, the style will
/// replace the closest enclosing [DefaultTextStyle].
final TextStyle? style;
/// {@macro flutter.painting.textPainter.strutStyle}
final StrutStyle? strutStyle;
/// How the text should be aligned horizontally.
final TextAlign? textAlign;
/// The directionality of the text.
///
/// This decides how [textAlign] values like [TextAlign.start] and
/// [TextAlign.end] are interpreted.
///
/// This is also used to disambiguate how to render bidirectional text. For
/// example, if the [data] is an English phrase followed by a Hebrew phrase,
/// in a [TextDirection.ltr] context the English phrase will be on the left
/// and the Hebrew phrase to its right, while in a [TextDirection.rtl]
/// context, the English phrase will be on the right and the Hebrew phrase on
/// its left.
///
/// Defaults to the ambient [Directionality], if any.
final TextDirection? textDirection;
/// Used to select a font when the same Unicode character can
/// be rendered differently, depending on the locale.
///
/// It's rarely necessary to set this property. By default its value
/// is inherited from the enclosing app with `Localizations.localeOf(context)`.
///
/// See [RenderParagraph.locale] for more information.
final Locale? locale;
/// Whether the text should break at soft line breaks.
///
/// If false, the glyphs in the text will be positioned as if there was unlimited horizontal space.
final bool? softWrap;
/// How visual overflow should be handled.
///
/// If this is null [TextStyle.overflow] will be used, otherwise the value
/// from the nearest [DefaultTextStyle] ancestor will be used.
final TextOverflow? overflow;
/// Deprecated. Will be removed in a future version of Flutter. Use
/// [textScaler] instead.
///
/// The number of font pixels for each logical pixel.
///
/// For example, if the text scale factor is 1.5, text will be 50% larger than
/// the specified font size.
///
/// The value given to the constructor as textScaleFactor. If null, will
/// use the [MediaQueryData.textScaleFactor] obtained from the ambient
/// [MediaQuery], or 1.0 if there is no [MediaQuery] in scope.
@Deprecated(
'Use textScaler instead. '
'Use of textScaleFactor was deprecated in preparation for the upcoming nonlinear text scaling support. '
'This feature was deprecated after v3.12.0-2.0.pre.',
)
final double? textScaleFactor;
/// {@macro flutter.painting.textPainter.textScaler}
final TextScaler? textScaler;
/// An optional maximum number of lines for the text to span, wrapping if necessary.
/// If the text exceeds the given number of lines, it will be truncated according
/// to [overflow].
///
/// If this is 1, text will not wrap. Otherwise, text will be wrapped at the
/// edge of the box.
///
/// If this is null, but there is an ambient [DefaultTextStyle] that specifies
/// an explicit number for its [DefaultTextStyle.maxLines], then the
/// [DefaultTextStyle] value will take precedence. You can use a [RichText]
/// widget directly to entirely override the [DefaultTextStyle].
final int? maxLines;
/// {@template flutter.widgets.Text.semanticsLabel}
/// An alternative semantics label for this text.
///
/// If present, the semantics of this widget will contain this value instead
/// of the actual text. This will overwrite any of the semantics labels applied
/// directly to the [TextSpan]s.
///
/// This is useful for replacing abbreviations or shorthands with the full
/// text value:
///
/// ```dart
/// const Text(r'$$', semanticsLabel: 'Double dollars')
/// ```
/// {@endtemplate}
final String? semanticsLabel;
/// {@macro flutter.painting.textPainter.textWidthBasis}
final TextWidthBasis? textWidthBasis;
/// {@macro dart.ui.textHeightBehavior}
final ui.TextHeightBehavior? textHeightBehavior;
/// The color to use when painting the selection.
///
/// This is ignored if [SelectionContainer.maybeOf] returns null
/// in the [BuildContext] of the [Text] widget.
///
/// If null, the ambient [DefaultSelectionStyle] is used (if any); failing
/// that, the selection color defaults to [DefaultSelectionStyle.defaultColor]
/// (semi-transparent grey).
final Color? selectionColor;
@override
Widget build(BuildContext context) {
final DefaultTextStyle defaultTextStyle = DefaultTextStyle.of(context);
TextStyle? effectiveTextStyle = style;
if (style == null || style!.inherit) {
effectiveTextStyle = defaultTextStyle.style.merge(style);
}
if (MediaQuery.boldTextOf(context)) {
effectiveTextStyle = effectiveTextStyle!.merge(const TextStyle(fontWeight: FontWeight.bold));
}
final SelectionRegistrar? registrar = SelectionContainer.maybeOf(context);
final TextScaler textScaler = switch ((this.textScaler, textScaleFactor)) {
(final TextScaler textScaler, _) => textScaler,
// For unmigrated apps, fall back to textScaleFactor.
(null, final double textScaleFactor) => TextScaler.linear(textScaleFactor),
(null, null) => MediaQuery.textScalerOf(context),
};
Widget result = RichText(
textAlign: textAlign ?? defaultTextStyle.textAlign ?? TextAlign.start,
textDirection: textDirection, // RichText uses Directionality.of to obtain a default if this is null.
locale: locale, // RichText uses Localizations.localeOf to obtain a default if this is null
softWrap: softWrap ?? defaultTextStyle.softWrap,
overflow: overflow ?? effectiveTextStyle?.overflow ?? defaultTextStyle.overflow,
textScaler: textScaler,
maxLines: maxLines ?? defaultTextStyle.maxLines,
strutStyle: strutStyle,
textWidthBasis: textWidthBasis ?? defaultTextStyle.textWidthBasis,
textHeightBehavior: textHeightBehavior ?? defaultTextStyle.textHeightBehavior ?? DefaultTextHeightBehavior.maybeOf(context),
selectionRegistrar: registrar,
selectionColor: selectionColor ?? DefaultSelectionStyle.of(context).selectionColor ?? DefaultSelectionStyle.defaultColor,
text: TextSpan(
style: effectiveTextStyle,
text: data,
children: textSpan != null ? <InlineSpan>[textSpan!] : null,
),
);
if (registrar != null) {
result = MouseRegion(
cursor: DefaultSelectionStyle.of(context).mouseCursor ?? SystemMouseCursors.text,
child: result,
);
}
if (semanticsLabel != null) {
result = Semantics(
textDirection: textDirection,
label: semanticsLabel,
child: ExcludeSemantics(
child: result,
),
);
}
return result;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(StringProperty('data', data, showName: false));
if (textSpan != null) {
properties.add(textSpan!.toDiagnosticsNode(name: 'textSpan', style: DiagnosticsTreeStyle.transition));
}
style?.debugFillProperties(properties);
properties.add(EnumProperty<TextAlign>('textAlign', textAlign, defaultValue: null));
properties.add(EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null));
properties.add(DiagnosticsProperty<Locale>('locale', locale, defaultValue: null));
properties.add(FlagProperty('softWrap', value: softWrap, ifTrue: 'wrapping at box width', ifFalse: 'no wrapping except at line break characters', showName: true));
properties.add(EnumProperty<TextOverflow>('overflow', overflow, defaultValue: null));
properties.add(DoubleProperty('textScaleFactor', textScaleFactor, defaultValue: null));
properties.add(IntProperty('maxLines', maxLines, defaultValue: null));
properties.add(EnumProperty<TextWidthBasis>('textWidthBasis', textWidthBasis, defaultValue: null));
properties.add(DiagnosticsProperty<ui.TextHeightBehavior>('textHeightBehavior', textHeightBehavior, defaultValue: null));
if (semanticsLabel != null) {
properties.add(StringProperty('semanticsLabel', semanticsLabel));
}
}
}
| flutter/packages/flutter/lib/src/widgets/text.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/text.dart",
"repo_id": "flutter",
"token_count": 8629
} | 825 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/rendering.dart';
import 'basic.dart';
import 'debug.dart';
import 'framework.dart';
import 'scroll_notification.dart';
export 'package:flutter/rendering.dart' show
AxisDirection,
GrowthDirection;
/// A widget through which a portion of larger content can be viewed, typically
/// in combination with a [Scrollable].
///
/// [Viewport] is the visual workhorse of the scrolling machinery. It displays a
/// subset of its children according to its own dimensions and the given
/// [offset]. As the offset varies, different children are visible through
/// the viewport.
///
/// [Viewport] hosts a bidirectional list of slivers, anchored on a [center]
/// sliver, which is placed at the zero scroll offset. The center widget is
/// displayed in the viewport according to the [anchor] property.
///
/// Slivers that are earlier in the child list than [center] are displayed in
/// reverse order in the reverse [axisDirection] starting from the [center]. For
/// example, if the [axisDirection] is [AxisDirection.down], the first sliver
/// before [center] is placed above the [center]. The slivers that are later in
/// the child list than [center] are placed in order in the [axisDirection]. For
/// example, in the preceding scenario, the first sliver after [center] is
/// placed below the [center].
///
/// [Viewport] cannot contain box children directly. Instead, use a
/// [SliverList], [SliverFixedExtentList], [SliverGrid], or a
/// [SliverToBoxAdapter], for example.
///
/// See also:
///
/// * [ListView], [PageView], [GridView], and [CustomScrollView], which combine
/// [Scrollable] and [Viewport] into widgets that are easier to use.
/// * [SliverToBoxAdapter], which allows a box widget to be placed inside a
/// sliver context (the opposite of this widget).
/// * [ShrinkWrappingViewport], a variant of [Viewport] that shrink-wraps its
/// contents along the main axis.
/// * [ViewportElementMixin], which should be mixed in to the [Element] type used
/// by viewport-like widgets to correctly handle scroll notifications.
class Viewport extends MultiChildRenderObjectWidget {
/// Creates a widget that is bigger on the inside.
///
/// The viewport listens to the [offset], which means you do not need to
/// rebuild this widget when the [offset] changes.
///
/// The [cacheExtent] must be specified if the [cacheExtentStyle] is
/// not [CacheExtentStyle.pixel].
Viewport({
super.key,
this.axisDirection = AxisDirection.down,
this.crossAxisDirection,
this.anchor = 0.0,
required this.offset,
this.center,
this.cacheExtent,
this.cacheExtentStyle = CacheExtentStyle.pixel,
this.clipBehavior = Clip.hardEdge,
List<Widget> slivers = const <Widget>[],
}) : assert(center == null || slivers.where((Widget child) => child.key == center).length == 1),
assert(cacheExtentStyle != CacheExtentStyle.viewport || cacheExtent != null),
super(children: slivers);
/// The direction in which the [offset]'s [ViewportOffset.pixels] increases.
///
/// For example, if the [axisDirection] is [AxisDirection.down], a scroll
/// offset of zero is at the top of the viewport and increases towards the
/// bottom of the viewport.
final AxisDirection axisDirection;
/// The direction in which child should be laid out in the cross axis.
///
/// If the [axisDirection] is [AxisDirection.down] or [AxisDirection.up], this
/// property defaults to [AxisDirection.left] if the ambient [Directionality]
/// is [TextDirection.rtl] and [AxisDirection.right] if the ambient
/// [Directionality] is [TextDirection.ltr].
///
/// If the [axisDirection] is [AxisDirection.left] or [AxisDirection.right],
/// this property defaults to [AxisDirection.down].
final AxisDirection? crossAxisDirection;
/// The relative position of the zero scroll offset.
///
/// For example, if [anchor] is 0.5 and the [axisDirection] is
/// [AxisDirection.down] or [AxisDirection.up], then the zero scroll offset is
/// vertically centered within the viewport. If the [anchor] is 1.0, and the
/// [axisDirection] is [AxisDirection.right], then the zero scroll offset is
/// on the left edge of the viewport.
///
/// {@macro flutter.rendering.GrowthDirection.sample}
final double anchor;
/// Which part of the content inside the viewport should be visible.
///
/// The [ViewportOffset.pixels] value determines the scroll offset that the
/// viewport uses to select which part of its content to display. As the user
/// scrolls the viewport, this value changes, which changes the content that
/// is displayed.
///
/// Typically a [ScrollPosition].
final ViewportOffset offset;
/// The first child in the [GrowthDirection.forward] growth direction.
///
/// Children after [center] will be placed in the [axisDirection] relative to
/// the [center]. Children before [center] will be placed in the opposite of
/// the [axisDirection] relative to the [center].
///
/// The [center] must be the key of a child of the viewport.
///
/// {@macro flutter.rendering.GrowthDirection.sample}
final Key? center;
/// {@macro flutter.rendering.RenderViewportBase.cacheExtent}
///
/// See also:
///
/// * [cacheExtentStyle], which controls the units of the [cacheExtent].
final double? cacheExtent;
/// {@macro flutter.rendering.RenderViewportBase.cacheExtentStyle}
final CacheExtentStyle cacheExtentStyle;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.hardEdge].
final Clip clipBehavior;
/// Given a [BuildContext] and an [AxisDirection], determine the correct cross
/// axis direction.
///
/// This depends on the [Directionality] if the `axisDirection` is vertical;
/// otherwise, the default cross axis direction is downwards.
static AxisDirection getDefaultCrossAxisDirection(BuildContext context, AxisDirection axisDirection) {
switch (axisDirection) {
case AxisDirection.up:
assert(debugCheckHasDirectionality(
context,
why: "to determine the cross-axis direction when the viewport has an 'up' axisDirection",
alternative: "Alternatively, consider specifying the 'crossAxisDirection' argument on the Viewport.",
));
return textDirectionToAxisDirection(Directionality.of(context));
case AxisDirection.right:
return AxisDirection.down;
case AxisDirection.down:
assert(debugCheckHasDirectionality(
context,
why: "to determine the cross-axis direction when the viewport has a 'down' axisDirection",
alternative: "Alternatively, consider specifying the 'crossAxisDirection' argument on the Viewport.",
));
return textDirectionToAxisDirection(Directionality.of(context));
case AxisDirection.left:
return AxisDirection.down;
}
}
@override
RenderViewport createRenderObject(BuildContext context) {
return RenderViewport(
axisDirection: axisDirection,
crossAxisDirection: crossAxisDirection ?? Viewport.getDefaultCrossAxisDirection(context, axisDirection),
anchor: anchor,
offset: offset,
cacheExtent: cacheExtent,
cacheExtentStyle: cacheExtentStyle,
clipBehavior: clipBehavior,
);
}
@override
void updateRenderObject(BuildContext context, RenderViewport renderObject) {
renderObject
..axisDirection = axisDirection
..crossAxisDirection = crossAxisDirection ?? Viewport.getDefaultCrossAxisDirection(context, axisDirection)
..anchor = anchor
..offset = offset
..cacheExtent = cacheExtent
..cacheExtentStyle = cacheExtentStyle
..clipBehavior = clipBehavior;
}
@override
MultiChildRenderObjectElement createElement() => _ViewportElement(this);
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(EnumProperty<AxisDirection>('axisDirection', axisDirection));
properties.add(EnumProperty<AxisDirection>('crossAxisDirection', crossAxisDirection, defaultValue: null));
properties.add(DoubleProperty('anchor', anchor));
properties.add(DiagnosticsProperty<ViewportOffset>('offset', offset));
if (center != null) {
properties.add(DiagnosticsProperty<Key>('center', center));
} else if (children.isNotEmpty && children.first.key != null) {
properties.add(DiagnosticsProperty<Key>('center', children.first.key, tooltip: 'implicit'));
}
properties.add(DiagnosticsProperty<double>('cacheExtent', cacheExtent));
properties.add(DiagnosticsProperty<CacheExtentStyle>('cacheExtentStyle', cacheExtentStyle));
}
}
class _ViewportElement extends MultiChildRenderObjectElement with NotifiableElementMixin, ViewportElementMixin {
/// Creates an element that uses the given widget as its configuration.
_ViewportElement(Viewport super.widget);
bool _doingMountOrUpdate = false;
int? _centerSlotIndex;
@override
RenderViewport get renderObject => super.renderObject as RenderViewport;
@override
void mount(Element? parent, Object? newSlot) {
assert(!_doingMountOrUpdate);
_doingMountOrUpdate = true;
super.mount(parent, newSlot);
_updateCenter();
assert(_doingMountOrUpdate);
_doingMountOrUpdate = false;
}
@override
void update(MultiChildRenderObjectWidget newWidget) {
assert(!_doingMountOrUpdate);
_doingMountOrUpdate = true;
super.update(newWidget);
_updateCenter();
assert(_doingMountOrUpdate);
_doingMountOrUpdate = false;
}
void _updateCenter() {
// TODO(ianh): cache the keys to make this faster
final Viewport viewport = widget as Viewport;
if (viewport.center != null) {
int elementIndex = 0;
for (final Element e in children) {
if (e.widget.key == viewport.center) {
renderObject.center = e.renderObject as RenderSliver?;
break;
}
elementIndex++;
}
assert(elementIndex < children.length);
_centerSlotIndex = elementIndex;
} else if (children.isNotEmpty) {
renderObject.center = children.first.renderObject as RenderSliver?;
_centerSlotIndex = 0;
} else {
renderObject.center = null;
_centerSlotIndex = null;
}
}
@override
void insertRenderObjectChild(RenderObject child, IndexedSlot<Element?> slot) {
super.insertRenderObjectChild(child, slot);
// Once [mount]/[update] are done, the `renderObject.center` will be updated
// in [_updateCenter].
if (!_doingMountOrUpdate && slot.index == _centerSlotIndex) {
renderObject.center = child as RenderSliver?;
}
}
@override
void moveRenderObjectChild(RenderObject child, IndexedSlot<Element?> oldSlot, IndexedSlot<Element?> newSlot) {
super.moveRenderObjectChild(child, oldSlot, newSlot);
assert(_doingMountOrUpdate);
}
@override
void removeRenderObjectChild(RenderObject child, Object? slot) {
super.removeRenderObjectChild(child, slot);
if (!_doingMountOrUpdate && renderObject.center == child) {
renderObject.center = null;
}
}
@override
void debugVisitOnstageChildren(ElementVisitor visitor) {
children.where((Element e) {
final RenderSliver renderSliver = e.renderObject! as RenderSliver;
return renderSliver.geometry!.visible;
}).forEach(visitor);
}
}
/// A widget that is bigger on the inside and shrink wraps its children in the
/// main axis.
///
/// [ShrinkWrappingViewport] displays a subset of its children according to its
/// own dimensions and the given [offset]. As the offset varies, different
/// children are visible through the viewport.
///
/// [ShrinkWrappingViewport] differs from [Viewport] in that [Viewport] expands
/// to fill the main axis whereas [ShrinkWrappingViewport] sizes itself to match
/// its children in the main axis. This shrink wrapping behavior is expensive
/// because the children, and hence the viewport, could potentially change size
/// whenever the [offset] changes (e.g., because of a collapsing header).
///
/// [ShrinkWrappingViewport] cannot contain box children directly. Instead, use
/// a [SliverList], [SliverFixedExtentList], [SliverGrid], or a
/// [SliverToBoxAdapter], for example.
///
/// See also:
///
/// * [ListView], [PageView], [GridView], and [CustomScrollView], which combine
/// [Scrollable] and [ShrinkWrappingViewport] into widgets that are easier to
/// use.
/// * [SliverToBoxAdapter], which allows a box widget to be placed inside a
/// sliver context (the opposite of this widget).
/// * [Viewport], a viewport that does not shrink-wrap its contents.
class ShrinkWrappingViewport extends MultiChildRenderObjectWidget {
/// Creates a widget that is bigger on the inside and shrink wraps its
/// children in the main axis.
///
/// The viewport listens to the [offset], which means you do not need to
/// rebuild this widget when the [offset] changes.
const ShrinkWrappingViewport({
super.key,
this.axisDirection = AxisDirection.down,
this.crossAxisDirection,
required this.offset,
this.clipBehavior = Clip.hardEdge,
List<Widget> slivers = const <Widget>[],
}) : super(children: slivers);
/// The direction in which the [offset]'s [ViewportOffset.pixels] increases.
///
/// For example, if the [axisDirection] is [AxisDirection.down], a scroll
/// offset of zero is at the top of the viewport and increases towards the
/// bottom of the viewport.
final AxisDirection axisDirection;
/// The direction in which child should be laid out in the cross axis.
///
/// If the [axisDirection] is [AxisDirection.down] or [AxisDirection.up], this
/// property defaults to [AxisDirection.left] if the ambient [Directionality]
/// is [TextDirection.rtl] and [AxisDirection.right] if the ambient
/// [Directionality] is [TextDirection.ltr].
///
/// If the [axisDirection] is [AxisDirection.left] or [AxisDirection.right],
/// this property defaults to [AxisDirection.down].
final AxisDirection? crossAxisDirection;
/// Which part of the content inside the viewport should be visible.
///
/// The [ViewportOffset.pixels] value determines the scroll offset that the
/// viewport uses to select which part of its content to display. As the user
/// scrolls the viewport, this value changes, which changes the content that
/// is displayed.
///
/// Typically a [ScrollPosition].
final ViewportOffset offset;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.hardEdge].
final Clip clipBehavior;
@override
RenderShrinkWrappingViewport createRenderObject(BuildContext context) {
return RenderShrinkWrappingViewport(
axisDirection: axisDirection,
crossAxisDirection: crossAxisDirection ?? Viewport.getDefaultCrossAxisDirection(context, axisDirection),
offset: offset,
clipBehavior: clipBehavior,
);
}
@override
void updateRenderObject(BuildContext context, RenderShrinkWrappingViewport renderObject) {
renderObject
..axisDirection = axisDirection
..crossAxisDirection = crossAxisDirection ?? Viewport.getDefaultCrossAxisDirection(context, axisDirection)
..offset = offset
..clipBehavior = clipBehavior;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(EnumProperty<AxisDirection>('axisDirection', axisDirection));
properties.add(EnumProperty<AxisDirection>('crossAxisDirection', crossAxisDirection, defaultValue: null));
properties.add(DiagnosticsProperty<ViewportOffset>('offset', offset));
}
}
| flutter/packages/flutter/lib/src/widgets/viewport.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/viewport.dart",
"repo_id": "flutter",
"token_count": 4947
} | 826 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/animation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('copyWith, ==, hashCode basics', () {
expect(AnimationStyle(), AnimationStyle().copyWith());
expect(AnimationStyle().hashCode, AnimationStyle().copyWith().hashCode);
});
testWidgets('AnimationStyle.copyWith() overrides all properties', (WidgetTester tester) async {
final AnimationStyle original = AnimationStyle(
curve: Curves.ease,
duration: const Duration(seconds: 1),
reverseCurve: Curves.ease,
reverseDuration: const Duration(seconds: 1),
);
final AnimationStyle copy = original.copyWith(
curve: Curves.linear,
duration: const Duration(seconds: 2),
reverseCurve: Curves.linear,
reverseDuration: const Duration(seconds: 2),
);
expect(copy.curve, Curves.linear);
expect(copy.duration, const Duration(seconds: 2));
expect(copy.reverseCurve, Curves.linear);
expect(copy.reverseDuration, const Duration(seconds: 2));
});
test('AnimationStyle.lerp identical a,b', () {
expect(AnimationStyle.lerp(null, null, 0), null);
final AnimationStyle data = AnimationStyle();
expect(identical(AnimationStyle.lerp(data, data, 0.5), data), true);
});
testWidgets('default AnimationStyle debugFillProperties', (WidgetTester tester) async {
final AnimationStyle a = AnimationStyle(
curve: Curves.ease,
duration: const Duration(seconds: 1),
reverseCurve: Curves.ease,
reverseDuration: const Duration(seconds: 1),
);
final AnimationStyle b = AnimationStyle(
curve: Curves.linear,
duration: const Duration(seconds: 2),
reverseCurve: Curves.linear,
reverseDuration: const Duration(seconds: 2),
);
expect(AnimationStyle.lerp(a, b, 0), a);
expect(AnimationStyle.lerp(a, b, 0.5), b);
expect(AnimationStyle.lerp(a, b, 1.0), b);
});
testWidgets('default AnimationStyle debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
AnimationStyle().debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString()).toList();
expect(description, <String>[]);
});
testWidgets('AnimationStyle implements debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
AnimationStyle(
curve: Curves.easeInOut,
duration: const Duration(seconds: 1),
reverseCurve: Curves.bounceInOut,
reverseDuration: const Duration(seconds: 2),
).debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString()).toList();
expect(description, <String>[
'curve: Cubic(0.42, 0.00, 0.58, 1.00)',
'duration: 0:00:01.000000',
'reverseCurve: _BounceInOutCurve',
'reverseDuration: 0:00:02.000000'
]);
});
}
| flutter/packages/flutter/test/animation/animation_style_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/animation/animation_style_test.dart",
"repo_id": "flutter",
"token_count": 1167
} | 827 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
class DependentWidget extends StatelessWidget {
const DependentWidget({
super.key,
required this.color,
});
final Color color;
@override
Widget build(BuildContext context) {
final Color resolved = CupertinoDynamicColor.resolve(color, context);
return DecoratedBox(
decoration: BoxDecoration(color: resolved),
child: const SizedBox.expand(),
);
}
}
const Color color0 = Color(0xFF000000);
const Color color1 = Color(0xFF000001);
const Color color2 = Color(0xFF000002);
const Color color3 = Color(0xFF000003);
const Color color4 = Color(0xFF000004);
const Color color5 = Color(0xFF000005);
const Color color6 = Color(0xFF000006);
const Color color7 = Color(0xFF000007);
// A color that depends on color vibrancy, accessibility contrast, as well as user
// interface elevation.
const CupertinoDynamicColor dynamicColor = CupertinoDynamicColor(
color: color0,
darkColor: color1,
elevatedColor: color2,
highContrastColor: color3,
darkElevatedColor: color4,
darkHighContrastColor: color5,
highContrastElevatedColor: color6,
darkHighContrastElevatedColor: color7,
);
// A color that uses [color0] in every circumstance.
const Color notSoDynamicColor1 = CupertinoDynamicColor(
color: color0,
darkColor: color0,
darkHighContrastColor: color0,
darkElevatedColor: color0,
darkHighContrastElevatedColor: color0,
highContrastColor: color0,
highContrastElevatedColor: color0,
elevatedColor: color0,
);
// A color that uses [color1] for light mode, and [color0] for dark mode.
const Color vibrancyDependentColor1 = CupertinoDynamicColor(
color: color1,
elevatedColor: color1,
highContrastColor: color1,
highContrastElevatedColor: color1,
darkColor: color0,
darkHighContrastColor: color0,
darkElevatedColor: color0,
darkHighContrastElevatedColor: color0,
);
// A color that uses [color1] for normal contrast mode, and [color0] for high
// contrast mode.
const Color contrastDependentColor1 = CupertinoDynamicColor(
color: color1,
darkColor: color1,
elevatedColor: color1,
darkElevatedColor: color1,
highContrastColor: color0,
darkHighContrastColor: color0,
highContrastElevatedColor: color0,
darkHighContrastElevatedColor: color0,
);
// A color that uses [color1] for base interface elevation, and [color0] for elevated
// interface elevation.
const Color elevationDependentColor1 = CupertinoDynamicColor(
color: color1,
darkColor: color1,
highContrastColor: color1,
darkHighContrastColor: color1,
elevatedColor: color0,
darkElevatedColor: color0,
highContrastElevatedColor: color0,
darkHighContrastElevatedColor: color0,
);
void main() {
test('== works as expected', () {
expect(dynamicColor, const CupertinoDynamicColor(
color: color0,
darkColor: color1,
elevatedColor: color2,
highContrastColor: color3,
darkElevatedColor: color4,
darkHighContrastColor: color5,
highContrastElevatedColor: color6,
darkHighContrastElevatedColor: color7,
),
);
expect(notSoDynamicColor1, isNot(vibrancyDependentColor1));
expect(notSoDynamicColor1, isNot(contrastDependentColor1));
expect(vibrancyDependentColor1, isNot(const CupertinoDynamicColor(
color: color0,
elevatedColor: color0,
highContrastColor: color0,
highContrastElevatedColor: color0,
darkColor: color0,
darkHighContrastColor: color0,
darkElevatedColor: color0,
darkHighContrastElevatedColor: color0,
)));
});
test('CupertinoDynamicColor.toString() works', () {
expect(
dynamicColor.toString(),
contains(
'CupertinoDynamicColor(*color = Color(0xff000000)*, '
'darkColor = Color(0xff000001), '
'highContrastColor = Color(0xff000003), '
'darkHighContrastColor = Color(0xff000005), '
'elevatedColor = Color(0xff000002), '
'darkElevatedColor = Color(0xff000004), '
'highContrastElevatedColor = Color(0xff000006), '
'darkHighContrastElevatedColor = Color(0xff000007)',
),
);
expect(notSoDynamicColor1.toString(), contains('CupertinoDynamicColor(*color = Color(0xff000000)*'));
expect(vibrancyDependentColor1.toString(), contains('CupertinoDynamicColor(*color = Color(0xff000001)*, darkColor = Color(0xff000000)'));
expect(contrastDependentColor1.toString(), contains('CupertinoDynamicColor(*color = Color(0xff000001)*, highContrastColor = Color(0xff000000)'));
expect(elevationDependentColor1.toString(), contains('CupertinoDynamicColor(*color = Color(0xff000001)*, elevatedColor = Color(0xff000000)'));
expect(
const CupertinoDynamicColor.withBrightnessAndContrast(
color: color0,
darkColor: color1,
highContrastColor: color2,
darkHighContrastColor: color3,
).toString(),
contains(
'CupertinoDynamicColor(*color = Color(0xff000000)*, '
'darkColor = Color(0xff000001), '
'highContrastColor = Color(0xff000002), '
'darkHighContrastColor = Color(0xff000003)',
),
);
});
test('can resolve null color', () {
expect(CupertinoDynamicColor.maybeResolve(null, _NullElement.instance), isNull);
});
test('withVibrancy constructor creates colors that may depend on vibrancy', () {
expect(vibrancyDependentColor1, const CupertinoDynamicColor.withBrightness(
color: color1,
darkColor: color0,
));
});
test('withVibrancyAndContrast constructor creates colors that may depend on contrast and vibrancy', () {
expect(contrastDependentColor1, const CupertinoDynamicColor.withBrightnessAndContrast(
color: color1,
darkColor: color1,
highContrastColor: color0,
darkHighContrastColor: color0,
));
expect(
const CupertinoDynamicColor(
color: color0,
darkColor: color1,
highContrastColor: color2,
darkHighContrastColor: color3,
elevatedColor: color0,
darkElevatedColor: color1,
highContrastElevatedColor: color2,
darkHighContrastElevatedColor: color3,
),
const CupertinoDynamicColor.withBrightnessAndContrast(
color: color0,
darkColor: color1,
highContrastColor: color2,
darkHighContrastColor: color3,
),
);
});
testWidgets(
'Dynamic colors that are not actually dynamic should not claim dependencies',
(WidgetTester tester) async {
await tester.pumpWidget(const DependentWidget(color: notSoDynamicColor1));
expect(tester.takeException(), null);
expect(find.byType(DependentWidget), paints..rect(color: color0));
},
);
testWidgets(
'Dynamic colors that are only dependent on vibrancy should not claim unnecessary dependencies, '
'and its resolved color should change when its dependency changes',
(WidgetTester tester) async {
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(),
child: DependentWidget(color: vibrancyDependentColor1),
),
);
expect(tester.takeException(), null);
expect(find.byType(DependentWidget), paints..rect(color: color1));
expect(find.byType(DependentWidget), isNot(paints..rect(color: color0)));
// Changing color vibrancy works.
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(platformBrightness: Brightness.dark),
child: DependentWidget(color: vibrancyDependentColor1),
),
);
expect(tester.takeException(), null);
expect(find.byType(DependentWidget), paints..rect(color: color0));
expect(find.byType(DependentWidget), isNot(paints..rect(color: color1)));
// CupertinoTheme should take precedence over MediaQuery.
await tester.pumpWidget(
const CupertinoTheme(
data: CupertinoThemeData(brightness: Brightness.light),
child: MediaQuery(
data: MediaQueryData(platformBrightness: Brightness.dark),
child: DependentWidget(color: vibrancyDependentColor1),
),
),
);
expect(tester.takeException(), null);
expect(find.byType(DependentWidget), paints..rect(color: color1));
expect(find.byType(DependentWidget), isNot(paints..rect(color: color0)));
},
);
testWidgets(
'Dynamic colors that are only dependent on accessibility contrast should not claim unnecessary dependencies, '
'and its resolved color should change when its dependency changes',
(WidgetTester tester) async {
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(),
child: DependentWidget(color: contrastDependentColor1),
),
);
expect(tester.takeException(), null);
expect(find.byType(DependentWidget), paints..rect(color: color1));
expect(find.byType(DependentWidget), isNot(paints..rect(color: color0)));
// Changing accessibility contrast works.
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(highContrast: true),
child: DependentWidget(color: contrastDependentColor1),
),
);
expect(tester.takeException(), null);
expect(find.byType(DependentWidget), paints..rect(color: color0));
expect(find.byType(DependentWidget), isNot(paints..rect(color: color1)));
},
);
testWidgets(
'Dynamic colors that are only dependent on elevation level should not claim unnecessary dependencies, '
'and its resolved color should change when its dependency changes',
(WidgetTester tester) async {
await tester.pumpWidget(
const CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.base,
child: DependentWidget(color: elevationDependentColor1),
),
);
expect(tester.takeException(), null);
expect(find.byType(DependentWidget), paints..rect(color: color1));
expect(find.byType(DependentWidget), isNot(paints..rect(color: color0)));
// Changing UI elevation works.
await tester.pumpWidget(
const CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.elevated,
child: DependentWidget(color: elevationDependentColor1),
),
);
expect(tester.takeException(), null);
expect(find.byType(DependentWidget), paints..rect(color: color0));
expect(find.byType(DependentWidget), isNot(paints..rect(color: color1)));
},
);
testWidgets('Dynamic color with all 3 dependencies works', (WidgetTester tester) async {
const Color dynamicRainbowColor1 = CupertinoDynamicColor(
color: color0,
darkColor: color1,
highContrastColor: color2,
darkHighContrastColor: color3,
darkElevatedColor: color4,
highContrastElevatedColor: color5,
darkHighContrastElevatedColor: color6,
elevatedColor: color7,
);
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(),
child: CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.base,
child: DependentWidget(color: dynamicRainbowColor1),
),
),
);
expect(find.byType(DependentWidget), paints..rect(color: color0));
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(platformBrightness: Brightness.dark),
child: CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.base,
child: DependentWidget(color: dynamicRainbowColor1),
),
),
);
expect(find.byType(DependentWidget), paints..rect(color: color1));
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(highContrast: true),
child: CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.base,
child: DependentWidget(color: dynamicRainbowColor1),
),
),
);
expect(find.byType(DependentWidget), paints..rect(color: color2));
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(platformBrightness: Brightness.dark, highContrast: true),
child: CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.base,
child: DependentWidget(color: dynamicRainbowColor1),
),
),
);
expect(find.byType(DependentWidget), paints..rect(color: color3));
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(platformBrightness: Brightness.dark),
child: CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.elevated,
child: DependentWidget(color: dynamicRainbowColor1),
),
),
);
expect(find.byType(DependentWidget), paints..rect(color: color4));
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(highContrast: true),
child: CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.elevated,
child: DependentWidget(color: dynamicRainbowColor1),
),
),
);
expect(find.byType(DependentWidget), paints..rect(color: color5));
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(platformBrightness: Brightness.dark, highContrast: true),
child: CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.elevated,
child: DependentWidget(color: dynamicRainbowColor1),
),
),
);
expect(find.byType(DependentWidget), paints..rect(color: color6));
await tester.pumpWidget(
const MediaQuery(
data: MediaQueryData(),
child: CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.elevated,
child: DependentWidget(color: dynamicRainbowColor1),
),
),
);
expect(find.byType(DependentWidget), paints..rect(color: color7));
});
testWidgets('CupertinoDynamicColor used in a CupertinoTheme', (WidgetTester tester) async {
late CupertinoDynamicColor color;
await tester.pumpWidget(
CupertinoApp(
theme: const CupertinoThemeData(
brightness: Brightness.dark,
primaryColor: dynamicColor,
),
home: Builder(
builder: (BuildContext context) {
color = CupertinoTheme.of(context).primaryColor as CupertinoDynamicColor;
return const Placeholder();
},
),
),
);
expect(color.value, dynamicColor.darkColor.value);
// Changing dependencies works.
await tester.pumpWidget(
CupertinoApp(
theme: const CupertinoThemeData(
brightness: Brightness.light,
primaryColor: dynamicColor,
),
home: Builder(
builder: (BuildContext context) {
color = CupertinoTheme.of(context).primaryColor as CupertinoDynamicColor;
return const Placeholder();
},
),
),
);
expect(color.value, dynamicColor.color.value);
// Having a dependency below the CupertinoTheme widget works.
await tester.pumpWidget(
CupertinoApp(
theme: const CupertinoThemeData(primaryColor: dynamicColor),
home: MediaQuery(
data: const MediaQueryData(),
child: CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.base,
child: Builder(
builder: (BuildContext context) {
color = CupertinoTheme.of(context).primaryColor as CupertinoDynamicColor;
return const Placeholder();
},
),
),
),
),
);
expect(color.value, dynamicColor.color.value);
// Changing dependencies works.
await tester.pumpWidget(
CupertinoApp(
// No brightness is explicitly specified here so it should defer to MediaQuery.
theme: const CupertinoThemeData(primaryColor: dynamicColor),
home: MediaQuery(
data: const MediaQueryData(platformBrightness: Brightness.dark, highContrast: true),
child: CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.elevated,
child: Builder(
builder: (BuildContext context) {
color = CupertinoTheme.of(context).primaryColor as CupertinoDynamicColor;
return const Placeholder();
},
),
),
),
),
);
expect(color.value, dynamicColor.darkHighContrastElevatedColor.value);
});
group('MaterialApp:', () {
Color? color;
setUp(() { color = null; });
testWidgets('dynamic color works in cupertino override theme', (WidgetTester tester) async {
CupertinoDynamicColor typedColor() => color! as CupertinoDynamicColor;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
cupertinoOverrideTheme: const CupertinoThemeData(
brightness: Brightness.dark,
primaryColor: dynamicColor,
),
),
home: MediaQuery(
data: const MediaQueryData(),
child: CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.base,
child: Builder(
builder: (BuildContext context) {
color = CupertinoTheme.of(context).primaryColor;
return const Placeholder();
},
),
),
),
),
);
// Explicit brightness is respected.
expect(typedColor().value, dynamicColor.darkColor.value);
color = null;
// Changing dependencies works.
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
cupertinoOverrideTheme: const CupertinoThemeData(
brightness: Brightness.dark,
primaryColor: dynamicColor,
),
),
home: MediaQuery(
data: const MediaQueryData(platformBrightness: Brightness.dark, highContrast: true),
child: CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.elevated,
child: Builder(
builder: (BuildContext context) {
color = CupertinoTheme.of(context).primaryColor;
return const Placeholder();
},
),
),
),
),
);
expect(typedColor().value, dynamicColor.darkHighContrastElevatedColor.value);
});
testWidgets('dynamic color does not work in a material theme', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
// This will create a MaterialBasedCupertinoThemeData with primaryColor set to `dynamicColor`.
theme: ThemeData(colorScheme: const ColorScheme.dark(primary: dynamicColor)),
home: MediaQuery(
data: const MediaQueryData(platformBrightness: Brightness.dark, highContrast: true),
child: CupertinoUserInterfaceLevel(
data: CupertinoUserInterfaceLevelData.elevated,
child: Builder(
builder: (BuildContext context) {
color = CupertinoTheme.of(context).primaryColor;
return const Placeholder();
},
),
),
),
),
);
// The color is not resolved.
expect(color, dynamicColor);
expect(color, isNot(dynamicColor.darkHighContrastElevatedColor));
});
});
}
class _NullElement extends Element {
_NullElement() : super(const _NullWidget());
static _NullElement instance = _NullElement();
@override
bool get debugDoingBuild => throw UnimplementedError();
}
class _NullWidget extends Widget {
const _NullWidget();
@override
Element createElement() => throw UnimplementedError();
}
| flutter/packages/flutter/test/cupertino/colors_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/cupertino/colors_test.dart",
"repo_id": "flutter",
"token_count": 7992
} | 828 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import '../../image_data.dart';
late List<int> selectedTabs;
void main() {
setUp(() {
selectedTabs = <int>[];
});
testWidgets('Last tab gets focus', (WidgetTester tester) async {
// 2 nodes for 2 tabs
final List<FocusNode> focusNodes = <FocusNode>[];
for (int i = 0; i < 2; i++) {
final FocusNode focusNode = FocusNode();
focusNodes.add(focusNode);
addTearDown(focusNode.dispose);
}
await tester.pumpWidget(
MaterialApp(
home: Material(
child: CupertinoTabScaffold(
tabBar: _buildTabBar(),
tabBuilder: (BuildContext context, int index) {
return TextField(
focusNode: focusNodes[index],
autofocus: true,
);
},
),
),
),
);
expect(focusNodes[0].hasFocus, isTrue);
await tester.tap(find.text('Tab 2'));
await tester.pump();
expect(focusNodes[0].hasFocus, isFalse);
expect(focusNodes[1].hasFocus, isTrue);
await tester.tap(find.text('Tab 1'));
await tester.pump();
expect(focusNodes[0].hasFocus, isTrue);
expect(focusNodes[1].hasFocus, isFalse);
});
testWidgets('Do not affect focus order in the route', (WidgetTester tester) async {
final List<FocusNode> focusNodes = <FocusNode>[];
for (int i = 0; i < 4; i++) {
final FocusNode focusNode = FocusNode();
focusNodes.add(focusNode);
addTearDown(focusNode.dispose);
}
await tester.pumpWidget(
MaterialApp(
home: Material(
child: CupertinoTabScaffold(
tabBar: _buildTabBar(),
tabBuilder: (BuildContext context, int index) {
return Column(
children: <Widget>[
TextField(
focusNode: focusNodes[index * 2],
decoration: const InputDecoration(
hintText: 'TextField 1',
),
),
TextField(
focusNode: focusNodes[index * 2 + 1],
decoration: const InputDecoration(
hintText: 'TextField 2',
),
),
],
);
},
),
),
),
);
expect(
focusNodes.any((FocusNode node) => node.hasFocus),
isFalse,
);
await tester.tap(find.widgetWithText(TextField, 'TextField 2'));
expect(
focusNodes.indexOf(focusNodes.singleWhere((FocusNode node) => node.hasFocus)),
1,
);
await tester.tap(find.text('Tab 2'));
await tester.pump();
await tester.tap(find.widgetWithText(TextField, 'TextField 1'));
expect(
focusNodes.indexOf(focusNodes.singleWhere((FocusNode node) => node.hasFocus)),
2,
);
await tester.tap(find.text('Tab 1'));
await tester.pump();
// Upon going back to tab 1, the item it tab 1 that previously had the focus
// (TextField 2) gets it back.
expect(
focusNodes.indexOf(focusNodes.singleWhere((FocusNode node) => node.hasFocus)),
1,
);
});
testWidgets('Tab bar respects themes', (WidgetTester tester) async {
await tester.pumpWidget(
CupertinoApp(
home: CupertinoTabScaffold(
tabBar: _buildTabBar(),
tabBuilder: (BuildContext context, int index) {
return const Placeholder();
},
),
),
);
BoxDecoration tabDecoration = tester.widget<DecoratedBox>(find.descendant(
of: find.byType(CupertinoTabBar),
matching: find.byType(DecoratedBox),
)).decoration as BoxDecoration;
expect(tabDecoration.color, isSameColorAs(const Color(0xF0F9F9F9))); // Inherited from theme.
await tester.tap(find.text('Tab 2'));
await tester.pump();
// Pump again but with dark theme.
await tester.pumpWidget(
CupertinoApp(
theme: const CupertinoThemeData(
brightness: Brightness.dark,
primaryColor: CupertinoColors.destructiveRed,
),
home: CupertinoTabScaffold(
tabBar: _buildTabBar(),
tabBuilder: (BuildContext context, int index) {
return const Placeholder();
},
),
),
);
tabDecoration = tester.widget<DecoratedBox>(find.descendant(
of: find.byType(CupertinoTabBar),
matching: find.byType(DecoratedBox),
)).decoration as BoxDecoration;
expect(tabDecoration.color, isSameColorAs(const Color(0xF01D1D1D)));
final RichText tab1 = tester.widget(find.descendant(
of: find.text('Tab 1'),
matching: find.byType(RichText),
));
// Tab 2 should still be selected after changing theme.
expect(tab1.text.style!.color!.value, 0xFF757575);
final RichText tab2 = tester.widget(find.descendant(
of: find.text('Tab 2'),
matching: find.byType(RichText),
));
expect(tab2.text.style!.color!.value, CupertinoColors.systemRed.darkColor.value);
});
testWidgets('dark mode background color', (WidgetTester tester) async {
const CupertinoDynamicColor backgroundColor = CupertinoDynamicColor.withBrightness(
color: Color(0xFF123456),
darkColor: Color(0xFF654321),
);
await tester.pumpWidget(
CupertinoApp(
theme: const CupertinoThemeData(brightness: Brightness.light),
home: CupertinoTabScaffold(
backgroundColor: backgroundColor,
tabBar: _buildTabBar(),
tabBuilder: (BuildContext context, int index) {
return const Placeholder();
},
),
),
);
// The DecoratedBox with the smallest depth is the DecoratedBox of the
// CupertinoTabScaffold.
BoxDecoration tabDecoration = tester.firstWidget<DecoratedBox>(
find.descendant(
of: find.byType(CupertinoTabScaffold),
matching: find.byType(DecoratedBox),
),
).decoration as BoxDecoration;
expect(tabDecoration.color!.value, backgroundColor.color.value);
// Dark mode
await tester.pumpWidget(
CupertinoApp(
theme: const CupertinoThemeData(brightness: Brightness.dark),
home: CupertinoTabScaffold(
backgroundColor: backgroundColor,
tabBar: _buildTabBar(),
tabBuilder: (BuildContext context, int index) {
return const Placeholder();
},
),
),
);
tabDecoration = tester.firstWidget<DecoratedBox>(
find.descendant(
of: find.byType(CupertinoTabScaffold),
matching: find.byType(DecoratedBox),
),
).decoration as BoxDecoration;
expect(tabDecoration.color!.value, backgroundColor.darkColor.value);
});
testWidgets('Does not lose state when focusing on text input', (WidgetTester tester) async {
// Regression testing for https://github.com/flutter/flutter/issues/28457.
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(),
child: MaterialApp(
home: Material(
child: CupertinoTabScaffold(
tabBar: _buildTabBar(),
tabBuilder: (BuildContext context, int index) {
return const TextField();
},
),
),
),
),
);
final EditableTextState editableState = tester.state<EditableTextState>(find.byType(EditableText));
await tester.enterText(find.byType(TextField), "don't lose me");
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
viewInsets: EdgeInsets.only(bottom: 100),
),
child: MaterialApp(
home: Material(
child: CupertinoTabScaffold(
tabBar: _buildTabBar(),
tabBuilder: (BuildContext context, int index) {
return const TextField();
},
),
),
),
),
);
// The exact same state instance is still there.
expect(tester.state<EditableTextState>(find.byType(EditableText)), editableState);
expect(find.text("don't lose me"), findsOneWidget);
});
testWidgets('textScaleFactor is set to 1.0', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Builder(builder: (BuildContext context) {
return MediaQuery.withClampedTextScaling(
minScaleFactor: 99,
maxScaleFactor: 99,
child: CupertinoTabScaffold(
tabBar: CupertinoTabBar(
items: List<BottomNavigationBarItem>.generate(
10,
(int i) => BottomNavigationBarItem(icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: '$i'),
),
),
tabBuilder: (BuildContext context, int index) => const Text('content'),
),
);
}),
),
);
final Iterable<RichText> barItems = tester.widgetList<RichText>(
find.descendant(
of: find.byType(CupertinoTabBar),
matching: find.byType(RichText),
),
);
final Iterable<RichText> contents = tester.widgetList<RichText>(
find.descendant(
of: find.text('content'),
matching: find.byType(RichText),
skipOffstage: false,
),
);
expect(barItems.length, greaterThan(0));
expect(barItems, isNot(contains(predicate((RichText t) => t.textScaler != TextScaler.noScaling))));
expect(contents.length, greaterThan(0));
expect(contents, isNot(contains(predicate((RichText t) => t.textScaler != const TextScaler.linear(99.0)))));
});
}
CupertinoTabBar _buildTabBar({ int selectedTab = 0 }) {
return CupertinoTabBar(
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))),
label: 'Tab 1',
),
BottomNavigationBarItem(
icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))),
label: 'Tab 2',
),
],
currentIndex: selectedTab,
onTap: (int newTab) => selectedTabs.add(newTab),
);
}
| flutter/packages/flutter/test/cupertino/material/tab_scaffold_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/cupertino/material/tab_scaffold_test.dart",
"repo_id": "flutter",
"token_count": 4623
} | 829 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set'])
library;
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Switch can toggle on tap', (WidgetTester tester) async {
final Key switchKey = UniqueKey();
bool value = false;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: CupertinoSwitch(
key: switchKey,
value: value,
dragStartBehavior: DragStartBehavior.down,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
);
},
),
),
);
expect(value, isFalse);
await tester.tap(find.byKey(switchKey));
expect(value, isTrue);
});
testWidgets('CupertinoSwitch can be toggled by keyboard shortcuts', (WidgetTester tester) async {
bool value = true;
Widget buildApp({bool enabled = true}) {
return CupertinoApp(
home: CupertinoPageScaffold(
child: Center(
child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) {
return CupertinoSwitch(
value: value,
onChanged: enabled ? (bool newValue) {
setState(() {
value = newValue;
});
} : null,
);
}),
),
),
);
}
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(value, isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pumpAndSettle();
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
expect(value, isFalse);
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pumpAndSettle();
expect(value, isTrue);
});
testWidgets('Switch emits light haptic vibration on tap', (WidgetTester tester) async {
final Key switchKey = UniqueKey();
bool value = false;
final List<MethodCall> log = <MethodCall>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async {
log.add(methodCall);
return null;
});
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: CupertinoSwitch(
key: switchKey,
value: value,
dragStartBehavior: DragStartBehavior.down,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
);
},
),
),
);
await tester.tap(find.byKey(switchKey));
await tester.pump();
expect(log, hasLength(1));
expect(log.single, isMethodCall('HapticFeedback.vibrate', arguments: 'HapticFeedbackType.lightImpact'));
}, variant: TargetPlatformVariant.only(TargetPlatform.iOS));
testWidgets('Using other widgets that rebuild the switch will not cause vibrations', (WidgetTester tester) async {
final Key switchKey = UniqueKey();
final Key switchKey2 = UniqueKey();
bool value = false;
bool value2 = false;
final List<MethodCall> log = <MethodCall>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async {
log.add(methodCall);
return null;
});
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: Column(
children: <Widget>[
CupertinoSwitch(
key: switchKey,
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
CupertinoSwitch(
key: switchKey2,
value: value2,
onChanged: (bool newValue) {
setState(() {
value2 = newValue;
});
},
),
],
),
);
},
),
),
);
await tester.tap(find.byKey(switchKey));
await tester.pump();
expect(log, hasLength(1));
expect(log[0], isMethodCall('HapticFeedback.vibrate', arguments: 'HapticFeedbackType.lightImpact'));
await tester.tap(find.byKey(switchKey2));
await tester.pump();
expect(log, hasLength(2));
expect(log[1], isMethodCall('HapticFeedback.vibrate', arguments: 'HapticFeedbackType.lightImpact'));
await tester.tap(find.byKey(switchKey));
await tester.pump();
expect(log, hasLength(3));
expect(log[2], isMethodCall('HapticFeedback.vibrate', arguments: 'HapticFeedbackType.lightImpact'));
await tester.tap(find.byKey(switchKey2));
await tester.pump();
expect(log, hasLength(4));
expect(log[3], isMethodCall('HapticFeedback.vibrate', arguments: 'HapticFeedbackType.lightImpact'));
}, variant: TargetPlatformVariant.only(TargetPlatform.iOS));
testWidgets('Haptic vibration triggers on drag', (WidgetTester tester) async {
bool value = false;
final List<MethodCall> log = <MethodCall>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async {
log.add(methodCall);
return null;
});
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: CupertinoSwitch(
value: value,
dragStartBehavior: DragStartBehavior.down,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
);
},
),
),
);
await tester.drag(find.byType(CupertinoSwitch), const Offset(30.0, 0.0));
expect(value, isTrue);
await tester.pump();
expect(log, hasLength(1));
expect(log[0], isMethodCall('HapticFeedback.vibrate', arguments: 'HapticFeedbackType.lightImpact'));
}, variant: TargetPlatformVariant.only(TargetPlatform.iOS));
testWidgets('No haptic vibration triggers from a programmatic value change', (WidgetTester tester) async {
final Key switchKey = UniqueKey();
bool value = false;
final List<MethodCall> log = <MethodCall>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async {
log.add(methodCall);
return null;
});
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: Column(
children: <Widget>[
CupertinoButton(
child: const Text('Button'),
onPressed: () {
setState(() {
value = !value;
});
},
),
CupertinoSwitch(
key: switchKey,
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
],
),
);
},
),
),
);
expect(value, isFalse);
await tester.tap(find.byType(CupertinoButton));
expect(value, isTrue);
await tester.pump();
expect(log, hasLength(0));
}, variant: TargetPlatformVariant.only(TargetPlatform.iOS));
testWidgets('Switch can drag (LTR)', (WidgetTester tester) async {
bool value = false;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: CupertinoSwitch(
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
);
},
),
),
);
expect(value, isFalse);
await tester.drag(find.byType(CupertinoSwitch), const Offset(-48.0, 0.0));
expect(value, isFalse);
await tester.drag(find.byType(CupertinoSwitch), const Offset(48.0, 0.0));
expect(value, isTrue);
await tester.pump();
await tester.drag(find.byType(CupertinoSwitch), const Offset(48.0, 0.0));
expect(value, isTrue);
await tester.pump();
await tester.drag(find.byType(CupertinoSwitch), const Offset(-48.0, 0.0));
expect(value, isFalse);
});
testWidgets('Switch can drag with dragStartBehavior', (WidgetTester tester) async {
bool value = false;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: CupertinoSwitch(
value: value,
dragStartBehavior: DragStartBehavior.down,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
);
},
),
),
);
expect(value, isFalse);
await tester.drag(find.byType(CupertinoSwitch), const Offset(-30.0, 0.0));
expect(value, isFalse);
await tester.drag(find.byType(CupertinoSwitch), const Offset(30.0, 0.0));
expect(value, isTrue);
await tester.pump();
await tester.drag(find.byType(CupertinoSwitch), const Offset(30.0, 0.0));
expect(value, isTrue);
await tester.pump();
await tester.drag(find.byType(CupertinoSwitch), const Offset(-30.0, 0.0));
expect(value, isFalse);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: CupertinoSwitch(
value: value,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
);
},
),
),
);
await tester.pumpAndSettle();
final Rect switchRect = tester.getRect(find.byType(CupertinoSwitch));
expect(value, isFalse);
TestGesture gesture = await tester.startGesture(switchRect.center);
// We have to execute the drag in two frames because the first update will
// just set the start position.
await gesture.moveBy(const Offset(20.0, 0.0));
await gesture.moveBy(const Offset(20.0, 0.0));
expect(value, isFalse);
await gesture.up();
expect(value, isTrue);
await tester.pump();
gesture = await tester.startGesture(switchRect.center);
await gesture.moveBy(const Offset(20.0, 0.0));
await gesture.moveBy(const Offset(20.0, 0.0));
expect(value, isTrue);
await gesture.up();
await tester.pump();
gesture = await tester.startGesture(switchRect.center);
await gesture.moveBy(const Offset(-20.0, 0.0));
await gesture.moveBy(const Offset(-20.0, 0.0));
expect(value, isTrue);
await gesture.up();
expect(value, isFalse);
await tester.pump();
});
testWidgets('Switch can drag (RTL)', (WidgetTester tester) async {
bool value = false;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: CupertinoSwitch(
value: value,
dragStartBehavior: DragStartBehavior.down,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
);
},
),
),
);
expect(value, isFalse);
await tester.drag(find.byType(CupertinoSwitch), const Offset(30.0, 0.0));
expect(value, isFalse);
await tester.drag(find.byType(CupertinoSwitch), const Offset(-30.0, 0.0));
expect(value, isTrue);
await tester.pump();
await tester.drag(find.byType(CupertinoSwitch), const Offset(-30.0, 0.0));
expect(value, isTrue);
await tester.pump();
await tester.drag(find.byType(CupertinoSwitch), const Offset(30.0, 0.0));
expect(value, isFalse);
});
testWidgets('can veto switch dragging result', (WidgetTester tester) async {
bool value = false;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Material(
child: Center(
child: CupertinoSwitch(
dragStartBehavior: DragStartBehavior.down,
value: value,
onChanged: (bool newValue) {
setState(() {
value = value || newValue;
});
},
),
),
);
},
),
),
);
// Move a little to the right, not past the middle.
TestGesture gesture = await tester.startGesture(tester.getRect(find.byType(CupertinoSwitch)).center);
await gesture.moveBy(const Offset(kTouchSlop + 0.1, 0.0));
await tester.pump();
await gesture.moveBy(const Offset(-kTouchSlop + 5.1, 0.0));
await tester.pump();
await gesture.up();
await tester.pump();
expect(value, isFalse);
final CurvedAnimation position = (tester.state(find.byType(CupertinoSwitch)) as dynamic).position as CurvedAnimation;
expect(position.value, lessThan(0.5));
await tester.pump();
await tester.pumpAndSettle();
expect(value, isFalse);
expect(position.value, 0);
// Move past the middle.
gesture = await tester.startGesture(tester.getRect(find.byType(CupertinoSwitch)).center);
await gesture.moveBy(const Offset(kTouchSlop + 0.1, 0.0));
await tester.pump();
await gesture.up();
await tester.pump();
expect(value, isTrue);
expect(position.value, greaterThan(0.5));
await tester.pump();
await tester.pumpAndSettle();
expect(value, isTrue);
expect(position.value, 1.0);
// Now move back to the left, the revert animation should play.
gesture = await tester.startGesture(tester.getRect(find.byType(CupertinoSwitch)).center);
await gesture.moveBy(const Offset(-kTouchSlop - 0.1, 0.0));
await tester.pump();
await gesture.up();
await tester.pump();
expect(value, isTrue);
expect(position.value, lessThan(0.5));
await tester.pump();
await tester.pumpAndSettle();
expect(value, isTrue);
expect(position.value, 1.0);
});
testWidgets('Switch is translucent when disabled', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: CupertinoSwitch(
value: false,
dragStartBehavior: DragStartBehavior.down,
onChanged: null,
),
),
),
);
expect(find.byType(Opacity), findsOneWidget);
expect(tester.widget<Opacity>(find.byType(Opacity).first).opacity, 0.5);
});
testWidgets('Switch is using track color when set', (WidgetTester tester) async {
const Color trackColor = Color(0xFF00FF00);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: CupertinoSwitch(
value: false,
trackColor: trackColor,
dragStartBehavior: DragStartBehavior.down,
onChanged: null,
),
),
),
);
expect(find.byType(CupertinoSwitch), findsOneWidget);
expect(tester.widget<CupertinoSwitch>(find.byType(CupertinoSwitch)).trackColor, trackColor);
expect(find.byType(CupertinoSwitch), paints..rrect(color: trackColor));
});
testWidgets('Switch is using default thumb color', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: CupertinoSwitch(
value: false,
onChanged: null,
),
),
),
);
expect(find.byType(CupertinoSwitch), findsOneWidget);
expect(tester.widget<CupertinoSwitch>(find.byType(CupertinoSwitch)).thumbColor, null);
expect(
find.byType(CupertinoSwitch),
paints
..rrect()
..rrect()
..rrect()
..rrect()
..rrect(color: CupertinoColors.white),
);
});
testWidgets('Switch is using thumb color when set', (WidgetTester tester) async {
const Color thumbColor = Color(0xFF000000);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: CupertinoSwitch(
value: false,
thumbColor: thumbColor,
onChanged: null,
),
),
),
);
expect(find.byType(CupertinoSwitch), findsOneWidget);
expect(tester.widget<CupertinoSwitch>(find.byType(CupertinoSwitch)).thumbColor, thumbColor);
expect(
find.byType(CupertinoSwitch),
paints
..rrect()
..rrect()
..rrect()
..rrect()
..rrect(color: thumbColor),
);
});
testWidgets('Switch is opaque when enabled', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: CupertinoSwitch(
value: false,
dragStartBehavior: DragStartBehavior.down,
onChanged: (bool newValue) {},
),
),
),
);
expect(find.byType(Opacity), findsOneWidget);
expect(tester.widget<Opacity>(find.byType(Opacity).first).opacity, 1.0);
});
testWidgets('Switch turns translucent after becoming disabled', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: CupertinoSwitch(
value: false,
dragStartBehavior: DragStartBehavior.down,
onChanged: (bool newValue) {},
),
),
),
);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: CupertinoSwitch(
value: false,
dragStartBehavior: DragStartBehavior.down,
onChanged: null,
),
),
),
);
expect(find.byType(Opacity), findsOneWidget);
expect(tester.widget<Opacity>(find.byType(Opacity).first).opacity, 0.5);
});
testWidgets('Switch turns opaque after becoming enabled', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: CupertinoSwitch(
value: false,
dragStartBehavior: DragStartBehavior.down,
onChanged: null,
),
),
),
);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: CupertinoSwitch(
value: false,
dragStartBehavior: DragStartBehavior.down,
onChanged: (bool newValue) {},
),
),
),
);
expect(find.byType(Opacity), findsOneWidget);
expect(tester.widget<Opacity>(find.byType(Opacity).first).opacity, 1.0);
});
testWidgets('Switch renders correctly before, during, and after being tapped', (WidgetTester tester) async {
final Key switchKey = UniqueKey();
bool value = false;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: RepaintBoundary(
child: CupertinoSwitch(
key: switchKey,
value: value,
dragStartBehavior: DragStartBehavior.down,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
),
);
await expectLater(
find.byKey(switchKey),
matchesGoldenFile('switch.tap.off.png'),
);
await tester.tap(find.byKey(switchKey));
expect(value, isTrue);
// Kick off animation, then advance to intermediate frame.
await tester.pump();
await tester.pump(const Duration(milliseconds: 60));
await expectLater(
find.byKey(switchKey),
matchesGoldenFile('switch.tap.turningOn.png'),
);
await tester.pumpAndSettle();
await expectLater(
find.byKey(switchKey),
matchesGoldenFile('switch.tap.on.png'),
);
});
PaintPattern onLabelPaintPattern({
required int alpha,
bool isRtl = false,
}) =>
paints
..rect(
rect: Rect.fromLTWH(isRtl ? 43.5 : 14.5, 14.5, 1.0, 10.0),
color: const Color(0xffffffff).withAlpha(alpha),
style: PaintingStyle.fill,
);
PaintPattern offLabelPaintPattern({
required int alpha,
bool highContrast = false,
bool isRtl = false,
}) =>
paints
..circle(
x: isRtl ? 16.0 : 43.0,
y: 19.5,
radius: 5.0,
color:
(highContrast ? const Color(0xffffffff) : const Color(0xffb3b3b3))
.withAlpha(alpha),
strokeWidth: 1.0,
style: PaintingStyle.stroke,
);
testWidgets('Switch renders switch labels correctly before, during, and after being tapped', (WidgetTester tester) async {
final Key switchKey = UniqueKey();
bool value = false;
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(onOffSwitchLabels: true),
child: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: RepaintBoundary(
child: CupertinoSwitch(
key: switchKey,
value: value,
dragStartBehavior: DragStartBehavior.down,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
),
),
);
final RenderObject switchRenderObject =
tester.element(find.byType(CupertinoSwitch)).renderObject!;
expect(switchRenderObject, offLabelPaintPattern(alpha: 255));
expect(switchRenderObject, onLabelPaintPattern(alpha: 0));
await tester.tap(find.byKey(switchKey));
expect(value, isTrue);
// Kick off animation, then advance to intermediate frame.
await tester.pump();
await tester.pump(const Duration(milliseconds: 60));
expect(switchRenderObject, onLabelPaintPattern(alpha: 131));
expect(switchRenderObject, offLabelPaintPattern(alpha: 124));
await tester.pumpAndSettle();
expect(switchRenderObject, onLabelPaintPattern(alpha: 255));
expect(switchRenderObject, offLabelPaintPattern(alpha: 0));
});
testWidgets('Switch renders switch labels correctly before, during, and after being tapped in high contrast', (WidgetTester tester) async {
final Key switchKey = UniqueKey();
bool value = false;
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(
onOffSwitchLabels: true,
highContrast: true,
),
child: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: RepaintBoundary(
child: CupertinoSwitch(
key: switchKey,
value: value,
dragStartBehavior: DragStartBehavior.down,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
),
),
);
final RenderObject switchRenderObject =
tester.element(find.byType(CupertinoSwitch)).renderObject!;
expect(switchRenderObject, offLabelPaintPattern(highContrast: true, alpha: 255));
expect(switchRenderObject, onLabelPaintPattern(alpha: 0));
await tester.tap(find.byKey(switchKey));
expect(value, isTrue);
// Kick off animation, then advance to intermediate frame.
await tester.pump();
await tester.pump(const Duration(milliseconds: 60));
expect(switchRenderObject, onLabelPaintPattern(alpha: 131));
expect(switchRenderObject, offLabelPaintPattern(highContrast: true, alpha: 124));
await tester.pumpAndSettle();
expect(switchRenderObject, onLabelPaintPattern(alpha: 255));
expect(switchRenderObject, offLabelPaintPattern(highContrast: true, alpha: 0));
});
testWidgets('Switch renders switch labels correctly before, during, and after being tapped with direction rtl', (WidgetTester tester) async {
final Key switchKey = UniqueKey();
bool value = false;
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(onOffSwitchLabels: true),
child: Directionality(
textDirection: TextDirection.rtl,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: RepaintBoundary(
child: CupertinoSwitch(
key: switchKey,
value: value,
dragStartBehavior: DragStartBehavior.down,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
),
),
);
final RenderObject switchRenderObject =
tester.element(find.byType(CupertinoSwitch)).renderObject!;
expect(switchRenderObject, offLabelPaintPattern(isRtl: true, alpha: 255));
expect(switchRenderObject, onLabelPaintPattern(isRtl: true, alpha: 0));
await tester.tap(find.byKey(switchKey));
expect(value, isTrue);
// Kick off animation, then advance to intermediate frame.
await tester.pump();
await tester.pump(const Duration(milliseconds: 60));
expect(switchRenderObject, onLabelPaintPattern(isRtl: true, alpha: 131));
expect(switchRenderObject, offLabelPaintPattern(isRtl: true, alpha: 124));
await tester.pumpAndSettle();
expect(switchRenderObject, onLabelPaintPattern(isRtl: true, alpha: 255));
expect(switchRenderObject, offLabelPaintPattern(isRtl: true, alpha: 0));
});
testWidgets('Switch renders correctly in dark mode', (WidgetTester tester) async {
final Key switchKey = UniqueKey();
bool value = false;
await tester.pumpWidget(
MediaQuery(
data: const MediaQueryData(platformBrightness: Brightness.dark),
child: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: RepaintBoundary(
child: CupertinoSwitch(
key: switchKey,
value: value,
dragStartBehavior: DragStartBehavior.down,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
),
);
},
),
),
),
);
await expectLater(
find.byKey(switchKey),
matchesGoldenFile('switch.tap.off.dark.png'),
);
await tester.tap(find.byKey(switchKey));
expect(value, isTrue);
await tester.pumpAndSettle();
await expectLater(
find.byKey(switchKey),
matchesGoldenFile('switch.tap.on.dark.png'),
);
});
testWidgets('Switch can apply the ambient theme and be opted out', (WidgetTester tester) async {
final Key switchKey = UniqueKey();
bool value = false;
await tester.pumpWidget(
CupertinoTheme(
data: const CupertinoThemeData(primaryColor: Colors.amber, applyThemeToAll: true),
child: Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: RepaintBoundary(
child: Column(
children: <Widget>[
CupertinoSwitch(
key: switchKey,
value: value,
dragStartBehavior: DragStartBehavior.down,
applyTheme: true,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
CupertinoSwitch(
value: value,
dragStartBehavior: DragStartBehavior.down,
applyTheme: false,
onChanged: (bool newValue) {
setState(() {
value = newValue;
});
},
),
],
),
),
);
},
),
),
),
);
await expectLater(
find.byType(Column),
matchesGoldenFile('switch.tap.off.themed.png'),
);
await tester.tap(find.byKey(switchKey));
expect(value, isTrue);
await tester.pumpAndSettle();
await expectLater(
find.byType(Column),
matchesGoldenFile('switch.tap.on.themed.png'),
);
});
testWidgets('Hovering over Cupertino switch updates cursor to clickable on Web', (WidgetTester tester) async {
const bool value = false;
// Disabled CupertinoSwitch does not update cursor on Web.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return const Center(
child: CupertinoSwitch(
value: value,
dragStartBehavior: DragStartBehavior.down,
onChanged: null,
),
);
},
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
final Offset cupertinoSwitch = tester.getCenter(find.byType(CupertinoSwitch));
await gesture.addPointer(location: cupertinoSwitch);
await tester.pumpAndSettle();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
// Enabled CupertinoSwitch updates cursor when hovering on Web.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: CupertinoSwitch(
value: value,
dragStartBehavior: DragStartBehavior.down,
onChanged: (bool newValue) { },
),
);
},
),
),
);
await gesture.moveTo(const Offset(10, 10));
await tester.pumpAndSettle();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
await gesture.moveTo(cupertinoSwitch);
await tester.pumpAndSettle();
expect(
RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1),
kIsWeb ? SystemMouseCursors.click : SystemMouseCursors.basic,
);
});
testWidgets('CupertinoSwitch is focusable and has correct focus color', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'CupertinoSwitch');
addTearDown(focusNode.dispose);
tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
bool value = true;
const Color focusColor = Color(0xffff0000);
Widget buildApp({bool enabled = true}) {
return Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Center(
child: CupertinoSwitch(
value: value,
onChanged: enabled ? (bool newValue) {
setState(() {
value = newValue;
});
} : null,
focusColor: focusColor,
focusNode: focusNode,
autofocus: true,
),
);
},
),
);
}
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
find.byType(CupertinoSwitch),
paints
..rrect(color: const Color(0xff34c759))
..rrect(color: focusColor)
..clipRRect()
..rrect(color: const Color(0x26000000))
..rrect(color: const Color(0x0f000000))
..rrect(color: const Color(0x0a000000))
..rrect(color: const Color(0xffffffff)),
);
// Check the false value.
value = false;
await tester.pumpWidget(buildApp());
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
expect(
find.byType(CupertinoSwitch),
paints
..rrect(color: const Color(0x28787880))
..rrect(color: focusColor)
..clipRRect()
..rrect(color: const Color(0x26000000))
..rrect(color: const Color(0x0f000000))
..rrect(color: const Color(0x0a000000))
..rrect(color: const Color(0xffffffff)),
);
// Check what happens when disabled.
value = false;
await tester.pumpWidget(buildApp(enabled: false));
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isFalse);
expect(
find.byType(CupertinoSwitch),
paints
..rrect(color: const Color(0x28787880))
..clipRRect()
..rrect(color: const Color(0x26000000))
..rrect(color: const Color(0x0f000000))
..rrect(color: const Color(0x0a000000))
..rrect(color: const Color(0xffffffff)),
);
});
testWidgets('CupertinoSwitch.onFocusChange callback', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'CupertinoSwitch');
addTearDown(focusNode.dispose);
bool focused = false;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: CupertinoSwitch(
value: true,
focusNode: focusNode,
onFocusChange: (bool value) {
focused = value;
},
onChanged:(bool newValue) {},
),
),
),
);
focusNode.requestFocus();
await tester.pump();
expect(focused, isTrue);
expect(focusNode.hasFocus, isTrue);
focusNode.unfocus();
await tester.pump();
expect(focused, isFalse);
expect(focusNode.hasFocus, isFalse);
});
}
| flutter/packages/flutter/test/cupertino/switch_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/cupertino/switch_test.dart",
"repo_id": "flutter",
"token_count": 17689
} | 830 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// A test script that invokes compute() to start an isolate.
import 'package:flutter/src/foundation/_isolates_io.dart';
int getLength(String s) {
throw 10;
}
Future<void> main() async {
const String s = 'hello world';
try {
await compute(getLength, s);
} catch (e) {
if (e != 10) {
throw Exception('compute threw bad result');
}
}
}
| flutter/packages/flutter/test/foundation/_compute_caller_error.dart/0 | {
"file_path": "flutter/packages/flutter/test/foundation/_compute_caller_error.dart",
"repo_id": "flutter",
"token_count": 175
} | 831 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('debugInstrumentAction', () {
late DebugPrintCallback originalDebugPrintCallback;
late StringBuffer printBuffer;
setUp(() {
debugInstrumentationEnabled = true;
printBuffer = StringBuffer();
originalDebugPrintCallback = debugPrint;
debugPrint = (String? message, { int? wrapWidth }) {
printBuffer.writeln(message);
};
});
tearDown(() {
debugInstrumentationEnabled = false;
debugPrint = originalDebugPrintCallback;
});
test('works with non-failing actions', () async {
final int result = await debugInstrumentAction<int>('no-op', () async {
debugPrint('action()');
return 1;
});
expect(result, 1);
expect(
printBuffer.toString(),
matches(RegExp('^action\\(\\)\nAction "no-op" took .+\$', multiLine: true)),
);
});
test('returns failing future if action throws', () async {
await expectLater(
() => debugInstrumentAction<void>('throws', () async {
await Future<void>.delayed(Duration.zero);
throw 'Error';
}),
throwsA('Error'),
);
expect(printBuffer.toString(), matches(r'^Action "throws" took .+'));
});
});
}
| flutter/packages/flutter/test/foundation/debug_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/foundation/debug_test.dart",
"repo_id": "flutter",
"token_count": 567
} | 832 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@TestOn('!chrome')
library;
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
// TODO(ianh): These tests and the filtering mechanism should be revisited to
// account for causal async stack traces. https://github.com/flutter/flutter/issues/8128
test('FlutterError.defaultStackFilter', () {
final List<String> filtered = FlutterError.defaultStackFilter(StackTrace.current.toString().trimRight().split('\n')).toList();
expect(filtered.length, greaterThanOrEqualTo(4));
expect(filtered[0], matches(r'^#0 +main\.<anonymous closure> \(.*stack_trace_test\.dart:[0-9]+:[0-9]+\)$'));
expect(filtered[1], matches(r'^#1 +Declarer\.test\.<anonymous closure>.<anonymous closure> \(package:test_api/.+:[0-9]+:[0-9]+\)$'));
expect(filtered[2], equals('<asynchronous suspension>'));
});
test('FlutterError.defaultStackFilter (async test body)', () async {
final List<String> filtered = FlutterError.defaultStackFilter(StackTrace.current.toString().trimRight().split('\n')).toList();
expect(filtered.length, greaterThanOrEqualTo(3));
expect(filtered[0], matches(r'^#0 +main\.<anonymous closure> \(.*stack_trace_test\.dart:[0-9]+:[0-9]+\)$'));
});
}
| flutter/packages/flutter/test/foundation/stack_trace_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/foundation/stack_trace_test.dart",
"repo_id": "flutter",
"token_count": 480
} | 833 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart';
import 'package:flutter_test/flutter_test.dart';
import 'gesture_tester.dart';
// Down/move/up pair 1: normal tap sequence
const PointerDownEvent down = PointerDownEvent(
pointer: 5,
position: Offset(10, 10),
);
const PointerUpEvent up = PointerUpEvent(
pointer: 5,
position: Offset(11, 9),
);
const PointerMoveEvent move = PointerMoveEvent(
pointer: 5,
position: Offset(100, 200),
);
// Down/up pair 2: normal tap sequence far away from pair 1
const PointerDownEvent down2 = PointerDownEvent(
pointer: 6,
position: Offset(10, 10),
);
const PointerUpEvent up2 = PointerUpEvent(
pointer: 6,
position: Offset(11, 9),
);
// Down/up pair 3: tap sequence with secondary button
const PointerDownEvent down3 = PointerDownEvent(
pointer: 7,
position: Offset(30, 30),
buttons: kSecondaryButton,
);
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
group('Long press', () {
late LongPressGestureRecognizer gesture;
late List<String> recognized;
void setUpHandlers() {
gesture
..onLongPressDown = (LongPressDownDetails details) {
recognized.add('down');
}
..onLongPressCancel = () {
recognized.add('cancel');
}
..onLongPress = () {
recognized.add('start');
}
..onLongPressMoveUpdate = (LongPressMoveUpdateDetails details) {
recognized.add('move');
}
..onLongPressUp = () {
recognized.add('end');
};
}
setUp(() {
recognized = <String>[];
gesture = LongPressGestureRecognizer();
setUpHandlers();
});
testGesture('Should recognize long press', (GestureTester tester) {
gesture.addPointer(down);
tester.closeArena(5);
expect(recognized, const <String>[]);
tester.route(down);
expect(recognized, const <String>['down']);
tester.async.elapse(const Duration(milliseconds: 300));
expect(recognized, const <String>['down']);
tester.async.elapse(const Duration(milliseconds: 700));
expect(recognized, const <String>['down', 'start']);
gesture.dispose();
expect(recognized, const <String>['down', 'start']);
});
testGesture('Should recognize long press with altered duration', (GestureTester tester) {
gesture = LongPressGestureRecognizer(duration: const Duration(milliseconds: 100));
setUpHandlers();
gesture.addPointer(down);
tester.closeArena(5);
expect(recognized, const <String>[]);
tester.route(down);
expect(recognized, const <String>['down']);
tester.async.elapse(const Duration(milliseconds: 50));
expect(recognized, const <String>['down']);
tester.async.elapse(const Duration(milliseconds: 50));
expect(recognized, const <String>['down', 'start']);
gesture.dispose();
expect(recognized, const <String>['down', 'start']);
});
testGesture('Up cancels long press', (GestureTester tester) {
gesture.addPointer(down);
tester.closeArena(5);
expect(recognized, const <String>[]);
tester.route(down);
expect(recognized, const <String>['down']);
tester.async.elapse(const Duration(milliseconds: 300));
expect(recognized, const <String>['down']);
tester.route(up);
expect(recognized, const <String>['down', 'cancel']);
tester.async.elapse(const Duration(seconds: 1));
gesture.dispose();
expect(recognized, const <String>['down', 'cancel']);
});
testGesture('Moving before accept cancels', (GestureTester tester) {
gesture.addPointer(down);
tester.closeArena(5);
expect(recognized, const <String>[]);
tester.route(down);
expect(recognized, const <String>['down']);
tester.async.elapse(const Duration(milliseconds: 300));
expect(recognized, const <String>['down']);
tester.route(move);
expect(recognized, const <String>['down', 'cancel']);
tester.async.elapse(const Duration(seconds: 1));
tester.route(up);
tester.async.elapse(const Duration(milliseconds: 300));
expect(recognized, const <String>['down', 'cancel']);
gesture.dispose();
expect(recognized, const <String>['down', 'cancel']);
});
testGesture('Moving after accept is ok', (GestureTester tester) {
gesture.addPointer(down);
tester.closeArena(5);
expect(recognized, const <String>[]);
tester.route(down);
expect(recognized, const <String>['down']);
tester.async.elapse(const Duration(seconds: 1));
expect(recognized, const <String>['down', 'start']);
tester.route(move);
expect(recognized, const <String>['down', 'start', 'move']);
tester.route(up);
expect(recognized, const <String>['down', 'start', 'move', 'end']);
tester.async.elapse(const Duration(milliseconds: 300));
expect(recognized, const <String>['down', 'start', 'move', 'end']);
gesture.dispose();
expect(recognized, const <String>['down', 'start', 'move', 'end']);
});
testGesture('Should recognize both tap down and long press', (GestureTester tester) {
final TapGestureRecognizer tap = TapGestureRecognizer();
tap.onTapDown = (_) {
recognized.add('tap_down');
};
tap.addPointer(down);
gesture.addPointer(down);
tester.closeArena(5);
expect(recognized, const <String>[]);
tester.route(down);
expect(recognized, const <String>['down']);
tester.async.elapse(const Duration(milliseconds: 300));
expect(recognized, const <String>['down', 'tap_down']);
tester.async.elapse(const Duration(milliseconds: 700));
expect(recognized, const <String>['down', 'tap_down', 'start']);
tap.dispose();
gesture.dispose();
expect(recognized, const <String>['down', 'tap_down', 'start']);
});
testGesture('Drag start delayed by microtask', (GestureTester tester) {
final HorizontalDragGestureRecognizer drag = HorizontalDragGestureRecognizer();
bool isDangerousStack = false;
drag.onStart = (DragStartDetails details) {
expect(isDangerousStack, isFalse);
recognized.add('drag_start');
};
drag.addPointer(down);
gesture.addPointer(down);
tester.closeArena(5);
expect(recognized, const <String>[]);
tester.route(down);
expect(recognized, const <String>['down']);
tester.async.elapse(const Duration(milliseconds: 300));
expect(recognized, const <String>['down']);
isDangerousStack = true;
gesture.dispose();
isDangerousStack = false;
expect(recognized, const <String>['down', 'cancel']);
tester.async.flushMicrotasks();
expect(recognized, const <String>['down', 'cancel', 'drag_start']);
drag.dispose();
});
testGesture('Should recognize long press up', (GestureTester tester) {
gesture.addPointer(down);
tester.closeArena(5);
expect(recognized, const <String>[]);
tester.route(down); // kLongPressTimeout = 500;
expect(recognized, const <String>['down']);
tester.async.elapse(const Duration(milliseconds: 300));
expect(recognized, const <String>['down']);
tester.async.elapse(const Duration(milliseconds: 700));
expect(recognized, const <String>['down', 'start']);
tester.route(up);
expect(recognized, const <String>['down', 'start', 'end']);
gesture.dispose();
expect(recognized, const <String>['down', 'start', 'end']);
});
testGesture('Should not recognize long press with more than one buttons', (GestureTester tester) {
gesture.addPointer(const PointerDownEvent(
pointer: 5,
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton | kTertiaryButton,
position: Offset(10, 10),
));
tester.closeArena(5);
expect(recognized, const <String>[]);
tester.route(down);
expect(recognized, const <String>[]);
tester.async.elapse(const Duration(milliseconds: 1000));
expect(recognized, const <String>[]);
tester.route(up);
expect(recognized, const <String>[]);
gesture.dispose();
expect(recognized, const <String>[]);
});
testGesture('Should cancel long press when buttons change before acceptance', (GestureTester tester) {
gesture.addPointer(down);
tester.closeArena(5);
expect(recognized, const <String>[]);
tester.route(down);
expect(recognized, const <String>['down']);
tester.async.elapse(const Duration(milliseconds: 300));
expect(recognized, const <String>['down']);
tester.route(const PointerMoveEvent(
pointer: 5,
kind: PointerDeviceKind.mouse,
buttons: kTertiaryButton,
position: Offset(10, 10),
));
expect(recognized, const <String>['down', 'cancel']);
tester.async.elapse(const Duration(milliseconds: 700));
expect(recognized, const <String>['down', 'cancel']);
tester.route(up);
expect(recognized, const <String>['down', 'cancel']);
gesture.dispose();
expect(recognized, const <String>['down', 'cancel']);
});
testGesture('non-allowed pointer does not inadvertently reset the recognizer', (GestureTester tester) {
gesture = LongPressGestureRecognizer(
supportedDevices: <PointerDeviceKind>{ PointerDeviceKind.touch },
);
setUpHandlers();
// Accept a long-press gesture
gesture.addPointer(down);
tester.closeArena(5);
tester.route(down);
tester.async.elapse(const Duration(milliseconds: 500));
expect(recognized, const <String>['down', 'start']);
// Add a non-allowed pointer (doesn't match the kind filter)
gesture.addPointer(const PointerDownEvent(
pointer: 101,
kind: PointerDeviceKind.mouse,
position: Offset(10, 10),
));
expect(recognized, const <String>['down', 'start']);
// Moving the primary pointer should result in a normal event
tester.route(const PointerMoveEvent(
pointer: 5,
position: Offset(15, 15),
));
expect(recognized, const <String>['down', 'start', 'move']);
gesture.dispose();
});
});
group('long press drag', () {
late LongPressGestureRecognizer gesture;
Offset? longPressDragUpdate;
late List<String> recognized;
void setUpHandlers() {
gesture
..onLongPressDown = (LongPressDownDetails details) {
recognized.add('down');
}
..onLongPressCancel = () {
recognized.add('cancel');
}
..onLongPress = () {
recognized.add('start');
}
..onLongPressMoveUpdate = (LongPressMoveUpdateDetails details) {
recognized.add('move');
longPressDragUpdate = details.globalPosition;
}
..onLongPressUp = () {
recognized.add('end');
};
}
setUp(() {
gesture = LongPressGestureRecognizer();
setUpHandlers();
recognized = <String>[];
});
testGesture('Should recognize long press down', (GestureTester tester) {
gesture.addPointer(down);
tester.closeArena(5);
expect(recognized, const <String>[]);
tester.route(down);
expect(recognized, const <String>['down']);
tester.async.elapse(const Duration(milliseconds: 300));
expect(recognized, const <String>['down']);
tester.async.elapse(const Duration(milliseconds: 700));
expect(recognized, const <String>['down', 'start']);
gesture.dispose();
expect(recognized, const <String>['down', 'start']);
});
testGesture('Short up cancels long press', (GestureTester tester) {
gesture.addPointer(down);
tester.closeArena(5);
expect(recognized, const <String>[]);
tester.route(down);
expect(recognized, const <String>['down']);
tester.async.elapse(const Duration(milliseconds: 300));
expect(recognized, const <String>['down']);
tester.route(up);
expect(recognized, const <String>['down', 'cancel']);
tester.async.elapse(const Duration(seconds: 1));
expect(recognized, const <String>['down', 'cancel']);
gesture.dispose();
expect(recognized, const <String>['down', 'cancel']);
});
testGesture('Moving before accept cancels', (GestureTester tester) {
gesture.addPointer(down);
tester.closeArena(5);
expect(recognized, const <String>[]);
tester.route(down);
expect(recognized, const <String>['down']);
tester.async.elapse(const Duration(milliseconds: 300));
expect(recognized, const <String>['down']);
tester.route(move);
expect(recognized, const <String>['down', 'cancel']);
tester.async.elapse(const Duration(seconds: 1));
tester.route(up);
tester.async.elapse(const Duration(milliseconds: 300));
expect(recognized, const <String>['down', 'cancel']);
gesture.dispose();
expect(recognized, const <String>['down', 'cancel']);
});
testGesture('Moving after accept does not cancel', (GestureTester tester) {
gesture.addPointer(down);
tester.closeArena(5);
expect(recognized, const <String>[]);
tester.route(down);
expect(recognized, const <String>['down']);
tester.async.elapse(const Duration(seconds: 1));
expect(recognized, const <String>['down', 'start']);
tester.route(move);
expect(recognized, const <String>['down', 'start', 'move']);
expect(longPressDragUpdate, const Offset(100, 200));
tester.route(up);
tester.async.elapse(const Duration(milliseconds: 300));
expect(recognized, const <String>['down', 'start', 'move', 'end']);
gesture.dispose();
expect(recognized, const <String>['down', 'start', 'move', 'end']);
});
});
group('Enforce consistent-button restriction:', () {
// In sequence between `down` and `up` but with buttons changed
const PointerMoveEvent moveR = PointerMoveEvent(
pointer: 5,
buttons: kSecondaryButton,
position: Offset(10, 10),
);
late LongPressGestureRecognizer gesture;
final List<String> recognized = <String>[];
setUp(() {
gesture = LongPressGestureRecognizer()
..onLongPressDown = (LongPressDownDetails details) {
recognized.add('down');
}
..onLongPressCancel = () {
recognized.add('cancel');
}
..onLongPressStart = (LongPressStartDetails details) {
recognized.add('start');
}
..onLongPressEnd = (LongPressEndDetails details) {
recognized.add('end');
};
});
tearDown(() {
gesture.dispose();
recognized.clear();
});
testGesture('Should cancel long press when buttons change before acceptance', (GestureTester tester) {
// First press
gesture.addPointer(down);
tester.closeArena(down.pointer);
tester.route(down);
tester.async.elapse(const Duration(milliseconds: 300));
tester.route(moveR);
expect(recognized, const <String>['down', 'cancel']);
tester.async.elapse(const Duration(milliseconds: 700));
tester.route(up);
expect(recognized, const <String>['down', 'cancel']);
});
testGesture('Buttons change before acceptance should not prevent the next long press', (GestureTester tester) {
// First press
gesture.addPointer(down);
tester.closeArena(down.pointer);
tester.route(down);
expect(recognized, <String>['down']);
tester.async.elapse(const Duration(milliseconds: 300));
tester.route(moveR);
expect(recognized, <String>['down', 'cancel']);
tester.async.elapse(const Duration(milliseconds: 700));
tester.route(up);
recognized.clear();
// Second press
gesture.addPointer(down2);
tester.closeArena(down2.pointer);
tester.route(down2);
expect(recognized, <String>['down']);
tester.async.elapse(const Duration(milliseconds: 1000));
expect(recognized, <String>['down', 'start']);
recognized.clear();
tester.route(up2);
expect(recognized, <String>['end']);
});
testGesture('Should not cancel long press when buttons change after acceptance', (GestureTester tester) {
// First press
gesture.addPointer(down);
tester.closeArena(down.pointer);
tester.route(down);
tester.async.elapse(const Duration(milliseconds: 1000));
expect(recognized, <String>['down', 'start']);
recognized.clear();
tester.route(moveR);
expect(recognized, <String>[]);
tester.route(up);
expect(recognized, <String>['end']);
});
testGesture('Buttons change after acceptance should not prevent the next long press', (GestureTester tester) {
// First press
gesture.addPointer(down);
tester.closeArena(down.pointer);
tester.route(down);
tester.async.elapse(const Duration(milliseconds: 1000));
tester.route(moveR);
tester.route(up);
recognized.clear();
// Second press
gesture.addPointer(down2);
tester.closeArena(down2.pointer);
tester.route(down2);
tester.async.elapse(const Duration(milliseconds: 1000));
expect(recognized, <String>['down', 'start']);
recognized.clear();
tester.route(up2);
expect(recognized, <String>['end']);
});
});
testGesture('Can filter long press based on device kind', (GestureTester tester) {
final LongPressGestureRecognizer mouseLongPress = LongPressGestureRecognizer(
supportedDevices: <PointerDeviceKind>{ PointerDeviceKind.mouse },
);
bool mouseLongPressDown = false;
mouseLongPress.onLongPress = () {
mouseLongPressDown = true;
};
const PointerDownEvent mouseDown = PointerDownEvent(
pointer: 5,
position: Offset(10, 10),
kind: PointerDeviceKind.mouse,
);
const PointerDownEvent touchDown = PointerDownEvent(
pointer: 5,
position: Offset(10, 10),
);
// Touch events shouldn't be recognized.
mouseLongPress.addPointer(touchDown);
tester.closeArena(5);
expect(mouseLongPressDown, isFalse);
tester.route(touchDown);
expect(mouseLongPressDown, isFalse);
tester.async.elapse(const Duration(seconds: 2));
expect(mouseLongPressDown, isFalse);
// Mouse events are still recognized.
mouseLongPress.addPointer(mouseDown);
tester.closeArena(5);
expect(mouseLongPressDown, isFalse);
tester.route(mouseDown);
expect(mouseLongPressDown, isFalse);
tester.async.elapse(const Duration(seconds: 2));
expect(mouseLongPressDown, isTrue);
mouseLongPress.dispose();
});
group('Recognizers listening on different buttons do not form competition:', () {
// This test is assisted by tap recognizers. If a tap gesture has
// no competing recognizers, a pointer down event triggers its onTapDown
// immediately; if there are competitors, onTapDown is triggered after a
// timeout.
// The following tests make sure that long press recognizers do not form
// competition with a tap gesture recognizer listening on a different button.
final List<String> recognized = <String>[];
late TapGestureRecognizer tapPrimary;
late TapGestureRecognizer tapSecondary;
late LongPressGestureRecognizer longPress;
setUp(() {
tapPrimary = TapGestureRecognizer()
..onTapDown = (TapDownDetails details) {
recognized.add('tapPrimary');
};
tapSecondary = TapGestureRecognizer()
..onSecondaryTapDown = (TapDownDetails details) {
recognized.add('tapSecondary');
};
longPress = LongPressGestureRecognizer()
..onLongPressStart = (_) {
recognized.add('longPress');
};
});
tearDown(() {
recognized.clear();
tapPrimary.dispose();
tapSecondary.dispose();
longPress.dispose();
});
testGesture('A primary long press recognizer does not form competition with a secondary tap recognizer', (GestureTester tester) {
longPress.addPointer(down3);
tapSecondary.addPointer(down3);
tester.closeArena(down3.pointer);
tester.route(down3);
expect(recognized, <String>['tapSecondary']);
});
testGesture('A primary long press recognizer forms competition with a primary tap recognizer', (GestureTester tester) {
longPress.addPointer(down);
tapPrimary.addPointer(down);
tester.closeArena(down.pointer);
tester.route(down);
expect(recognized, <String>[]);
tester.route(up);
expect(recognized, <String>['tapPrimary']);
});
});
testGesture('A secondary long press should not trigger primary', (GestureTester tester) {
final List<String> recognized = <String>[];
final LongPressGestureRecognizer longPress = LongPressGestureRecognizer()
..onLongPressStart = (LongPressStartDetails details) {
recognized.add('primaryStart');
}
..onLongPress = () {
recognized.add('primary');
}
..onLongPressMoveUpdate = (LongPressMoveUpdateDetails details) {
recognized.add('primaryUpdate');
}
..onLongPressEnd = (LongPressEndDetails details) {
recognized.add('primaryEnd');
}
..onLongPressUp = () {
recognized.add('primaryUp');
};
const PointerDownEvent down2 = PointerDownEvent(
pointer: 2,
buttons: kSecondaryButton,
position: Offset(30.0, 30.0),
);
const PointerMoveEvent move2 = PointerMoveEvent(
pointer: 2,
buttons: kSecondaryButton,
position: Offset(100, 200),
);
const PointerUpEvent up2 = PointerUpEvent(
pointer: 2,
position: Offset(100, 201),
);
longPress.addPointer(down2);
tester.closeArena(2);
tester.route(down2);
tester.async.elapse(const Duration(milliseconds: 700));
tester.route(move2);
tester.route(up2);
expect(recognized, <String>[]);
longPress.dispose();
recognized.clear();
});
testGesture('A tertiary long press should not trigger primary or secondary', (GestureTester tester) {
final List<String> recognized = <String>[];
final LongPressGestureRecognizer longPress = LongPressGestureRecognizer()
..onLongPressStart = (LongPressStartDetails details) {
recognized.add('primaryStart');
}
..onLongPress = () {
recognized.add('primary');
}
..onLongPressMoveUpdate = (LongPressMoveUpdateDetails details) {
recognized.add('primaryUpdate');
}
..onLongPressEnd = (LongPressEndDetails details) {
recognized.add('primaryEnd');
}
..onLongPressUp = () {
recognized.add('primaryUp');
}
..onSecondaryLongPressStart = (LongPressStartDetails details) {
recognized.add('secondaryStart');
}
..onSecondaryLongPress = () {
recognized.add('secondary');
}
..onSecondaryLongPressMoveUpdate = (LongPressMoveUpdateDetails details) {
recognized.add('secondaryUpdate');
}
..onSecondaryLongPressEnd = (LongPressEndDetails details) {
recognized.add('secondaryEnd');
}
..onSecondaryLongPressUp = () {
recognized.add('secondaryUp');
};
const PointerDownEvent down2 = PointerDownEvent(
pointer: 2,
buttons: kTertiaryButton,
position: Offset(30.0, 30.0),
);
const PointerMoveEvent move2 = PointerMoveEvent(
pointer: 2,
buttons: kTertiaryButton,
position: Offset(100, 200),
);
const PointerUpEvent up2 = PointerUpEvent(
pointer: 2,
position: Offset(100, 201),
);
longPress.addPointer(down2);
tester.closeArena(2);
tester.route(down2);
tester.async.elapse(const Duration(milliseconds: 700));
tester.route(move2);
tester.route(up2);
expect(recognized, <String>[]);
longPress.dispose();
recognized.clear();
});
testGesture('Switching buttons mid-stream does not fail to send "end" event', (GestureTester tester) {
final List<String> recognized = <String>[];
final LongPressGestureRecognizer longPress = LongPressGestureRecognizer()
..onLongPressStart = (LongPressStartDetails details) {
recognized.add('primaryStart');
}
..onLongPressEnd = (LongPressEndDetails details) {
recognized.add('primaryEnd');
};
const PointerDownEvent down4 = PointerDownEvent(
pointer: 8,
position: Offset(10, 10),
);
const PointerMoveEvent move4 = PointerMoveEvent(
pointer: 8,
position: Offset(100, 200),
buttons: kPrimaryButton | kSecondaryButton,
);
const PointerUpEvent up4 = PointerUpEvent(
pointer: 8,
position: Offset(100, 200),
buttons: kSecondaryButton,
);
longPress.addPointer(down4);
tester.closeArena(4);
tester.route(down4);
tester.async.elapse(const Duration(milliseconds: 1000));
recognized.add('two seconds later...');
tester.route(move4);
tester.async.elapse(const Duration(milliseconds: 1000));
recognized.add('two more seconds later...');
tester.route(up4);
tester.async.elapse(const Duration(milliseconds: 1000));
expect(recognized, <String>['primaryStart', 'two seconds later...', 'two more seconds later...', 'primaryEnd']);
longPress.dispose();
});
testGesture('Switching buttons mid-stream does not fail to send "end" event (alternative sequence)', (GestureTester tester) {
// This reproduces sequences seen on macOS.
final List<String> recognized = <String>[];
final LongPressGestureRecognizer longPress = LongPressGestureRecognizer()
..onLongPressStart = (LongPressStartDetails details) {
recognized.add('primaryStart');
}
..onLongPressEnd = (LongPressEndDetails details) {
recognized.add('primaryEnd');
};
const PointerDownEvent down5 = PointerDownEvent(
pointer: 9,
position: Offset(10, 10),
);
const PointerMoveEvent move5a = PointerMoveEvent(
pointer: 9,
position: Offset(100, 200),
buttons: 3, // add 2
);
const PointerMoveEvent move5b = PointerMoveEvent(
pointer: 9,
position: Offset(100, 200),
buttons: 2, // remove 1
);
const PointerUpEvent up5 = PointerUpEvent(
pointer: 9,
position: Offset(100, 200),
);
longPress.addPointer(down5);
tester.closeArena(4);
tester.route(down5);
tester.async.elapse(const Duration(milliseconds: 1000));
recognized.add('two seconds later...');
tester.route(move5a);
tester.async.elapse(const Duration(milliseconds: 1000));
recognized.add('two more seconds later...');
tester.route(move5b);
tester.async.elapse(const Duration(milliseconds: 1000));
recognized.add('two more seconds later still...');
tester.route(up5);
tester.async.elapse(const Duration(milliseconds: 1000));
expect(recognized, <String>['primaryStart', 'two seconds later...', 'two more seconds later...', 'two more seconds later still...', 'primaryEnd']);
longPress.dispose();
});
}
| flutter/packages/flutter/test/gestures/long_press_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/gestures/long_press_test.dart",
"repo_id": "flutter",
"token_count": 10803
} | 834 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('Horizontal', () {
testWidgets('gets local coordinates', (WidgetTester tester) async {
int dragCancelCount = 0;
final List<DragDownDetails> downDetails = <DragDownDetails>[];
final List<DragEndDetails> endDetails = <DragEndDetails>[];
final List<DragStartDetails> startDetails = <DragStartDetails>[];
final List<DragUpdateDetails> updateDetails = <DragUpdateDetails>[];
final Key redContainer = UniqueKey();
await tester.pumpWidget(
Center(
child: GestureDetector(
onHorizontalDragCancel: () {
dragCancelCount++;
},
onHorizontalDragDown: (DragDownDetails details) {
downDetails.add(details);
},
onHorizontalDragEnd: (DragEndDetails details) {
endDetails.add(details);
},
onHorizontalDragStart: (DragStartDetails details) {
startDetails.add(details);
},
onHorizontalDragUpdate: (DragUpdateDetails details) {
updateDetails.add(details);
},
child: Container(
key: redContainer,
width: 100,
height: 150,
color: Colors.red,
),
),
),
);
await tester.drag(find.byKey(redContainer), const Offset(100, 0));
expect(dragCancelCount, 0);
expect(downDetails.single.localPosition, const Offset(50, 75));
expect(downDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails, hasLength(1));
expect(startDetails.single.localPosition, const Offset(50, 75));
expect(startDetails.single.globalPosition, const Offset(400, 300));
expect(updateDetails.last.localPosition, const Offset(50 + 100.0, 75));
expect(updateDetails.last.globalPosition, const Offset(400 + 100.0, 300));
expect(
updateDetails.fold(Offset.zero, (Offset offset, DragUpdateDetails details) => offset + details.delta),
const Offset(100, 0),
);
expect(
updateDetails.fold(0.0, (double offset, DragUpdateDetails details) => offset + (details.primaryDelta ?? 0)),
100.0,
);
});
testWidgets('kTouchSlop is evaluated in the global coordinate space when scaled up', (WidgetTester tester) async {
int dragCancelCount = 0;
final List<DragDownDetails> downDetails = <DragDownDetails>[];
final List<DragEndDetails> endDetails = <DragEndDetails>[];
final List<DragStartDetails> startDetails = <DragStartDetails>[];
final List<DragUpdateDetails> updateDetails = <DragUpdateDetails>[];
final Key redContainer = UniqueKey();
await tester.pumpWidget(
Center(
child: Transform.scale(
scale: 2.0,
child: GestureDetector(
onHorizontalDragCancel: () {
dragCancelCount++;
},
onHorizontalDragDown: (DragDownDetails details) {
downDetails.add(details);
},
onHorizontalDragEnd: (DragEndDetails details) {
endDetails.add(details);
},
onHorizontalDragStart: (DragStartDetails details) {
startDetails.add(details);
},
onHorizontalDragUpdate: (DragUpdateDetails details) {
updateDetails.add(details);
},
onTap: () {
// Competing gesture detector.
},
child: Container(
key: redContainer,
width: 100,
height: 150,
color: Colors.red,
),
),
),
),
);
// Move just above kTouchSlop should recognize drag.
await tester.drag(find.byKey(redContainer), const Offset(kTouchSlop + 1, 0));
expect(dragCancelCount, 0);
expect(downDetails.single.localPosition, const Offset(50, 75));
expect(downDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails, hasLength(1));
expect(startDetails.single.localPosition, const Offset(50 + (kTouchSlop + 1) / 2, 75));
expect(startDetails.single.globalPosition, const Offset(400 + (kTouchSlop + 1), 300));
expect(updateDetails, isEmpty);
dragCancelCount = 0;
downDetails.clear();
endDetails.clear();
startDetails.clear();
updateDetails.clear();
// Move just below kTouchSlop does not recognize drag.
await tester.drag(find.byKey(redContainer), const Offset(kTouchSlop - 1, 0));
expect(dragCancelCount, 1);
expect(downDetails.single.localPosition, const Offset(50, 75));
expect(downDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails, isEmpty);
expect(startDetails, isEmpty);
expect(updateDetails, isEmpty);
dragCancelCount = 0;
downDetails.clear();
endDetails.clear();
startDetails.clear();
updateDetails.clear();
// Move in two separate movements
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(redContainer)));
await gesture.moveBy(const Offset(kTouchSlop + 1, 30));
await gesture.moveBy(const Offset(100, 10));
await gesture.up();
expect(dragCancelCount, 0);
expect(downDetails.single.localPosition, const Offset(50, 75));
expect(downDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails, hasLength(1));
expect(startDetails.single.localPosition, const Offset(50 + (kTouchSlop + 1) / 2, 75.0 + 30.0 / 2));
expect(startDetails.single.globalPosition, const Offset(400 + (kTouchSlop + 1), 300 + 30.0));
expect(updateDetails.single.localPosition, startDetails.single.localPosition + const Offset(100.0 / 2, 10 / 2));
expect(updateDetails.single.globalPosition, startDetails.single.globalPosition + const Offset(100.0, 10.0));
expect(updateDetails.single.delta, const Offset(100.0 / 2, 0.0));
expect(updateDetails.single.primaryDelta, 100.0 / 2);
dragCancelCount = 0;
downDetails.clear();
endDetails.clear();
startDetails.clear();
updateDetails.clear();
});
testWidgets('kTouchSlop is evaluated in the global coordinate space when scaled down', (WidgetTester tester) async {
int dragCancelCount = 0;
final List<DragDownDetails> downDetails = <DragDownDetails>[];
final List<DragEndDetails> endDetails = <DragEndDetails>[];
final List<DragStartDetails> startDetails = <DragStartDetails>[];
final List<DragUpdateDetails> updateDetails = <DragUpdateDetails>[];
final Key redContainer = UniqueKey();
await tester.pumpWidget(
Center(
child: Transform.scale(
scale: 0.5,
child: GestureDetector(
onHorizontalDragCancel: () {
dragCancelCount++;
},
onHorizontalDragDown: (DragDownDetails details) {
downDetails.add(details);
},
onHorizontalDragEnd: (DragEndDetails details) {
endDetails.add(details);
},
onHorizontalDragStart: (DragStartDetails details) {
startDetails.add(details);
},
onHorizontalDragUpdate: (DragUpdateDetails details) {
updateDetails.add(details);
},
onTap: () {
// Competing gesture detector.
},
child: Container(
key: redContainer,
width: 100,
height: 150,
color: Colors.red,
),
),
),
),
);
// Move just above kTouchSlop should recognize drag.
await tester.drag(find.byKey(redContainer), const Offset(kTouchSlop + 1, 0));
expect(dragCancelCount, 0);
expect(downDetails.single.localPosition, const Offset(50, 75));
expect(downDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails, hasLength(1));
expect(startDetails.single.localPosition, const Offset(50 + (kTouchSlop + 1) * 2, 75));
expect(startDetails.single.globalPosition, const Offset(400 + (kTouchSlop + 1), 300));
expect(updateDetails, isEmpty);
dragCancelCount = 0;
downDetails.clear();
endDetails.clear();
startDetails.clear();
updateDetails.clear();
// Move just below kTouchSlop does not recognize drag.
await tester.drag(find.byKey(redContainer), const Offset(kTouchSlop - 1, 0));
expect(dragCancelCount, 1);
expect(downDetails.single.localPosition, const Offset(50, 75));
expect(downDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails, isEmpty);
expect(startDetails, isEmpty);
expect(updateDetails, isEmpty);
dragCancelCount = 0;
downDetails.clear();
endDetails.clear();
startDetails.clear();
updateDetails.clear();
// Move in two separate movements
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(redContainer)));
await gesture.moveBy(const Offset(kTouchSlop + 1, 30));
await gesture.moveBy(const Offset(100, 10));
await gesture.up();
expect(dragCancelCount, 0);
expect(downDetails.single.localPosition, const Offset(50, 75));
expect(downDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails, hasLength(1));
expect(startDetails.single.localPosition, const Offset(50 + (kTouchSlop + 1) * 2, 75.0 + 30.0 * 2));
expect(startDetails.single.globalPosition, const Offset(400 + (kTouchSlop + 1), 300 + 30.0));
expect(updateDetails.single.localPosition, startDetails.single.localPosition + const Offset(100.0 * 2, 10.0 * 2.0));
expect(updateDetails.single.globalPosition, startDetails.single.globalPosition + const Offset(100.0, 10.0));
expect(updateDetails.single.delta, const Offset(100.0 * 2.0, 0.0));
expect(updateDetails.single.primaryDelta, 100.0 * 2);
dragCancelCount = 0;
downDetails.clear();
endDetails.clear();
startDetails.clear();
updateDetails.clear();
});
testWidgets('kTouchSlop is evaluated in the global coordinate space when rotated 45 degrees', (WidgetTester tester) async {
int dragCancelCount = 0;
final List<DragDownDetails> downDetails = <DragDownDetails>[];
final List<DragEndDetails> endDetails = <DragEndDetails>[];
final List<DragStartDetails> startDetails = <DragStartDetails>[];
final List<DragUpdateDetails> updateDetails = <DragUpdateDetails>[];
final Key redContainer = UniqueKey();
await tester.pumpWidget(
Center(
child: Transform.rotate(
angle: math.pi / 4,
child: GestureDetector(
onHorizontalDragCancel: () {
dragCancelCount++;
},
onHorizontalDragDown: (DragDownDetails details) {
downDetails.add(details);
},
onHorizontalDragEnd: (DragEndDetails details) {
endDetails.add(details);
},
onHorizontalDragStart: (DragStartDetails details) {
startDetails.add(details);
},
onHorizontalDragUpdate: (DragUpdateDetails details) {
updateDetails.add(details);
},
onTap: () {
// Competing gesture detector.
},
child: Container(
key: redContainer,
width: 100,
height: 150,
color: Colors.red,
),
),
),
),
);
// Move just below kTouchSlop should not recognize drag.
const Offset moveBy1 = Offset(kTouchSlop/ 2, kTouchSlop / 2);
expect(moveBy1.distance, lessThan(kTouchSlop));
await tester.drag(find.byKey(redContainer), moveBy1);
expect(dragCancelCount, 1);
expect(downDetails.single.localPosition, within(distance: 0.0001, from: const Offset(50, 75)));
expect(downDetails.single.globalPosition, within(distance: 0.0001, from: const Offset(400, 300)));
expect(endDetails, isEmpty);
expect(startDetails, isEmpty);
expect(updateDetails, isEmpty);
dragCancelCount = 0;
downDetails.clear();
endDetails.clear();
startDetails.clear();
updateDetails.clear();
// Move above kTouchSlop recognizes drag.
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(redContainer)));
await gesture.moveBy(const Offset(kTouchSlop, kTouchSlop));
await gesture.moveBy(const Offset(3, 4));
await gesture.up();
expect(dragCancelCount, 0);
expect(downDetails.single.localPosition, within(distance: 0.0001, from: const Offset(50, 75)));
expect(downDetails.single.globalPosition, within(distance: 0.0001, from: const Offset(400, 300)));
expect(endDetails, hasLength(1));
expect(startDetails, hasLength(1));
expect(updateDetails.single.globalPosition, within(distance: 0.0001, from: const Offset(400 + kTouchSlop + 3, 300 + kTouchSlop + 4)));
expect(updateDetails.single.delta, within(distance: 0.1, from: const Offset(5, 0.0))); // sqrt(3^2 + 4^2)
expect(updateDetails.single.primaryDelta, within<double>(distance: 0.1, from: 5.0)); // sqrt(3^2 + 4^2)
});
});
group('Vertical', () {
testWidgets('gets local coordinates', (WidgetTester tester) async {
int dragCancelCount = 0;
final List<DragDownDetails> downDetails = <DragDownDetails>[];
final List<DragEndDetails> endDetails = <DragEndDetails>[];
final List<DragStartDetails> startDetails = <DragStartDetails>[];
final List<DragUpdateDetails> updateDetails = <DragUpdateDetails>[];
final Key redContainer = UniqueKey();
await tester.pumpWidget(
Center(
child: GestureDetector(
onVerticalDragCancel: () {
dragCancelCount++;
},
onVerticalDragDown: (DragDownDetails details) {
downDetails.add(details);
},
onVerticalDragEnd: (DragEndDetails details) {
endDetails.add(details);
},
onVerticalDragStart: (DragStartDetails details) {
startDetails.add(details);
},
onVerticalDragUpdate: (DragUpdateDetails details) {
updateDetails.add(details);
},
child: Container(
key: redContainer,
width: 100,
height: 150,
color: Colors.red,
),
),
),
);
await tester.drag(find.byKey(redContainer), const Offset(0, 100));
expect(dragCancelCount, 0);
expect(downDetails.single.localPosition, const Offset(50, 75));
expect(downDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails, hasLength(1));
expect(startDetails.single.localPosition, const Offset(50, 75));
expect(startDetails.single.globalPosition, const Offset(400, 300));
expect(updateDetails.last.localPosition, const Offset(50, 75 + 100.0));
expect(updateDetails.last.globalPosition, const Offset(400, 300 + 100.0));
expect(
updateDetails.fold(Offset.zero, (Offset offset, DragUpdateDetails details) => offset + details.delta),
const Offset(0, 100),
);
expect(
updateDetails.fold(0.0, (double offset, DragUpdateDetails details) => offset + (details.primaryDelta ?? 0)),
100.0,
);
});
testWidgets('kTouchSlop is evaluated in the global coordinate space when scaled up', (WidgetTester tester) async {
int dragCancelCount = 0;
final List<DragDownDetails> downDetails = <DragDownDetails>[];
final List<DragEndDetails> endDetails = <DragEndDetails>[];
final List<DragStartDetails> startDetails = <DragStartDetails>[];
final List<DragUpdateDetails> updateDetails = <DragUpdateDetails>[];
final Key redContainer = UniqueKey();
await tester.pumpWidget(
Center(
child: Transform.scale(
scale: 2.0,
child: GestureDetector(
onVerticalDragCancel: () {
dragCancelCount++;
},
onVerticalDragDown: (DragDownDetails details) {
downDetails.add(details);
},
onVerticalDragEnd: (DragEndDetails details) {
endDetails.add(details);
},
onVerticalDragStart: (DragStartDetails details) {
startDetails.add(details);
},
onVerticalDragUpdate: (DragUpdateDetails details) {
updateDetails.add(details);
},
onTap: () {
// Competing gesture detector.
},
child: Container(
key: redContainer,
width: 100,
height: 150,
color: Colors.red,
),
),
),
),
);
// Move just above kTouchSlop should recognize drag.
await tester.drag(find.byKey(redContainer), const Offset(0, kTouchSlop + 1));
expect(dragCancelCount, 0);
expect(downDetails.single.localPosition, const Offset(50, 75));
expect(downDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails, hasLength(1));
expect(startDetails.single.localPosition, const Offset(50, 75 + (kTouchSlop + 1) / 2));
expect(startDetails.single.globalPosition, const Offset(400, 300 + (kTouchSlop + 1)));
expect(updateDetails, isEmpty);
dragCancelCount = 0;
downDetails.clear();
endDetails.clear();
startDetails.clear();
updateDetails.clear();
// Move just below kTouchSlop does not recognize drag.
await tester.drag(find.byKey(redContainer), const Offset(0, kTouchSlop - 1));
expect(dragCancelCount, 1);
expect(downDetails.single.localPosition, const Offset(50, 75));
expect(downDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails, isEmpty);
expect(startDetails, isEmpty);
expect(updateDetails, isEmpty);
dragCancelCount = 0;
downDetails.clear();
endDetails.clear();
startDetails.clear();
updateDetails.clear();
// Move in two separate movements
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(redContainer)));
await gesture.moveBy(const Offset(30, kTouchSlop + 1));
await gesture.moveBy(const Offset(10, 100));
await gesture.up();
expect(dragCancelCount, 0);
expect(downDetails.single.localPosition, const Offset(50, 75));
expect(downDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails, hasLength(1));
expect(startDetails.single.localPosition, const Offset(50 + 30.0 / 2, 75.0 + (kTouchSlop + 1) / 2));
expect(startDetails.single.globalPosition, const Offset(400 + 30.0, 300 + (kTouchSlop + 1)));
expect(updateDetails.single.localPosition, startDetails.single.localPosition + const Offset(10.0 / 2, 100.0 / 2));
expect(updateDetails.single.globalPosition, startDetails.single.globalPosition + const Offset(10.0, 100.0));
expect(updateDetails.single.delta, const Offset(0.0, 100.0 / 2));
expect(updateDetails.single.primaryDelta, 100.0 / 2);
dragCancelCount = 0;
downDetails.clear();
endDetails.clear();
startDetails.clear();
updateDetails.clear();
});
testWidgets('kTouchSlop is evaluated in the global coordinate space when scaled down', (WidgetTester tester) async {
int dragCancelCount = 0;
final List<DragDownDetails> downDetails = <DragDownDetails>[];
final List<DragEndDetails> endDetails = <DragEndDetails>[];
final List<DragStartDetails> startDetails = <DragStartDetails>[];
final List<DragUpdateDetails> updateDetails = <DragUpdateDetails>[];
final Key redContainer = UniqueKey();
await tester.pumpWidget(
Center(
child: Transform.scale(
scale: 0.5,
child: GestureDetector(
onVerticalDragCancel: () {
dragCancelCount++;
},
onVerticalDragDown: (DragDownDetails details) {
downDetails.add(details);
},
onVerticalDragEnd: (DragEndDetails details) {
endDetails.add(details);
},
onVerticalDragStart: (DragStartDetails details) {
startDetails.add(details);
},
onVerticalDragUpdate: (DragUpdateDetails details) {
updateDetails.add(details);
},
onTap: () {
// Competing gesture detector.
},
child: Container(
key: redContainer,
width: 100,
height: 150,
color: Colors.red,
),
),
),
),
);
// Move just above kTouchSlop should recognize drag.
await tester.drag(find.byKey(redContainer), const Offset(0, kTouchSlop + 1));
expect(dragCancelCount, 0);
expect(downDetails.single.localPosition, const Offset(50, 75));
expect(downDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails, hasLength(1));
expect(startDetails.single.localPosition, const Offset(50, 75 + (kTouchSlop + 1) * 2));
expect(startDetails.single.globalPosition, const Offset(400, 300 + (kTouchSlop + 1)));
expect(updateDetails, isEmpty);
dragCancelCount = 0;
downDetails.clear();
endDetails.clear();
startDetails.clear();
updateDetails.clear();
// Move just below kTouchSlop does not recognize drag.
await tester.drag(find.byKey(redContainer), const Offset(0, kTouchSlop - 1));
expect(dragCancelCount, 1);
expect(downDetails.single.localPosition, const Offset(50, 75));
expect(downDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails, isEmpty);
expect(startDetails, isEmpty);
expect(updateDetails, isEmpty);
dragCancelCount = 0;
downDetails.clear();
endDetails.clear();
startDetails.clear();
updateDetails.clear();
// Move in two separate movements
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(redContainer)));
await gesture.moveBy(const Offset(30, kTouchSlop + 1));
await gesture.moveBy(const Offset(10, 100));
await gesture.up();
expect(dragCancelCount, 0);
expect(downDetails.single.localPosition, const Offset(50, 75));
expect(downDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails, hasLength(1));
expect(startDetails.single.localPosition, const Offset(50 + 30.0 * 2, 75.0 + (kTouchSlop + 1) * 2));
expect(startDetails.single.globalPosition, const Offset(400 + 30.0, 300 + (kTouchSlop + 1)));
expect(updateDetails.single.localPosition, startDetails.single.localPosition + const Offset(10.0 * 2, 100.0 * 2.0));
expect(updateDetails.single.globalPosition, startDetails.single.globalPosition + const Offset(10.0, 100.0));
expect(updateDetails.single.delta, const Offset(0.0, 100.0 * 2.0));
expect(updateDetails.single.primaryDelta, 100.0 * 2);
dragCancelCount = 0;
downDetails.clear();
endDetails.clear();
startDetails.clear();
updateDetails.clear();
});
testWidgets('kTouchSlop is evaluated in the global coordinate space when rotated 45 degrees', (WidgetTester tester) async {
int dragCancelCount = 0;
final List<DragDownDetails> downDetails = <DragDownDetails>[];
final List<DragEndDetails> endDetails = <DragEndDetails>[];
final List<DragStartDetails> startDetails = <DragStartDetails>[];
final List<DragUpdateDetails> updateDetails = <DragUpdateDetails>[];
final Key redContainer = UniqueKey();
await tester.pumpWidget(
Center(
child: Transform.rotate(
angle: math.pi / 4,
child: GestureDetector(
onVerticalDragCancel: () {
dragCancelCount++;
},
onVerticalDragDown: (DragDownDetails details) {
downDetails.add(details);
},
onVerticalDragEnd: (DragEndDetails details) {
endDetails.add(details);
},
onVerticalDragStart: (DragStartDetails details) {
startDetails.add(details);
},
onVerticalDragUpdate: (DragUpdateDetails details) {
updateDetails.add(details);
},
onTap: () {
// Competing gesture detector.
},
child: Container(
key: redContainer,
width: 100,
height: 150,
color: Colors.red,
),
),
),
),
);
// Move just below kTouchSlop should not recognize drag.
const Offset moveBy1 = Offset(kTouchSlop/ 2, kTouchSlop / 2);
expect(moveBy1.distance, lessThan(kTouchSlop));
await tester.drag(find.byKey(redContainer), moveBy1);
expect(dragCancelCount, 1);
expect(downDetails.single.localPosition, within(distance: 0.0001, from: const Offset(50, 75)));
expect(downDetails.single.globalPosition, within(distance: 0.0001, from: const Offset(400, 300)));
expect(endDetails, isEmpty);
expect(startDetails, isEmpty);
expect(updateDetails, isEmpty);
dragCancelCount = 0;
downDetails.clear();
endDetails.clear();
startDetails.clear();
updateDetails.clear();
// Move above kTouchSlop recognizes drag.
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(redContainer)));
await gesture.moveBy(const Offset(kTouchSlop, kTouchSlop));
await gesture.moveBy(const Offset(-4, 3));
await gesture.up();
expect(dragCancelCount, 0);
expect(downDetails.single.localPosition, within(distance: 0.0001, from: const Offset(50, 75)));
expect(downDetails.single.globalPosition, within(distance: 0.0001, from: const Offset(400, 300)));
expect(endDetails, hasLength(1));
expect(startDetails, hasLength(1));
expect(updateDetails.single.globalPosition, within(distance: 0.0001, from: const Offset(400 + kTouchSlop - 4, 300 + kTouchSlop + 3)));
expect(updateDetails.single.delta, within(distance: 0.1, from: const Offset(0.0, 5.0))); // sqrt(3^2 + 4^2)
expect(updateDetails.single.primaryDelta, within<double>(distance: 0.1, from: 5.0)); // sqrt(3^2 + 4^2)
});
});
}
| flutter/packages/flutter/test/gestures/transformed_monodrag_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/gestures/transformed_monodrag_test.dart",
"repo_id": "flutter",
"token_count": 11663
} | 835 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
Finder findAppBarMaterial() {
return find.descendant(
of: find.byType(AppBar),
matching: find.byType(Material),
).first;
}
Color? getAppBarBackgroundColor(WidgetTester tester) {
return tester.widget<Material>(findAppBarMaterial()).color;
}
double appBarHeight(WidgetTester tester) {
return tester.getSize(find.byType(AppBar, skipOffstage: false)).height;
}
double appBarTop(WidgetTester tester) {
return tester.getTopLeft(find.byType(AppBar, skipOffstage: false)).dy;
}
double appBarBottom(WidgetTester tester) {
return tester.getBottomLeft(find.byType(AppBar, skipOffstage: false)).dy;
}
double tabBarHeight(WidgetTester tester) {
return tester.getSize(find.byType(TabBar, skipOffstage: false)).height;
}
ScrollController primaryScrollController(WidgetTester tester) {
return PrimaryScrollController.of(
tester.element(find.byType(CustomScrollView))
);
}
void verifyTextNotClipped(Finder textFinder, WidgetTester tester) {
final Rect clipRect = tester.getRect(
find.ancestor(of: textFinder, matching: find.byType(ClipRect)).first,
);
final Rect textRect = tester.getRect(textFinder);
expect(textRect.top, inInclusiveRange(clipRect.top, clipRect.bottom));
expect(textRect.bottom, inInclusiveRange(clipRect.top, clipRect.bottom));
expect(textRect.left, inInclusiveRange(clipRect.left, clipRect.right));
expect(textRect.right, inInclusiveRange(clipRect.left, clipRect.right));
}
| flutter/packages/flutter/test/material/app_bar_utils.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/app_bar_utils.dart",
"repo_id": "flutter",
"token_count": 558
} | 836 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('ButtonBar default control smoketest', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: ButtonBar(),
),
);
});
group('alignment', () {
testWidgets('default alignment is MainAxisAlignment.end', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: ButtonBar(
children: <Widget>[
SizedBox(width: 10.0, height: 10.0),
],
),
),
);
final Finder child = find.byType(SizedBox);
// Should be positioned to the right of the bar,
expect(tester.getRect(child).left, 782.0); // bar width - default padding - 10
expect(tester.getRect(child).right, 792.0); // bar width - default padding
});
testWidgets('ButtonBarTheme.alignment overrides default', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: ButtonBarTheme(
data: ButtonBarThemeData(
alignment: MainAxisAlignment.center,
),
child: ButtonBar(
children: <Widget>[
SizedBox(width: 10.0, height: 10.0),
],
),
),
),
);
final Finder child = find.byType(SizedBox);
// Should be positioned in the center
expect(tester.getRect(child).left, 395.0); // (bar width - padding) / 2 - 10 / 2
expect(tester.getRect(child).right, 405.0); // (bar width - padding) / 2 - 10 / 2 + 10
});
testWidgets('ButtonBar.alignment overrides ButtonBarTheme.alignment and default', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: ButtonBarTheme(
data: ButtonBarThemeData(
alignment: MainAxisAlignment.center,
),
child: ButtonBar(
alignment: MainAxisAlignment.start,
children: <Widget>[
SizedBox(width: 10.0, height: 10.0),
],
),
),
),
);
final Finder child = find.byType(SizedBox);
// Should be positioned on the left
expect(tester.getRect(child).left, 8.0); // padding
expect(tester.getRect(child).right, 18.0); // padding + 10
});
});
group('mainAxisSize', () {
testWidgets('Default mainAxisSize is MainAxisSize.max', (WidgetTester tester) async {
const Key buttonBarKey = Key('row');
const Key child0Key = Key('child0');
const Key child1Key = Key('child1');
const Key child2Key = Key('child2');
await tester.pumpWidget(
const MaterialApp(
home: Center(
child: ButtonBar(
key: buttonBarKey,
// buttonPadding set to zero to simplify test calculations.
buttonPadding: EdgeInsets.zero,
children: <Widget>[
SizedBox(key: child0Key, width: 100.0, height: 100.0),
SizedBox(key: child1Key, width: 100.0, height: 100.0),
SizedBox(key: child2Key, width: 100.0, height: 100.0),
],
),
),
),
);
// ButtonBar should take up all the space it is provided by its parent.
final Rect buttonBarRect = tester.getRect(find.byKey(buttonBarKey));
expect(buttonBarRect.size.width, equals(800.0));
expect(buttonBarRect.size.height, equals(100.0));
// The children of [ButtonBar] are aligned by [MainAxisAlignment.end] by
// default.
Rect childRect;
childRect = tester.getRect(find.byKey(child0Key));
expect(childRect.size.width, equals(100.0));
expect(childRect.size.height, equals(100.0));
expect(childRect.right, 800.0 - 200.0);
childRect = tester.getRect(find.byKey(child1Key));
expect(childRect.size.width, equals(100.0));
expect(childRect.size.height, equals(100.0));
expect(childRect.right, 800.0 - 100.0);
childRect = tester.getRect(find.byKey(child2Key));
expect(childRect.size.width, equals(100.0));
expect(childRect.size.height, equals(100.0));
expect(childRect.right, 800.0);
});
testWidgets('ButtonBarTheme.mainAxisSize overrides default', (WidgetTester tester) async {
const Key buttonBarKey = Key('row');
const Key child0Key = Key('child0');
const Key child1Key = Key('child1');
const Key child2Key = Key('child2');
await tester.pumpWidget(
const MaterialApp(
home: ButtonBarTheme(
data: ButtonBarThemeData(
mainAxisSize: MainAxisSize.min,
),
child: Center(
child: ButtonBar(
key: buttonBarKey,
// buttonPadding set to zero to simplify test calculations.
buttonPadding: EdgeInsets.zero,
children: <Widget>[
SizedBox(key: child0Key, width: 100.0, height: 100.0),
SizedBox(key: child1Key, width: 100.0, height: 100.0),
SizedBox(key: child2Key, width: 100.0, height: 100.0),
],
),
),
),
),
);
// ButtonBar should take up minimum space it requires.
final Rect buttonBarRect = tester.getRect(find.byKey(buttonBarKey));
expect(buttonBarRect.size.width, equals(300.0));
expect(buttonBarRect.size.height, equals(100.0));
Rect childRect;
childRect = tester.getRect(find.byKey(child0Key));
expect(childRect.size.width, equals(100.0));
expect(childRect.size.height, equals(100.0));
// Should be a center aligned because of [Center] widget.
// First child is on the left side of the button bar.
expect(childRect.left, (800.0 - buttonBarRect.width) / 2.0);
childRect = tester.getRect(find.byKey(child1Key));
expect(childRect.size.width, equals(100.0));
expect(childRect.size.height, equals(100.0));
// Should be a center aligned because of [Center] widget.
// Second child is on the center the button bar.
expect(childRect.left, ((800.0 - buttonBarRect.width) / 2.0) + 100.0);
childRect = tester.getRect(find.byKey(child2Key));
expect(childRect.size.width, equals(100.0));
expect(childRect.size.height, equals(100.0));
// Should be a center aligned because of [Center] widget.
// Third child is on the right side of the button bar.
expect(childRect.left, ((800.0 - buttonBarRect.width) / 2.0) + 200.0);
});
testWidgets('ButtonBar.mainAxisSize overrides ButtonBarTheme.mainAxisSize and default', (WidgetTester tester) async {
const Key buttonBarKey = Key('row');
const Key child0Key = Key('child0');
const Key child1Key = Key('child1');
const Key child2Key = Key('child2');
await tester.pumpWidget(
const MaterialApp(
home: ButtonBarTheme(
data: ButtonBarThemeData(
mainAxisSize: MainAxisSize.min,
),
child: Center(
child: ButtonBar(
key: buttonBarKey,
// buttonPadding set to zero to simplify test calculations.
buttonPadding: EdgeInsets.zero,
mainAxisSize: MainAxisSize.max,
children: <Widget>[
SizedBox(key: child0Key, width: 100.0, height: 100.0),
SizedBox(key: child1Key, width: 100.0, height: 100.0),
SizedBox(key: child2Key, width: 100.0, height: 100.0),
],
),
),
),
),
);
// ButtonBar should take up all the space it is provided by its parent.
final Rect buttonBarRect = tester.getRect(find.byKey(buttonBarKey));
expect(buttonBarRect.size.width, equals(800.0));
expect(buttonBarRect.size.height, equals(100.0));
// The children of [ButtonBar] are aligned by [MainAxisAlignment.end] by
// default.
Rect childRect;
childRect = tester.getRect(find.byKey(child0Key));
expect(childRect.size.width, equals(100.0));
expect(childRect.size.height, equals(100.0));
expect(childRect.right, 800.0 - 200.0);
childRect = tester.getRect(find.byKey(child1Key));
expect(childRect.size.width, equals(100.0));
expect(childRect.size.height, equals(100.0));
expect(childRect.right, 800.0 - 100.0);
childRect = tester.getRect(find.byKey(child2Key));
expect(childRect.size.width, equals(100.0));
expect(childRect.size.height, equals(100.0));
expect(childRect.right, 800.0);
});
});
group('button properties override ButtonTheme', () {
testWidgets('default button properties override ButtonTheme properties', (WidgetTester tester) async {
late BuildContext capturedContext;
await tester.pumpWidget(
MaterialApp(
home: ButtonBar(
children: <Widget>[
Builder(builder: (BuildContext context) {
capturedContext = context;
return Container();
}),
],
),
),
);
final ButtonThemeData buttonTheme = ButtonTheme.of(capturedContext);
expect(buttonTheme.textTheme, equals(ButtonTextTheme.primary));
expect(buttonTheme.minWidth, equals(64.0));
expect(buttonTheme.height, equals(36.0));
expect(buttonTheme.padding, equals(const EdgeInsets.symmetric(horizontal: 8.0)));
expect(buttonTheme.alignedDropdown, equals(false));
expect(buttonTheme.layoutBehavior, equals(ButtonBarLayoutBehavior.padded));
});
testWidgets('ButtonBarTheme button properties override defaults and ButtonTheme properties', (WidgetTester tester) async {
late BuildContext capturedContext;
await tester.pumpWidget(
MaterialApp(
home: ButtonBarTheme(
data: const ButtonBarThemeData(
buttonTextTheme: ButtonTextTheme.primary,
buttonMinWidth: 42.0,
buttonHeight: 84.0,
buttonPadding: EdgeInsets.fromLTRB(10, 20, 30, 40),
buttonAlignedDropdown: true,
layoutBehavior: ButtonBarLayoutBehavior.constrained,
),
child: ButtonBar(
children: <Widget>[
Builder(builder: (BuildContext context) {
capturedContext = context;
return Container();
}),
],
),
),
),
);
final ButtonThemeData buttonTheme = ButtonTheme.of(capturedContext);
expect(buttonTheme.textTheme, equals(ButtonTextTheme.primary));
expect(buttonTheme.minWidth, equals(42.0));
expect(buttonTheme.height, equals(84.0));
expect(buttonTheme.padding, equals(const EdgeInsets.fromLTRB(10, 20, 30, 40)));
expect(buttonTheme.alignedDropdown, equals(true));
expect(buttonTheme.layoutBehavior, equals(ButtonBarLayoutBehavior.constrained));
});
testWidgets('ButtonBar button properties override ButtonBarTheme, defaults and ButtonTheme properties', (WidgetTester tester) async {
late BuildContext capturedContext;
await tester.pumpWidget(
MaterialApp(
home: ButtonBarTheme(
data: const ButtonBarThemeData(
buttonTextTheme: ButtonTextTheme.accent,
buttonMinWidth: 4242.0,
buttonHeight: 8484.0,
buttonPadding: EdgeInsets.fromLTRB(50, 60, 70, 80),
buttonAlignedDropdown: false,
layoutBehavior: ButtonBarLayoutBehavior.padded,
),
child: ButtonBar(
buttonTextTheme: ButtonTextTheme.primary,
buttonMinWidth: 42.0,
buttonHeight: 84.0,
buttonPadding: const EdgeInsets.fromLTRB(10, 20, 30, 40),
buttonAlignedDropdown: true,
layoutBehavior: ButtonBarLayoutBehavior.constrained,
children: <Widget>[
Builder(builder: (BuildContext context) {
capturedContext = context;
return Container();
}),
],
),
),
),
);
final ButtonThemeData buttonTheme = ButtonTheme.of(capturedContext);
expect(buttonTheme.textTheme, equals(ButtonTextTheme.primary));
expect(buttonTheme.minWidth, equals(42.0));
expect(buttonTheme.height, equals(84.0));
expect(buttonTheme.padding, equals(const EdgeInsets.fromLTRB(10, 20, 30, 40)));
expect(buttonTheme.alignedDropdown, equals(true));
expect(buttonTheme.layoutBehavior, equals(ButtonBarLayoutBehavior.constrained));
});
});
group('layoutBehavior', () {
testWidgets('ButtonBar has a min height of 52 when using ButtonBarLayoutBehavior.constrained', (WidgetTester tester) async {
await tester.pumpWidget(
const SingleChildScrollView(
child: ListBody(
children: <Widget>[
Directionality(
textDirection: TextDirection.ltr,
child: ButtonBar(
layoutBehavior: ButtonBarLayoutBehavior.constrained,
children: <Widget>[
SizedBox(width: 10.0, height: 10.0),
],
),
),
],
),
),
);
final Finder buttonBar = find.byType(ButtonBar);
expect(tester.getBottomRight(buttonBar).dy - tester.getTopRight(buttonBar).dy, 52.0);
});
testWidgets('ButtonBar has padding applied when using ButtonBarLayoutBehavior.padded', (WidgetTester tester) async {
await tester.pumpWidget(
const SingleChildScrollView(
child: ListBody(
children: <Widget>[
Directionality(
textDirection: TextDirection.ltr,
child: ButtonBar(
layoutBehavior: ButtonBarLayoutBehavior.padded,
children: <Widget>[
SizedBox(width: 10.0, height: 10.0),
],
),
),
],
),
),
);
final Finder buttonBar = find.byType(ButtonBar);
expect(tester.getBottomRight(buttonBar).dy - tester.getTopRight(buttonBar).dy, 26.0);
});
});
group("ButtonBar's children wrap when they overflow horizontally", () {
testWidgets("ButtonBar's children wrap when buttons overflow", (WidgetTester tester) async {
final Key keyOne = UniqueKey();
final Key keyTwo = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: ButtonBar(
children: <Widget>[
SizedBox(key: keyOne, height: 50.0, width: 800.0),
SizedBox(key: keyTwo, height: 50.0, width: 800.0),
],
),
),
);
// Second [Container] should wrap around to the next column since
// they take up max width constraint.
final Rect containerOneRect = tester.getRect(find.byKey(keyOne));
final Rect containerTwoRect = tester.getRect(find.byKey(keyTwo));
expect(containerOneRect.bottom, containerTwoRect.top);
expect(containerOneRect.left, containerTwoRect.left);
});
testWidgets(
"ButtonBar's children overflow defaults - MainAxisAlignment.end", (WidgetTester tester) async {
final Key keyOne = UniqueKey();
final Key keyTwo = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: ButtonBar(
// Set padding to zero to align buttons with edge of button bar.
buttonPadding: EdgeInsets.zero,
children: <Widget>[
SizedBox(key: keyOne, height: 50.0, width: 500.0),
SizedBox(key: keyTwo, height: 50.0, width: 500.0),
],
),
),
);
final Rect buttonBarRect = tester.getRect(find.byType(ButtonBar));
final Rect containerOneRect = tester.getRect(find.byKey(keyOne));
final Rect containerTwoRect = tester.getRect(find.byKey(keyTwo));
// Second [Container] should wrap around to the next row.
expect(containerOneRect.bottom, containerTwoRect.top);
// Second [Container] should align to the start of the ButtonBar.
expect(containerOneRect.right, containerTwoRect.right);
expect(containerOneRect.right, buttonBarRect.right);
},
);
testWidgets("ButtonBar's children overflow - MainAxisAlignment.start", (WidgetTester tester) async {
final Key keyOne = UniqueKey();
final Key keyTwo = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: ButtonBar(
alignment: MainAxisAlignment.start,
// Set padding to zero to align buttons with edge of button bar.
buttonPadding: EdgeInsets.zero,
children: <Widget>[
SizedBox(key: keyOne, height: 50.0, width: 500.0),
SizedBox(key: keyTwo, height: 50.0, width: 500.0),
],
),
),
);
final Rect buttonBarRect = tester.getRect(find.byType(ButtonBar));
final Rect containerOneRect = tester.getRect(find.byKey(keyOne));
final Rect containerTwoRect = tester.getRect(find.byKey(keyTwo));
// Second [Container] should wrap around to the next row.
expect(containerOneRect.bottom, containerTwoRect.top);
// [Container]s should align to the end of the ButtonBar.
expect(containerOneRect.left, containerTwoRect.left);
expect(containerOneRect.left, buttonBarRect.left);
});
testWidgets("ButtonBar's children overflow - MainAxisAlignment.center", (WidgetTester tester) async {
final Key keyOne = UniqueKey();
final Key keyTwo = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: ButtonBar(
alignment: MainAxisAlignment.center,
// Set padding to zero to align buttons with edge of button bar.
buttonPadding: EdgeInsets.zero,
children: <Widget>[
SizedBox(key: keyOne, height: 50.0, width: 500.0),
SizedBox(key: keyTwo, height: 50.0, width: 500.0),
],
),
),
);
final Rect buttonBarRect = tester.getRect(find.byType(ButtonBar));
final Rect containerOneRect = tester.getRect(find.byKey(keyOne));
final Rect containerTwoRect = tester.getRect(find.byKey(keyTwo));
// Second [Container] should wrap around to the next row.
expect(containerOneRect.bottom, containerTwoRect.top);
// [Container]s should center themselves in the ButtonBar.
expect(containerOneRect.center.dx, containerTwoRect.center.dx);
expect(containerOneRect.center.dx, buttonBarRect.center.dx);
});
testWidgets(
"ButtonBar's children default to MainAxisAlignment.start for horizontal "
'alignment when overflowing in spaceBetween, spaceAround and spaceEvenly '
'cases when overflowing.', (WidgetTester tester) async {
final Key keyOne = UniqueKey();
final Key keyTwo = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: ButtonBar(
alignment: MainAxisAlignment.spaceEvenly,
// Set padding to zero to align buttons with edge of button bar.
buttonPadding: EdgeInsets.zero,
children: <Widget>[
SizedBox(key: keyOne, height: 50.0, width: 500.0),
SizedBox(key: keyTwo, height: 50.0, width: 500.0),
],
),
),
);
Rect buttonBarRect = tester.getRect(find.byType(ButtonBar));
Rect containerOneRect = tester.getRect(find.byKey(keyOne));
Rect containerTwoRect = tester.getRect(find.byKey(keyTwo));
// Second [Container] should wrap around to the next row.
expect(containerOneRect.bottom, containerTwoRect.top);
// Should align horizontally to the start of the button bar.
expect(containerOneRect.left, containerTwoRect.left);
expect(containerOneRect.left, buttonBarRect.left);
await tester.pumpWidget(
MaterialApp(
home: ButtonBar(
alignment: MainAxisAlignment.spaceAround,
// Set padding to zero to align buttons with edge of button bar.
buttonPadding: EdgeInsets.zero,
children: <Widget>[
SizedBox(key: keyOne, height: 50.0, width: 500.0),
SizedBox(key: keyTwo, height: 50.0, width: 500.0),
],
),
),
);
buttonBarRect = tester.getRect(find.byType(ButtonBar));
containerOneRect = tester.getRect(find.byKey(keyOne));
containerTwoRect = tester.getRect(find.byKey(keyTwo));
// Second [Container] should wrap around to the next row.
expect(containerOneRect.bottom, containerTwoRect.top);
// Should align horizontally to the start of the button bar.
expect(containerOneRect.left, containerTwoRect.left);
expect(containerOneRect.left, buttonBarRect.left);
},
);
testWidgets(
"ButtonBar's children respects verticalDirection when overflowing",
(WidgetTester tester) async {
final Key keyOne = UniqueKey();
final Key keyTwo = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: ButtonBar(
alignment: MainAxisAlignment.center,
// Set padding to zero to align buttons with edge of button bar.
buttonPadding: EdgeInsets.zero,
// Set the vertical direction to start from the bottom and lay
// out upwards.
overflowDirection: VerticalDirection.up,
children: <Widget>[
SizedBox(key: keyOne, height: 50.0, width: 500.0),
SizedBox(key: keyTwo, height: 50.0, width: 500.0),
],
),
),
);
final Rect containerOneRect = tester.getRect(find.byKey(keyOne));
final Rect containerTwoRect = tester.getRect(find.byKey(keyTwo));
// Second [Container] should appear above first container.
expect(containerTwoRect.bottom, lessThanOrEqualTo(containerOneRect.top));
},
);
testWidgets(
'ButtonBar has no spacing by default when overflowing',
(WidgetTester tester) async {
final Key keyOne = UniqueKey();
final Key keyTwo = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: ButtonBar(
alignment: MainAxisAlignment.center,
// Set padding to zero to align buttons with edge of button bar.
buttonPadding: EdgeInsets.zero,
children: <Widget>[
SizedBox(key: keyOne, height: 50.0, width: 500.0),
SizedBox(key: keyTwo, height: 50.0, width: 500.0),
],
),
),
);
final Rect containerOneRect = tester.getRect(find.byKey(keyOne));
final Rect containerTwoRect = tester.getRect(find.byKey(keyTwo));
expect(containerOneRect.bottom, containerTwoRect.top);
},
);
testWidgets(
"ButtonBar's children respects overflowButtonSpacing when overflowing",
(WidgetTester tester) async {
final Key keyOne = UniqueKey();
final Key keyTwo = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: ButtonBar(
alignment: MainAxisAlignment.center,
// Set padding to zero to align buttons with edge of button bar.
buttonPadding: EdgeInsets.zero,
// Set the overflow button spacing to ensure add some space between
// buttons in an overflow case.
overflowButtonSpacing: 10.0,
children: <Widget>[
SizedBox(key: keyOne, height: 50.0, width: 500.0),
SizedBox(key: keyTwo, height: 50.0, width: 500.0),
],
),
),
);
final Rect containerOneRect = tester.getRect(find.byKey(keyOne));
final Rect containerTwoRect = tester.getRect(find.byKey(keyTwo));
expect(containerOneRect.bottom, containerTwoRect.top - 10.0);
},
);
});
testWidgets('_RenderButtonBarRow.constraints does not work before layout', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(home: ButtonBar()),
duration: Duration.zero,
phase: EnginePhase.build,
);
final Finder buttonBar = find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_ButtonBarRow');
final RenderBox renderButtonBar = tester.renderObject(buttonBar) as RenderBox;
expect(renderButtonBar.debugNeedsLayout, isTrue);
expect(() => renderButtonBar.constraints, throwsStateError);
});
}
| flutter/packages/flutter/test/material/button_bar_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/button_bar_test.dart",
"repo_id": "flutter",
"token_count": 11105
} | 837 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@TestOn('!chrome')
library;
import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:vector_math/vector_math_64.dart' show Matrix3;
import 'data_table_test_utils.dart';
void main() {
testWidgets('DataTable control test', (WidgetTester tester) async {
final List<String> log = <String>[];
Widget buildTable({ int? sortColumnIndex, bool sortAscending = true }) {
return DataTable(
sortColumnIndex: sortColumnIndex,
sortAscending: sortAscending,
onSelectAll: (bool? value) {
log.add('select-all: $value');
},
columns: <DataColumn>[
const DataColumn(
label: Text('Name'),
tooltip: 'Name',
),
DataColumn(
label: const Text('Calories'),
tooltip: 'Calories',
numeric: true,
onSort: (int columnIndex, bool ascending) {
log.add('column-sort: $columnIndex $ascending');
},
),
],
rows: kDesserts.map<DataRow>((Dessert dessert) {
return DataRow(
key: ValueKey<String>(dessert.name),
onSelectChanged: (bool? selected) {
log.add('row-selected: ${dessert.name}');
},
onLongPress: () {
log.add('onLongPress: ${dessert.name}');
},
cells: <DataCell>[
DataCell(
Text(dessert.name),
),
DataCell(
Text('${dessert.calories}'),
showEditIcon: true,
onTap: () {
log.add('cell-tap: ${dessert.calories}');
},
onDoubleTap: () {
log.add('cell-doubleTap: ${dessert.calories}');
},
onLongPress: () {
log.add('cell-longPress: ${dessert.calories}');
},
onTapCancel: () {
log.add('cell-tapCancel: ${dessert.calories}');
},
onTapDown: (TapDownDetails details) {
log.add('cell-tapDown: ${dessert.calories}');
},
),
],
);
}).toList(),
);
}
await tester.pumpWidget(MaterialApp(
home: Material(child: buildTable()),
));
await tester.tap(find.byType(Checkbox).first);
expect(log, <String>['select-all: true']);
log.clear();
await tester.tap(find.text('Cupcake'));
expect(log, <String>['row-selected: Cupcake']);
log.clear();
await tester.longPress(find.text('Cupcake'));
expect(log, <String>['onLongPress: Cupcake']);
log.clear();
await tester.tap(find.text('Calories'));
expect(log, <String>['column-sort: 1 true']);
log.clear();
await tester.pumpWidget(MaterialApp(
home: Material(child: buildTable(sortColumnIndex: 1)),
));
await tester.pumpAndSettle(const Duration(milliseconds: 200));
await tester.tap(find.text('Calories'));
expect(log, <String>['column-sort: 1 false']);
log.clear();
await tester.pumpWidget(MaterialApp(
home: Material(child: buildTable(sortColumnIndex: 1, sortAscending: false)),
));
await tester.pumpAndSettle(const Duration(milliseconds: 200));
await tester.tap(find.text('375'));
await tester.pump(const Duration(milliseconds: 100));
await tester.tap(find.text('375'));
expect(log, <String>['cell-doubleTap: 375']);
log.clear();
await tester.longPress(find.text('375'));
// The tap down is triggered on gesture down.
// Then, the cancel is triggered when the gesture arena
// recognizes that the long press overrides the tap event
// so it triggers a tap cancel, followed by the long press.
expect(log,<String>['cell-tapDown: 375' ,'cell-tapCancel: 375', 'cell-longPress: 375']);
log.clear();
TestGesture gesture = await tester.startGesture(
tester.getRect(find.text('375')).center,
);
await tester.pump(const Duration(milliseconds: 100));
// onTapDown callback is registered.
expect(log, equals(<String>['cell-tapDown: 375']));
await gesture.up();
await tester.pump(const Duration(seconds: 1));
// onTap callback is registered after the gesture is removed.
expect(log, equals(<String>['cell-tapDown: 375', 'cell-tap: 375']));
log.clear();
// dragging off the bounds of the cell calls the cancel callback
gesture = await tester.startGesture(tester.getRect(find.text('375')).center);
await tester.pump(const Duration(milliseconds: 100));
await gesture.moveBy(const Offset(0.0, 200.0));
await gesture.cancel();
expect(log, equals(<String>['cell-tapDown: 375', 'cell-tapCancel: 375']));
log.clear();
await tester.tap(find.byType(Checkbox).last);
expect(log, <String>['row-selected: KitKat']);
log.clear();
});
testWidgets('DataTable control test - tristate', (WidgetTester tester) async {
final List<String> log = <String>[];
const int numItems = 3;
Widget buildTable(List<bool> selected, {int? disabledIndex}) {
return DataTable(
onSelectAll: (bool? value) {
log.add('select-all: $value');
},
columns: const <DataColumn>[
DataColumn(
label: Text('Name'),
tooltip: 'Name',
),
],
rows: List<DataRow>.generate(
numItems,
(int index) => DataRow(
cells: <DataCell>[DataCell(Text('Row $index'))],
selected: selected[index],
onSelectChanged: index == disabledIndex ? null : (bool? value) {
log.add('row-selected: $index');
},
),
),
);
}
// Tapping the parent checkbox when no rows are selected, selects all.
await tester.pumpWidget(MaterialApp(
home: Material(child: buildTable(<bool>[false, false, false])),
));
await tester.tap(find.byType(Checkbox).first);
expect(log, <String>['select-all: true']);
log.clear();
// Tapping the parent checkbox when some rows are selected, selects all.
await tester.pumpWidget(MaterialApp(
home: Material(child: buildTable(<bool>[true, false, true])),
));
await tester.tap(find.byType(Checkbox).first);
expect(log, <String>['select-all: true']);
log.clear();
// Tapping the parent checkbox when all rows are selected, deselects all.
await tester.pumpWidget(MaterialApp(
home: Material(child: buildTable(<bool>[true, true, true])),
));
await tester.tap(find.byType(Checkbox).first);
expect(log, <String>['select-all: false']);
log.clear();
// Tapping the parent checkbox when all rows are selected and one is
// disabled, deselects all.
await tester.pumpWidget(MaterialApp(
home: Material(
child: buildTable(
<bool>[true, true, false],
disabledIndex: 2,
),
),
));
await tester.tap(find.byType(Checkbox).first);
expect(log, <String>['select-all: false']);
log.clear();
});
testWidgets('DataTable control test - no checkboxes', (WidgetTester tester) async {
final List<String> log = <String>[];
Widget buildTable({ bool checkboxes = false }) {
return DataTable(
showCheckboxColumn: checkboxes,
onSelectAll: (bool? value) {
log.add('select-all: $value');
},
columns: const <DataColumn>[
DataColumn(
label: Text('Name'),
tooltip: 'Name',
),
DataColumn(
label: Text('Calories'),
tooltip: 'Calories',
numeric: true,
),
],
rows: kDesserts.map<DataRow>((Dessert dessert) {
return DataRow(
key: ValueKey<String>(dessert.name),
onSelectChanged: (bool? selected) {
log.add('row-selected: ${dessert.name}');
},
cells: <DataCell>[
DataCell(
Text(dessert.name),
),
DataCell(
Text('${dessert.calories}'),
showEditIcon: true,
onTap: () {
log.add('cell-tap: ${dessert.calories}');
},
),
],
);
}).toList(),
);
}
await tester.pumpWidget(MaterialApp(
home: Material(child: buildTable()),
));
expect(find.byType(Checkbox), findsNothing);
await tester.tap(find.text('Cupcake'));
expect(log, <String>['row-selected: Cupcake']);
log.clear();
await tester.pumpWidget(MaterialApp(
home: Material(child: buildTable(checkboxes: true)),
));
await tester.pumpAndSettle(const Duration(milliseconds: 200));
final Finder checkboxes = find.byType(Checkbox);
expect(checkboxes, findsNWidgets(11));
await tester.tap(checkboxes.first);
expect(log, <String>['select-all: true']);
log.clear();
});
testWidgets('DataTable overflow test - header', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: DataTable(
headingTextStyle: const TextStyle(
fontSize: 14.0,
letterSpacing: 0.0, // Will overflow if letter spacing is larger than 0.0.
),
columns: <DataColumn>[
DataColumn(
label: Text('X' * 2000),
),
],
rows: const <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(
Text('X'),
),
],
),
],
),
),
),
);
expect(tester.renderObject<RenderBox>(find.byType(Text).first).size.width, greaterThan(800.0));
expect(tester.renderObject<RenderBox>(find.byType(Row).first).size.width, greaterThan(800.0));
expect(tester.takeException(), isNull); // column overflows table, but text doesn't overflow cell
});
testWidgets('DataTable overflow test - header with spaces', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: DataTable(
columns: <DataColumn>[
DataColumn(
label: Text('X ' * 2000), // has soft wrap points, but they should be ignored
),
],
rows: const <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(
Text('X'),
),
],
),
],
),
),
),
);
expect(tester.renderObject<RenderBox>(find.byType(Text).first).size.width, greaterThan(800.0));
expect(tester.renderObject<RenderBox>(find.byType(Row).first).size.width, greaterThan(800.0));
expect(tester.takeException(), isNull); // column overflows table, but text doesn't overflow cell
}, skip: true); // https://github.com/flutter/flutter/issues/13512
testWidgets('DataTable overflow test', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text('X'),
),
],
rows: <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(
Text('X' * 2000),
),
],
),
],
),
),
),
);
expect(tester.renderObject<RenderBox>(find.byType(Text).first).size.width, lessThan(800.0));
expect(tester.renderObject<RenderBox>(find.byType(Row).first).size.width, greaterThan(800.0));
expect(tester.takeException(), isNull); // cell overflows table, but text doesn't overflow cell
});
testWidgets('DataTable overflow test', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text('X'),
),
],
rows: <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(
Text('X ' * 2000), // wraps
),
],
),
],
),
),
),
);
expect(tester.renderObject<RenderBox>(find.byType(Text).first).size.width, lessThan(800.0));
expect(tester.renderObject<RenderBox>(find.byType(Row).first).size.width, lessThan(800.0));
expect(tester.takeException(), isNull);
});
testWidgets('DataTable column onSort test', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text('Dessert'),
),
],
rows: const <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(
Text('Lollipop'), // wraps
),
],
),
],
),
),
),
);
await tester.tap(find.text('Dessert'));
await tester.pump();
expect(tester.takeException(), isNull);
});
testWidgets('DataTable sort indicator orientation', (WidgetTester tester) async {
Widget buildTable({ bool sortAscending = true }) {
return DataTable(
sortColumnIndex: 0,
sortAscending: sortAscending,
columns: <DataColumn>[
DataColumn(
label: const Text('Name'),
tooltip: 'Name',
onSort: (int columnIndex, bool ascending) {},
),
],
rows: kDesserts.map<DataRow>((Dessert dessert) {
return DataRow(
cells: <DataCell>[
DataCell(
Text(dessert.name),
),
],
);
}).toList(),
);
}
// Check for ascending list
await tester.pumpWidget(MaterialApp(
home: Material(child: buildTable()),
));
final Finder iconFinder = find.descendant(
of: find.byType(DataTable),
matching: find.widgetWithIcon(Transform, Icons.arrow_upward),
);
// The `tester.widget` ensures that there is exactly one upward arrow.
Transform transformOfArrow = tester.widget<Transform>(iconFinder);
expect(
transformOfArrow.transform.getRotation(),
equals(Matrix3.identity()),
);
// Check for descending list.
await tester.pumpWidget(MaterialApp(
home: Material(child: buildTable(sortAscending: false)),
));
await tester.pumpAndSettle();
// The `tester.widget` ensures that there is exactly one upward arrow.
transformOfArrow = tester.widget<Transform>(iconFinder);
expect(
transformOfArrow.transform.getRotation(),
equals(Matrix3.rotationZ(math.pi)),
);
});
testWidgets('DataTable sort indicator orientation does not change on state update', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/43724
Widget buildTable({String title = 'Name1'}) {
return DataTable(
sortColumnIndex: 0,
columns: <DataColumn>[
DataColumn(
label: Text(title),
tooltip: 'Name',
onSort: (int columnIndex, bool ascending) {},
),
],
rows: kDesserts.map<DataRow>((Dessert dessert) {
return DataRow(
cells: <DataCell>[
DataCell(
Text(dessert.name),
),
],
);
}).toList(),
);
}
// Check for ascending list
await tester.pumpWidget(MaterialApp(
home: Material(child: buildTable()),
));
final Finder iconFinder = find.descendant(
of: find.byType(DataTable),
matching: find.widgetWithIcon(Transform, Icons.arrow_upward),
);
// The `tester.widget` ensures that there is exactly one upward arrow.
Transform transformOfArrow = tester.widget<Transform>(iconFinder);
expect(
transformOfArrow.transform.getRotation(),
equals(Matrix3.identity()),
);
// Cause a rebuild by updating the widget
await tester.pumpWidget(MaterialApp(
home: Material(child: buildTable(title: 'Name2')),
));
await tester.pumpAndSettle();
// The `tester.widget` ensures that there is exactly one upward arrow.
transformOfArrow = tester.widget<Transform>(iconFinder);
expect(
transformOfArrow.transform.getRotation(),
equals(Matrix3.identity()), // Should not have changed
);
});
testWidgets('DataTable sort indicator orientation does not change on state update - reverse', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/43724
Widget buildTable({String title = 'Name1'}) {
return DataTable(
sortColumnIndex: 0,
sortAscending: false,
columns: <DataColumn>[
DataColumn(
label: Text(title),
tooltip: 'Name',
onSort: (int columnIndex, bool ascending) {},
),
],
rows: kDesserts.map<DataRow>((Dessert dessert) {
return DataRow(
cells: <DataCell>[
DataCell(
Text(dessert.name),
),
],
);
}).toList(),
);
}
// Check for ascending list
await tester.pumpWidget(MaterialApp(
home: Material(child: buildTable()),
));
final Finder iconFinder = find.descendant(
of: find.byType(DataTable),
matching: find.widgetWithIcon(Transform, Icons.arrow_upward),
);
// The `tester.widget` ensures that there is exactly one upward arrow.
Transform transformOfArrow = tester.widget<Transform>(iconFinder);
expect(
transformOfArrow.transform.getRotation(),
equals(Matrix3.rotationZ(math.pi)),
);
// Cause a rebuild by updating the widget
await tester.pumpWidget(MaterialApp(
home: Material(child: buildTable(title: 'Name2')),
));
await tester.pumpAndSettle();
// The `tester.widget` ensures that there is exactly one upward arrow.
transformOfArrow = tester.widget<Transform>(iconFinder);
expect(
transformOfArrow.transform.getRotation(),
equals(Matrix3.rotationZ(math.pi)), // Should not have changed
);
});
testWidgets('DataTable row onSelectChanged test', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text('Dessert'),
),
],
rows: const <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(
Text('Lollipop'), // wraps
),
],
),
],
),
),
),
);
await tester.tap(find.text('Lollipop'));
await tester.pump();
expect(tester.takeException(), isNull);
});
testWidgets('DataTable custom row height', (WidgetTester tester) async {
Widget buildCustomTable({
int? sortColumnIndex,
bool sortAscending = true,
double? dataRowMinHeight,
double? dataRowMaxHeight,
double headingRowHeight = 56.0,
}) {
return DataTable(
sortColumnIndex: sortColumnIndex,
sortAscending: sortAscending,
onSelectAll: (bool? value) {},
dataRowMinHeight: dataRowMinHeight,
dataRowMaxHeight: dataRowMaxHeight,
headingRowHeight: headingRowHeight,
columns: <DataColumn>[
const DataColumn(
label: Text('Name'),
tooltip: 'Name',
),
DataColumn(
label: const Text('Calories'),
tooltip: 'Calories',
numeric: true,
onSort: (int columnIndex, bool ascending) {},
),
],
rows: kDesserts.map<DataRow>((Dessert dessert) {
return DataRow(
key: ValueKey<String>(dessert.name),
onSelectChanged: (bool? selected) {},
cells: <DataCell>[
DataCell(
Text(dessert.name),
),
DataCell(
Text('${dessert.calories}'),
showEditIcon: true,
onTap: () {},
),
],
);
}).toList(),
);
}
// DEFAULT VALUES
await tester.pumpWidget(MaterialApp(
home: Material(
child: DataTable(
onSelectAll: (bool? value) {},
columns: <DataColumn>[
const DataColumn(
label: Text('Name'),
tooltip: 'Name',
),
DataColumn(
label: const Text('Calories'),
tooltip: 'Calories',
numeric: true,
onSort: (int columnIndex, bool ascending) {},
),
],
rows: kDesserts.map<DataRow>((Dessert dessert) {
return DataRow(
key: ValueKey<String>(dessert.name),
onSelectChanged: (bool? selected) {},
cells: <DataCell>[
DataCell(
Text(dessert.name),
),
DataCell(
Text('${dessert.calories}'),
showEditIcon: true,
onTap: () {},
),
],
);
}).toList(),
),
),
));
// The finder matches with the Container of the cell content, as well as the
// Container wrapping the whole table. The first one is used to test row
// heights.
Finder findFirstContainerFor(String text) => find.widgetWithText(Container, text).first;
expect(tester.getSize(findFirstContainerFor('Name')).height, 56.0);
expect(tester.getSize(findFirstContainerFor('Frozen yogurt')).height, kMinInteractiveDimension);
// CUSTOM VALUES
await tester.pumpWidget(MaterialApp(
home: Material(child: buildCustomTable(headingRowHeight: 48.0)),
));
expect(tester.getSize(findFirstContainerFor('Name')).height, 48.0);
await tester.pumpWidget(MaterialApp(
home: Material(child: buildCustomTable(headingRowHeight: 64.0)),
));
expect(tester.getSize(findFirstContainerFor('Name')).height, 64.0);
await tester.pumpWidget(MaterialApp(
home: Material(child: buildCustomTable(dataRowMinHeight: 30.0, dataRowMaxHeight: 30.0)),
));
expect(tester.getSize(findFirstContainerFor('Frozen yogurt')).height, 30.0);
await tester.pumpWidget(MaterialApp(
home: Material(child: buildCustomTable(dataRowMinHeight: 0.0, dataRowMaxHeight: double.infinity)),
));
expect(tester.getSize(findFirstContainerFor('Frozen yogurt')).height, greaterThan(0.0));
});
testWidgets('DataTable custom row height one row taller than others', (WidgetTester tester) async {
const String multilineText = 'Line one.\nLine two.\nLine three.\nLine four.';
Widget buildCustomTable({
double? dataRowMinHeight,
double? dataRowMaxHeight,
}) {
return DataTable(
dataRowMinHeight: dataRowMinHeight,
dataRowMaxHeight: dataRowMaxHeight,
columns: const <DataColumn>[
DataColumn(
label: Text('SingleRowColumn'),
),
DataColumn(
label: Text('MultiRowColumn'),
),
],
rows: const <DataRow>[
DataRow(cells: <DataCell>[
DataCell(Text('Data')),
DataCell(Column(children: <Widget>[
Text(multilineText),
])),
]),
],
);
}
Finder findFirstContainerFor(String text) => find.widgetWithText(Container, text).first;
await tester.pumpWidget(MaterialApp(
home: Material(child: buildCustomTable(dataRowMinHeight: 0.0, dataRowMaxHeight: double.infinity)),
));
final double singleLineRowHeight = tester.getSize(findFirstContainerFor('Data')).height;
final double multilineRowHeight = tester.getSize(findFirstContainerFor(multilineText)).height;
expect(multilineRowHeight, greaterThan(singleLineRowHeight));
});
testWidgets('DataTable custom row height - separate test for deprecated dataRowHeight', (WidgetTester tester) async {
Widget buildCustomTable({
double dataRowHeight = 48.0,
}) {
return DataTable(
onSelectAll: (bool? value) {},
dataRowHeight: dataRowHeight,
columns: <DataColumn>[
const DataColumn(
label: Text('Name'),
tooltip: 'Name',
),
DataColumn(
label: const Text('Calories'),
tooltip: 'Calories',
numeric: true,
onSort: (int columnIndex, bool ascending) {},
),
],
rows: kDesserts.map<DataRow>((Dessert dessert) {
return DataRow(
key: ValueKey<String>(dessert.name),
onSelectChanged: (bool? selected) {},
cells: <DataCell>[
DataCell(
Text(dessert.name),
),
DataCell(
Text('${dessert.calories}'),
showEditIcon: true,
onTap: () {},
),
],
);
}).toList(),
);
}
// The finder matches with the Container of the cell content, as well as the
// Container wrapping the whole table. The first one is used to test row
// heights.
Finder findFirstContainerFor(String text) => find.widgetWithText(Container, text).first;
// CUSTOM VALUES
await tester.pumpWidget(MaterialApp(
home: Material(child: buildCustomTable(dataRowHeight: 30.0)),
));
expect(tester.getSize(findFirstContainerFor('Frozen yogurt')).height, 30.0);
});
testWidgets('DataTable custom horizontal padding - checkbox', (WidgetTester tester) async {
const double defaultHorizontalMargin = 24.0;
const double defaultColumnSpacing = 56.0;
const double customHorizontalMargin = 10.0;
const double customColumnSpacing = 15.0;
Finder cellContent;
Finder checkbox;
Finder padding;
Widget buildDefaultTable({
int? sortColumnIndex,
bool sortAscending = true,
}) {
return DataTable(
sortColumnIndex: sortColumnIndex,
sortAscending: sortAscending,
onSelectAll: (bool? value) {},
columns: <DataColumn>[
const DataColumn(
label: Text('Name'),
tooltip: 'Name',
),
DataColumn(
label: const Text('Calories'),
tooltip: 'Calories',
numeric: true,
onSort: (int columnIndex, bool ascending) {},
),
DataColumn(
label: const Text('Fat'),
tooltip: 'Fat',
numeric: true,
onSort: (int columnIndex, bool ascending) {},
),
],
rows: kDesserts.map<DataRow>((Dessert dessert) {
return DataRow(
key: ValueKey<String>(dessert.name),
onSelectChanged: (bool? selected) {},
cells: <DataCell>[
DataCell(
Text(dessert.name),
),
DataCell(
Text('${dessert.calories}'),
showEditIcon: true,
onTap: () {},
),
DataCell(
Text('${dessert.fat}'),
showEditIcon: true,
onTap: () {},
),
],
);
}).toList(),
);
}
// DEFAULT VALUES
await tester.pumpWidget(MaterialApp(
home: Material(child: buildDefaultTable()),
));
// default checkbox padding
checkbox = find.byType(Checkbox).first;
padding = find.ancestor(of: checkbox, matching: find.byType(Padding));
expect(
tester.getRect(checkbox).left - tester.getRect(padding).left,
defaultHorizontalMargin,
);
expect(
tester.getRect(padding).right - tester.getRect(checkbox).right,
defaultHorizontalMargin / 2,
);
// default first column padding
padding = find.widgetWithText(Padding, 'Frozen yogurt');
cellContent = find.widgetWithText(Align, 'Frozen yogurt'); // DataTable wraps its DataCells in an Align widget
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
defaultHorizontalMargin / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
defaultColumnSpacing / 2,
);
// default middle column padding
padding = find.widgetWithText(Padding, '159');
cellContent = find.widgetWithText(Align, '159');
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
defaultColumnSpacing / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
defaultColumnSpacing / 2,
);
// default last column padding
padding = find.widgetWithText(Padding, '6.0');
cellContent = find.widgetWithText(Align, '6.0');
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
defaultColumnSpacing / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
defaultHorizontalMargin,
);
Widget buildCustomTable({
int? sortColumnIndex,
bool sortAscending = true,
double? horizontalMargin,
double? columnSpacing,
}) {
return DataTable(
sortColumnIndex: sortColumnIndex,
sortAscending: sortAscending,
onSelectAll: (bool? value) {},
horizontalMargin: horizontalMargin,
columnSpacing: columnSpacing,
columns: <DataColumn>[
const DataColumn(
label: Text('Name'),
tooltip: 'Name',
),
DataColumn(
label: const Text('Calories'),
tooltip: 'Calories',
numeric: true,
onSort: (int columnIndex, bool ascending) {},
),
DataColumn(
label: const Text('Fat'),
tooltip: 'Fat',
numeric: true,
onSort: (int columnIndex, bool ascending) {},
),
],
rows: kDesserts.map<DataRow>((Dessert dessert) {
return DataRow(
key: ValueKey<String>(dessert.name),
onSelectChanged: (bool? selected) {},
cells: <DataCell>[
DataCell(
Text(dessert.name),
),
DataCell(
Text('${dessert.calories}'),
showEditIcon: true,
onTap: () {},
),
DataCell(
Text('${dessert.fat}'),
showEditIcon: true,
onTap: () {},
),
],
);
}).toList(),
);
}
// CUSTOM VALUES
await tester.pumpWidget(MaterialApp(
home: Material(child: buildCustomTable(
horizontalMargin: customHorizontalMargin,
columnSpacing: customColumnSpacing,
)),
));
// custom checkbox padding
checkbox = find.byType(Checkbox).first;
padding = find.ancestor(of: checkbox, matching: find.byType(Padding));
expect(
tester.getRect(checkbox).left - tester.getRect(padding).left,
customHorizontalMargin,
);
expect(
tester.getRect(padding).right - tester.getRect(checkbox).right,
customHorizontalMargin / 2,
);
// custom first column padding
padding = find.widgetWithText(Padding, 'Frozen yogurt').first;
cellContent = find.widgetWithText(Align, 'Frozen yogurt'); // DataTable wraps its DataCells in an Align widget
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
customHorizontalMargin / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
customColumnSpacing / 2,
);
// custom middle column padding
padding = find.widgetWithText(Padding, '159');
cellContent = find.widgetWithText(Align, '159');
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
customColumnSpacing / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
customColumnSpacing / 2,
);
// custom last column padding
padding = find.widgetWithText(Padding, '6.0');
cellContent = find.widgetWithText(Align, '6.0');
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
customColumnSpacing / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
customHorizontalMargin,
);
});
testWidgets('DataTable custom horizontal padding - no checkbox', (WidgetTester tester) async {
const double defaultHorizontalMargin = 24.0;
const double defaultColumnSpacing = 56.0;
const double customHorizontalMargin = 10.0;
const double customColumnSpacing = 15.0;
Finder cellContent;
Finder padding;
Widget buildDefaultTable({
int? sortColumnIndex,
bool sortAscending = true,
}) {
return DataTable(
sortColumnIndex: sortColumnIndex,
sortAscending: sortAscending,
columns: <DataColumn>[
const DataColumn(
label: Text('Name'),
tooltip: 'Name',
),
DataColumn(
label: const Text('Calories'),
tooltip: 'Calories',
numeric: true,
onSort: (int columnIndex, bool ascending) {},
),
DataColumn(
label: const Text('Fat'),
tooltip: 'Fat',
numeric: true,
onSort: (int columnIndex, bool ascending) {},
),
],
rows: kDesserts.map<DataRow>((Dessert dessert) {
return DataRow(
key: ValueKey<String>(dessert.name),
cells: <DataCell>[
DataCell(
Text(dessert.name),
),
DataCell(
Text('${dessert.calories}'),
showEditIcon: true,
onTap: () {},
),
DataCell(
Text('${dessert.fat}'),
showEditIcon: true,
onTap: () {},
),
],
);
}).toList(),
);
}
// DEFAULT VALUES
await tester.pumpWidget(MaterialApp(
home: Material(child: buildDefaultTable()),
));
// default first column padding
padding = find.widgetWithText(Padding, 'Frozen yogurt');
cellContent = find.widgetWithText(Align, 'Frozen yogurt'); // DataTable wraps its DataCells in an Align widget
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
defaultHorizontalMargin,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
defaultColumnSpacing / 2,
);
// default middle column padding
padding = find.widgetWithText(Padding, '159');
cellContent = find.widgetWithText(Align, '159');
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
defaultColumnSpacing / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
defaultColumnSpacing / 2,
);
// default last column padding
padding = find.widgetWithText(Padding, '6.0');
cellContent = find.widgetWithText(Align, '6.0');
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
defaultColumnSpacing / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
defaultHorizontalMargin,
);
Widget buildCustomTable({
int? sortColumnIndex,
bool sortAscending = true,
double? horizontalMargin,
double? columnSpacing,
}) {
return DataTable(
sortColumnIndex: sortColumnIndex,
sortAscending: sortAscending,
horizontalMargin: horizontalMargin,
columnSpacing: columnSpacing,
columns: <DataColumn>[
const DataColumn(
label: Text('Name'),
tooltip: 'Name',
),
DataColumn(
label: const Text('Calories'),
tooltip: 'Calories',
numeric: true,
onSort: (int columnIndex, bool ascending) {},
),
DataColumn(
label: const Text('Fat'),
tooltip: 'Fat',
numeric: true,
onSort: (int columnIndex, bool ascending) {},
),
],
rows: kDesserts.map<DataRow>((Dessert dessert) {
return DataRow(
key: ValueKey<String>(dessert.name),
cells: <DataCell>[
DataCell(
Text(dessert.name),
),
DataCell(
Text('${dessert.calories}'),
showEditIcon: true,
onTap: () {},
),
DataCell(
Text('${dessert.fat}'),
showEditIcon: true,
onTap: () {},
),
],
);
}).toList(),
);
}
// CUSTOM VALUES
await tester.pumpWidget(MaterialApp(
home: Material(child: buildCustomTable(
horizontalMargin: customHorizontalMargin,
columnSpacing: customColumnSpacing,
)),
));
// custom first column padding
padding = find.widgetWithText(Padding, 'Frozen yogurt');
cellContent = find.widgetWithText(Align, 'Frozen yogurt'); // DataTable wraps its DataCells in an Align widget
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
customHorizontalMargin,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
customColumnSpacing / 2,
);
// custom middle column padding
padding = find.widgetWithText(Padding, '159');
cellContent = find.widgetWithText(Align, '159');
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
customColumnSpacing / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
customColumnSpacing / 2,
);
// custom last column padding
padding = find.widgetWithText(Padding, '6.0');
cellContent = find.widgetWithText(Align, '6.0');
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
customColumnSpacing / 2,
);
expect(
tester.getRect(padding).right - tester.getRect(cellContent).right,
customHorizontalMargin,
);
});
testWidgets('DataTable set border width test', (WidgetTester tester) async {
const List<DataColumn> columns = <DataColumn>[
DataColumn(label: Text('column1')),
DataColumn(label: Text('column2')),
];
const List<DataCell> cells = <DataCell>[
DataCell(Text('cell1')),
DataCell(Text('cell2')),
];
const List<DataRow> rows = <DataRow>[
DataRow(cells: cells),
DataRow(cells: cells),
];
// no thickness provided - border should be default: i.e "1.0" as it
// set in DataTable constructor
await tester.pumpWidget(
MaterialApp(
home: Material(
child: DataTable(
columns: columns,
rows: rows,
),
),
),
);
Table table = tester.widget(find.byType(Table));
TableRow tableRow = table.children.last;
BoxDecoration boxDecoration = tableRow.decoration! as BoxDecoration;
expect(boxDecoration.border!.top.width, 1.0);
const double thickness = 4.2;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: DataTable(
dividerThickness: thickness,
columns: columns,
rows: rows,
),
),
),
);
table = tester.widget(find.byType(Table));
tableRow = table.children.last;
boxDecoration = tableRow.decoration! as BoxDecoration;
expect(boxDecoration.border!.top.width, thickness);
});
testWidgets('DataTable set show bottom border', (WidgetTester tester) async {
const List<DataColumn> columns = <DataColumn>[
DataColumn(label: Text('column1')),
DataColumn(label: Text('column2')),
];
const List<DataCell> cells = <DataCell>[
DataCell(Text('cell1')),
DataCell(Text('cell2')),
];
const List<DataRow> rows = <DataRow>[
DataRow(cells: cells),
DataRow(cells: cells),
];
await tester.pumpWidget(
MaterialApp(
home: Material(
child: DataTable(
showBottomBorder: true,
columns: columns,
rows: rows,
),
),
),
);
Table table = tester.widget(find.byType(Table));
TableRow tableRow = table.children.last;
BoxDecoration boxDecoration = tableRow.decoration! as BoxDecoration;
expect(boxDecoration.border!.bottom.width, 1.0);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: DataTable(
columns: columns,
rows: rows,
),
),
),
);
table = tester.widget(find.byType(Table));
tableRow = table.children.last;
boxDecoration = tableRow.decoration! as BoxDecoration;
expect(boxDecoration.border!.bottom.width, 0.0);
});
testWidgets('DataTable column heading cell - with and without sorting', (WidgetTester tester) async {
Widget buildTable({ int? sortColumnIndex, bool sortEnabled = true }) {
return DataTable(
sortColumnIndex: sortColumnIndex,
columns: <DataColumn>[
DataColumn(
label: const Expanded(child: Center(child: Text('Name'))),
tooltip: 'Name',
onSort: sortEnabled ? (_, __) {} : null,
),
],
rows: const <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(Text('A long desert name')),
],
),
],
);
}
// Start with without sorting
await tester.pumpWidget(MaterialApp(
home: Material(child: buildTable(
sortEnabled: false,
)),
));
{
final Finder nameText = find.text('Name');
expect(nameText, findsOneWidget);
final Finder nameCell = find.ancestor(of: find.text('Name'), matching: find.byType(Container)).first;
expect(tester.getCenter(nameText), equals(tester.getCenter(nameCell)));
expect(find.descendant(of: nameCell, matching: find.byType(Icon)), findsNothing);
}
// Turn on sorting
await tester.pumpWidget(MaterialApp(
home: Material(child: buildTable()),
));
{
final Finder nameText = find.text('Name');
expect(nameText, findsOneWidget);
final Finder nameCell = find.ancestor(of: find.text('Name'), matching: find.byType(Container)).first;
expect(find.descendant(of: nameCell, matching: find.byType(Icon)), findsOneWidget);
}
// Turn off sorting again
await tester.pumpWidget(MaterialApp(
home: Material(child: buildTable(
sortEnabled: false,
)),
));
{
final Finder nameText = find.text('Name');
expect(nameText, findsOneWidget);
final Finder nameCell = find.ancestor(of: find.text('Name'), matching: find.byType(Container)).first;
expect(tester.getCenter(nameText), equals(tester.getCenter(nameCell)));
expect(find.descendant(of: nameCell, matching: find.byType(Icon)), findsNothing);
}
});
testWidgets('DataTable correctly renders with a mouse', (WidgetTester tester) async {
// Regression test for a bug described in
// https://github.com/flutter/flutter/pull/43735#issuecomment-589459947
// Filed at https://github.com/flutter/flutter/issues/51152
Widget buildTable({ int? sortColumnIndex }) {
return DataTable(
sortColumnIndex: sortColumnIndex,
columns: <DataColumn>[
const DataColumn(
label: Expanded(child: Center(child: Text('column1'))),
tooltip: 'Column1',
),
DataColumn(
label: const Expanded(child: Center(child: Text('column2'))),
tooltip: 'Column2',
onSort: (_, __) {},
),
],
rows: const <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(Text('Content1')),
DataCell(Text('Content2')),
],
),
],
);
}
await tester.pumpWidget(MaterialApp(
home: Material(child: buildTable()),
));
expect(tester.renderObject(find.text('column1')).attached, true);
expect(tester.renderObject(find.text('column2')).attached, true);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: Offset.zero);
await tester.pumpAndSettle();
expect(tester.renderObject(find.text('column1')).attached, true);
expect(tester.renderObject(find.text('column2')).attached, true);
// Wait for the tooltip timer to expire to prevent it scheduling a new frame
// after the view is destroyed, which causes exceptions.
await tester.pumpAndSettle(const Duration(seconds: 1));
});
testWidgets('DataRow renders default selected row colors', (WidgetTester tester) async {
final ThemeData themeData = ThemeData.light();
Widget buildTable({bool selected = false}) {
return MaterialApp(
theme: themeData,
home: Material(
child: DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text('Column1'),
),
],
rows: <DataRow>[
DataRow(
onSelectChanged: (bool? checked) {},
selected: selected,
cells: const <DataCell>[
DataCell(Text('Content1')),
],
),
],
),
),
);
}
BoxDecoration lastTableRowBoxDecoration() {
final Table table = tester.widget(find.byType(Table));
final TableRow tableRow = table.children.last;
return tableRow.decoration! as BoxDecoration;
}
await tester.pumpWidget(buildTable());
expect(lastTableRowBoxDecoration().color, null);
await tester.pumpWidget(buildTable(selected: true));
expect(
lastTableRowBoxDecoration().color,
themeData.colorScheme.primary.withOpacity(0.08),
);
});
testWidgets('DataRow renders checkbox with colors from CheckboxTheme', (WidgetTester tester) async {
const Color fillColor = Color(0xFF00FF00);
const Color checkColor = Color(0xFF0000FF);
final ThemeData themeData = ThemeData(
checkboxTheme: const CheckboxThemeData(
fillColor: MaterialStatePropertyAll<Color?>(fillColor),
checkColor: MaterialStatePropertyAll<Color?>(checkColor),
),
);
Widget buildTable() {
return MaterialApp(
theme: themeData,
home: Material(
child: DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text('Column1'),
),
],
rows: <DataRow>[
DataRow(
selected: true,
onSelectChanged: (bool? checked) {},
cells: const <DataCell>[
DataCell(Text('Content1')),
],
),
],
),
),
);
}
await tester.pumpWidget(buildTable());
expect(
Material.of(tester.element(find.byType(Checkbox).last)),
paints
..path()
..path(color: fillColor)
..path(color: checkColor),
);
});
testWidgets('DataRow renders custom colors when selected', (WidgetTester tester) async {
const Color selectedColor = Colors.green;
const Color defaultColor = Colors.red;
Widget buildTable({bool selected = false}) {
return Material(
child: DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text('Column1'),
),
],
rows: <DataRow>[
DataRow(
selected: selected,
color: MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return selectedColor;
}
return defaultColor;
},
),
cells: const <DataCell>[
DataCell(Text('Content1')),
],
),
],
),
);
}
BoxDecoration lastTableRowBoxDecoration() {
final Table table = tester.widget(find.byType(Table));
final TableRow tableRow = table.children.last;
return tableRow.decoration! as BoxDecoration;
}
await tester.pumpWidget(MaterialApp(
home: buildTable(),
));
expect(lastTableRowBoxDecoration().color, defaultColor);
await tester.pumpWidget(MaterialApp(
home: buildTable(selected: true),
));
expect(lastTableRowBoxDecoration().color, selectedColor);
});
testWidgets('DataRow renders custom colors when disabled', (WidgetTester tester) async {
const Color disabledColor = Colors.grey;
const Color defaultColor = Colors.red;
Widget buildTable({bool disabled = false}) {
return Material(
child: DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text('Column1'),
),
],
rows: <DataRow>[
DataRow(
cells: const <DataCell>[
DataCell(Text('Content1')),
],
onSelectChanged: (bool? value) {},
),
DataRow(
color: MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return disabledColor;
}
return defaultColor;
},
),
cells: const <DataCell>[
DataCell(Text('Content2')),
],
onSelectChanged: disabled ? null : (bool? value) {},
),
],
),
);
}
BoxDecoration lastTableRowBoxDecoration() {
final Table table = tester.widget(find.byType(Table));
final TableRow tableRow = table.children.last;
return tableRow.decoration! as BoxDecoration;
}
await tester.pumpWidget(MaterialApp(
home: buildTable(),
));
expect(lastTableRowBoxDecoration().color, defaultColor);
await tester.pumpWidget(MaterialApp(
home: buildTable(disabled: true),
));
expect(lastTableRowBoxDecoration().color, disabledColor);
});
testWidgets('Material2 - DataRow renders custom colors when pressed', (WidgetTester tester) async {
const Color pressedColor = Color(0xff4caf50);
Widget buildTable() {
return DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text('Column1'),
),
],
rows: <DataRow>[
DataRow(
color: MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return pressedColor;
}
return Colors.transparent;
},
),
onSelectChanged: (bool? value) {},
cells: const <DataCell>[
DataCell(Text('Content1')),
],
),
],
);
}
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(child: buildTable()),
));
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('Content1')));
await tester.pump(const Duration(milliseconds: 200)); // splash is well underway
final RenderBox box = Material.of(tester.element(find.byType(InkWell)))as RenderBox;
expect(box, paints..circle(x: 68.0, y: 24.0, color: pressedColor));
await gesture.up();
});
testWidgets('Material3 - DataRow renders custom colors when pressed', (WidgetTester tester) async {
const Color pressedColor = Color(0xff4caf50);
Widget buildTable() {
return DataTable(
columns: const <DataColumn>[
DataColumn(
label: Text('Column1'),
),
],
rows: <DataRow>[
DataRow(
color: MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return pressedColor;
}
return Colors.transparent;
},
),
onSelectChanged: (bool? value) {},
cells: const <DataCell>[
DataCell(Text('Content1')),
],
),
],
);
}
await tester.pumpWidget(MaterialApp(
theme: ThemeData(),
home: Material(child: buildTable()),
));
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('Content1')));
await tester.pump(const Duration(milliseconds: 200)); // splash is well underway
final RenderBox box = Material.of(tester.element(find.byType(InkWell)))as RenderBox;
// Material 3 uses the InkSparkle which uses a shader, so we can't capture
// the effect with paint methods.
expect(
box,
paints
..rect()
..rect(rect: const Rect.fromLTRB(0.0, 56.0, 800.0, 104.0), color: pressedColor.withOpacity(0.0)),
);
await gesture.up();
});
testWidgets('DataTable can render inside an AlertDialog', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: AlertDialog(
content: DataTable(
columns: const <DataColumn>[
DataColumn(label: Text('Col1')),
],
rows: const <DataRow>[
DataRow(cells: <DataCell>[DataCell(Text('1'))]),
],
),
scrollable: true,
),
),
),
);
expect(tester.takeException(), isNull);
});
testWidgets('DataTable renders with border and background decoration', (WidgetTester tester) async {
const double width = 800;
const double height = 600;
const double borderHorizontal = 5.0;
const double borderVertical = 10.0;
const Color borderColor = Color(0xff2196f3);
const Color backgroundColor = Color(0xfff5f5f5);
await tester.pumpWidget(
MaterialApp(
home: DataTable(
decoration: const BoxDecoration(
color: backgroundColor,
border: Border.symmetric(
vertical: BorderSide(width: borderVertical, color: borderColor),
horizontal: BorderSide(width: borderHorizontal, color: borderColor),
),
),
columns: const <DataColumn>[
DataColumn(label: Text('Col1')),
],
rows: const <DataRow>[
DataRow(cells: <DataCell>[DataCell(Text('1'))]),
],
),
),
);
expect(
find.ancestor(of: find.byType(Table), matching: find.byType(Container)),
paints..rect(
rect: const Rect.fromLTRB(0.0, 0.0, width, height),
color: backgroundColor,
),
);
expect(
find.ancestor(of: find.byType(Table), matching: find.byType(Container)),
paints..path(color: borderColor),
);
expect(
tester.getTopLeft(find.byType(Table)),
const Offset(borderVertical, borderHorizontal),
);
expect(
tester.getBottomRight(find.byType(Table)),
const Offset(width - borderVertical, height - borderHorizontal),
);
});
testWidgets('checkboxHorizontalMargin properly applied', (WidgetTester tester) async {
const double customCheckboxHorizontalMargin = 15.0;
const double customHorizontalMargin = 10.0;
Finder cellContent;
Finder checkbox;
Finder padding;
Widget buildCustomTable({
int? sortColumnIndex,
bool sortAscending = true,
double? horizontalMargin,
double? checkboxHorizontalMargin,
}) {
return DataTable(
sortColumnIndex: sortColumnIndex,
sortAscending: sortAscending,
onSelectAll: (bool? value) {},
horizontalMargin: horizontalMargin,
checkboxHorizontalMargin: checkboxHorizontalMargin,
columns: <DataColumn>[
const DataColumn(
label: Text('Name'),
tooltip: 'Name',
),
DataColumn(
label: const Text('Calories'),
tooltip: 'Calories',
numeric: true,
onSort: (int columnIndex, bool ascending) {},
),
DataColumn(
label: const Text('Fat'),
tooltip: 'Fat',
numeric: true,
onSort: (int columnIndex, bool ascending) {},
),
],
rows: kDesserts.map<DataRow>((Dessert dessert) {
return DataRow(
key: ValueKey<String>(dessert.name),
onSelectChanged: (bool? selected) {},
cells: <DataCell>[
DataCell(
Text(dessert.name),
),
DataCell(
Text('${dessert.calories}'),
showEditIcon: true,
onTap: () {},
),
DataCell(
Text('${dessert.fat}'),
showEditIcon: true,
onTap: () {},
),
],
);
}).toList(),
);
}
await tester.pumpWidget(MaterialApp(
home: Material(child: buildCustomTable(
checkboxHorizontalMargin: customCheckboxHorizontalMargin,
horizontalMargin: customHorizontalMargin,
)),
));
// Custom checkbox padding.
checkbox = find.byType(Checkbox).first;
padding = find.ancestor(of: checkbox, matching: find.byType(Padding));
expect(
tester.getRect(checkbox).left - tester.getRect(padding).left,
customCheckboxHorizontalMargin,
);
expect(
tester.getRect(padding).right - tester.getRect(checkbox).right,
customCheckboxHorizontalMargin,
);
// First column padding.
padding = find.widgetWithText(Padding, 'Frozen yogurt').first;
cellContent = find.widgetWithText(Align, 'Frozen yogurt'); // DataTable wraps its DataCells in an Align widget.
expect(
tester.getRect(cellContent).left - tester.getRect(padding).left,
customHorizontalMargin,
);
});
testWidgets('DataRow is disabled when onSelectChanged is not set', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: DataTable(
columns: const <DataColumn>[
DataColumn(label: Text('Col1')),
DataColumn(label: Text('Col2')),
],
rows: <DataRow>[
DataRow(cells: const <DataCell>[
DataCell(Text('Hello')),
DataCell(Text('world')),
],
onSelectChanged: (bool? value) {},
),
const DataRow(cells: <DataCell>[
DataCell(Text('Bug')),
DataCell(Text('report')),
]),
const DataRow(cells: <DataCell>[
DataCell(Text('GitHub')),
DataCell(Text('issue')),
]),
],
),
),
),
);
expect(find.widgetWithText(TableRowInkWell, 'Hello'), findsOneWidget);
expect(find.widgetWithText(TableRowInkWell, 'Bug'), findsNothing);
expect(find.widgetWithText(TableRowInkWell, 'GitHub'), findsNothing);
});
testWidgets('DataTable set interior border test', (WidgetTester tester) async {
const List<DataColumn> columns = <DataColumn>[
DataColumn(label: Text('column1')),
DataColumn(label: Text('column2')),
];
const List<DataCell> cells = <DataCell>[
DataCell(Text('cell1')),
DataCell(Text('cell2')),
];
const List<DataRow> rows = <DataRow>[
DataRow(cells: cells),
DataRow(cells: cells),
];
await tester.pumpWidget(
MaterialApp(
home: Material(
child: DataTable(
border: TableBorder.all(width: 2, color: Colors.red),
columns: columns,
rows: rows,
),
),
),
);
final Finder finder = find.byType(DataTable);
expect(tester.getSize(finder), equals(const Size(800, 600)));
await tester.pumpWidget(
MaterialApp(
home: Material(
child: DataTable(
border: TableBorder.all(color: Colors.red),
columns: columns,
rows: rows,
),
),
),
);
Table table = tester.widget(find.byType(Table));
TableBorder? tableBorder = table.border;
expect(tableBorder!.top.color, Colors.red);
expect(tableBorder.bottom.width, 1);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: DataTable(
columns: columns,
rows: rows,
),
),
),
);
table = tester.widget(find.byType(Table));
tableBorder = table.border;
expect(tableBorder?.bottom.width, null);
expect(tableBorder?.top.color, null);
});
// Regression test for https://github.com/flutter/flutter/issues/100952
testWidgets('Do not crashes when paint borders in a narrow space', (WidgetTester tester) async {
const List<DataColumn> columns = <DataColumn>[
DataColumn(label: Text('column1')),
DataColumn(label: Text('column2')),
];
const List<DataCell> cells = <DataCell>[
DataCell(Text('cell1')),
DataCell(Text('cell2')),
];
const List<DataRow> rows = <DataRow>[
DataRow(cells: cells),
DataRow(cells: cells),
];
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: SizedBox(
width: 117.0,
child: DataTable(
border: TableBorder.all(width: 2, color: Colors.red),
columns: columns,
rows: rows,
),
),
),
),
),
);
// Go without crashes.
});
testWidgets('DataTable clip behavior', (WidgetTester tester) async {
const Color selectedColor = Colors.green;
const Color defaultColor = Colors.red;
const BorderRadius borderRadius = BorderRadius.all(Radius.circular(30));
Widget buildTable({bool selected = false, required Clip clipBehavior}) {
return Material(
child: DataTable(
clipBehavior: clipBehavior,
border: TableBorder.all(borderRadius: borderRadius),
columns: const <DataColumn>[
DataColumn(
label: Text('Column1'),
),
],
rows: <DataRow>[
DataRow(
selected: selected,
color: MaterialStateProperty.resolveWith<Color>(
(Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return selectedColor;
}
return defaultColor;
},
),
cells: const <DataCell>[
DataCell(Text('Content1')),
],
),
],
),
);
}
// Test default clip behavior.
await tester.pumpWidget(MaterialApp(home: buildTable(clipBehavior: Clip.none)));
Material material = tester.widget<Material>(find.byType(Material).last);
expect(material.clipBehavior, Clip.none);
expect(material.borderRadius, borderRadius);
await tester.pumpWidget(MaterialApp(home: buildTable(clipBehavior: Clip.hardEdge)));
material = tester.widget<Material>(find.byType(Material).last);
expect(material.clipBehavior, Clip.hardEdge);
expect(material.borderRadius, borderRadius);
});
testWidgets('DataTable dataRowMinHeight smaller or equal dataRowMaxHeight validation', (WidgetTester tester) async {
DataTable createDataTable() =>
DataTable(
columns: const <DataColumn>[DataColumn(label: Text('Column1'))],
rows: const <DataRow>[],
dataRowMinHeight: 2.0,
dataRowMaxHeight: 1.0,
);
expect(() => createDataTable(), throwsA(predicate((AssertionError e) =>
e.toString().contains('dataRowMaxHeight >= dataRowMinHeight'))));
});
testWidgets('DataTable dataRowHeight is not used together with dataRowMinHeight or dataRowMaxHeight', (WidgetTester tester) async {
DataTable createDataTable({double? dataRowHeight, double? dataRowMinHeight, double? dataRowMaxHeight}) =>
DataTable(
columns: const <DataColumn>[DataColumn(label: Text('Column1'))],
rows: const <DataRow>[],
dataRowHeight: dataRowHeight,
dataRowMinHeight: dataRowMinHeight,
dataRowMaxHeight: dataRowMaxHeight,
);
expect(() => createDataTable(dataRowHeight: 1.0, dataRowMinHeight: 2.0, dataRowMaxHeight: 2.0), throwsA(predicate((AssertionError e) =>
e.toString().contains('dataRowHeight == null || (dataRowMinHeight == null && dataRowMaxHeight == null)'))));
expect(() => createDataTable(dataRowHeight: 1.0, dataRowMaxHeight: 2.0), throwsA(predicate((AssertionError e) =>
e.toString().contains('dataRowHeight == null || (dataRowMinHeight == null && dataRowMaxHeight == null)'))));
expect(() => createDataTable(dataRowHeight: 1.0, dataRowMinHeight: 2.0), throwsA(predicate((AssertionError e) =>
e.toString().contains('dataRowHeight == null || (dataRowMinHeight == null && dataRowMaxHeight == null)'))));
});
group('TableRowInkWell', () {
testWidgets('can handle secondary taps', (WidgetTester tester) async {
bool secondaryTapped = false;
bool secondaryTappedDown = false;
await tester.pumpWidget(MaterialApp(
home: Material(
child: Table(
children: <TableRow>[
TableRow(
children: <Widget>[
TableRowInkWell(
onSecondaryTap: () {
secondaryTapped = true;
},
onSecondaryTapDown: (TapDownDetails details) {
secondaryTappedDown = true;
},
child: const SizedBox(
width: 100.0,
height: 100.0,
),
),
],
),
],
),
),
));
expect(secondaryTapped, isFalse);
expect(secondaryTappedDown, isFalse);
expect(find.byType(TableRowInkWell), findsOneWidget);
await tester.tap(
find.byType(TableRowInkWell),
buttons: kSecondaryMouseButton,
);
await tester.pumpAndSettle();
expect(secondaryTapped, isTrue);
expect(secondaryTappedDown, isTrue);
});
});
testWidgets('Heading cell cursor resolves MaterialStateMouseCursor correctly', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DataTable(
sortColumnIndex: 0,
columns: <DataColumn>[
// This column can be sorted.
DataColumn(
mouseCursor: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return SystemMouseCursors.forbidden;
}
return SystemMouseCursors.copy;
}),
onSort: (int columnIndex, bool ascending) {},
label: const Text('A'),
),
// This column cannot be sorted.
DataColumn(
mouseCursor: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return SystemMouseCursors.forbidden;
}
return SystemMouseCursors.copy;
}),
label: const Text('B'),
),
],
rows: const <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(Text('Data 1')),
DataCell(Text('Data 2')),
],
),
DataRow(
cells: <DataCell>[
DataCell(Text('Data 3')),
DataCell(Text('Data 4')),
],
),
],
),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.text('A')));
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.copy);
await gesture.moveTo(tester.getCenter(find.text('B')));
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden);
});
testWidgets('DataRow cursor resolves MaterialStateMouseCursor correctly', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DataTable(
sortColumnIndex: 0,
columns: <DataColumn>[
DataColumn(
label: const Text('A'),
onSort: (int columnIndex, bool ascending) {},
),
const DataColumn(label: Text('B')),
],
rows: <DataRow>[
// This row can be selected.
DataRow(
mouseCursor: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return SystemMouseCursors.copy;
}
return SystemMouseCursors.forbidden;
}),
onSelectChanged: (bool? selected) {},
cells: const <DataCell>[
DataCell(Text('Data 1')),
DataCell(Text('Data 2')),
],
),
// This row is selected.
DataRow(
selected: true,
onSelectChanged: (bool? selected) {},
mouseCursor: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return SystemMouseCursors.copy;
}
return SystemMouseCursors.forbidden;
}),
cells: const <DataCell>[
DataCell(Text('Data 3')),
DataCell(Text('Data 4')),
],
),
],
),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.text('Data 1')));
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.forbidden);
await gesture.moveTo(tester.getCenter(find.text('Data 3')));
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.copy);
});
testWidgets("DataRow cursor doesn't update checkbox cursor", (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DataTable(
sortColumnIndex: 0,
columns: <DataColumn>[
DataColumn(
label: const Text('A'),
onSort: (int columnIndex, bool ascending) {},
),
const DataColumn(label: Text('B')),
],
rows: <DataRow>[
DataRow(
onSelectChanged: (bool? selected) {},
mouseCursor: const MaterialStatePropertyAll<MouseCursor>(SystemMouseCursors.copy),
cells: const <DataCell>[
DataCell(Text('Data')),
DataCell(Text('Data 2')),
],
),
],
),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.byType(Checkbox).last));
await tester.pump();
// Test that the checkbox cursor is not changed.
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
await gesture.moveTo(tester.getCenter(find.text('Data')));
await tester.pump();
// Test that cursor is updated for the row.
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.copy);
});
// This is a regression test for https://github.com/flutter/flutter/issues/114470.
testWidgets('DataTable text styles are merged with default text style', (WidgetTester tester) async {
late DefaultTextStyle defaultTextStyle;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
defaultTextStyle = DefaultTextStyle.of(context);
return DataTable(
headingTextStyle: const TextStyle(),
dataTextStyle: const TextStyle(),
columns: const <DataColumn>[
DataColumn(label: Text('Header 1')),
DataColumn(label: Text('Header 2')),
],
rows: const <DataRow>[
DataRow(
cells: <DataCell>[
DataCell(Text('Data 1')),
DataCell(Text('Data 2')),
],
),
],
);
}
),
),
),
);
final TextStyle? headingTextStyle = _getTextRenderObject(tester, 'Header 1').text.style;
expect(headingTextStyle, defaultTextStyle.style);
final TextStyle? dataTextStyle = _getTextRenderObject(tester, 'Data 1').text.style;
expect(dataTextStyle, defaultTextStyle.style);
});
}
RenderParagraph _getTextRenderObject(WidgetTester tester, String text) {
return tester.renderObject(find.text(text));
}
| flutter/packages/flutter/test/material/data_table_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/data_table_test.dart",
"repo_id": "flutter",
"token_count": 34717
} | 838 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
const List<String> menuItems = <String>['one', 'two', 'three', 'four'];
void onChanged<T>(T _) { }
Finder _iconRichText(Key iconKey) {
return find.descendant(
of: find.byKey(iconKey),
matching: find.byType(RichText),
);
}
Widget buildFormFrame({
Key? buttonKey,
AutovalidateMode autovalidateMode = AutovalidateMode.disabled,
int elevation = 8,
String? value = 'two',
ValueChanged<String?>? onChanged,
VoidCallback? onTap,
Widget? icon,
Color? iconDisabledColor,
Color? iconEnabledColor,
double iconSize = 24.0,
bool isDense = true,
bool isExpanded = false,
Widget? hint,
Widget? disabledHint,
Widget? underline,
List<String>? items = menuItems,
Alignment alignment = Alignment.center,
TextDirection textDirection = TextDirection.ltr,
AlignmentGeometry buttonAlignment = AlignmentDirectional.centerStart,
}) {
return TestApp(
textDirection: textDirection,
child: Material(
child: Align(
alignment: alignment,
child: RepaintBoundary(
child: DropdownButtonFormField<String>(
key: buttonKey,
autovalidateMode: autovalidateMode,
elevation: elevation,
value: value,
hint: hint,
disabledHint: disabledHint,
onChanged: onChanged,
onTap: onTap,
icon: icon,
iconSize: iconSize,
iconDisabledColor: iconDisabledColor,
iconEnabledColor: iconEnabledColor,
isDense: isDense,
isExpanded: isExpanded,
items: items?.map<DropdownMenuItem<String>>((String item) {
return DropdownMenuItem<String>(
key: ValueKey<String>(item),
value: item,
child: Text(item, key: ValueKey<String>('${item}Text')),
);
}).toList(),
alignment: buttonAlignment,
),
),
),
),
);
}
class _TestAppState extends State<TestApp> {
@override
Widget build(BuildContext context) {
return Localizations(
locale: const Locale('en', 'US'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultWidgetsLocalizations.delegate,
DefaultMaterialLocalizations.delegate,
],
child: MediaQuery(
data: const MediaQueryData().copyWith(size: widget.mediaSize),
child: Directionality(
textDirection: widget.textDirection,
child: Navigator(
onGenerateRoute: (RouteSettings settings) {
assert(settings.name == '/');
return MaterialPageRoute<void>(
settings: settings,
builder: (BuildContext context) => widget.child,
);
},
),
),
),
);
}
}
class TestApp extends StatefulWidget {
const TestApp({
super.key,
required this.textDirection,
required this.child,
this.mediaSize,
});
final TextDirection textDirection;
final Widget child;
final Size? mediaSize;
@override
State<TestApp> createState() => _TestAppState();
}
void verifyPaintedShadow(Finder customPaint, int elevation) {
const Rect originalRectangle = Rect.fromLTRB(0.0, 0.0, 800, 208.0);
final List<BoxShadow> boxShadows = List<BoxShadow>.generate(3, (int index) => kElevationToShadow[elevation]![index]);
final List<RRect> rrects = List<RRect>.generate(3, (int index) {
return RRect.fromRectAndRadius(
originalRectangle.shift(
boxShadows[index].offset,
).inflate(boxShadows[index].spreadRadius),
const Radius.circular(2.0),
);
});
expect(
customPaint,
paints
..save()
..rrect(rrect: rrects[0], color: boxShadows[0].color, hasMaskFilter: true)
..rrect(rrect: rrects[1], color: boxShadows[1].color, hasMaskFilter: true)
..rrect(rrect: rrects[2], color: boxShadows[2].color, hasMaskFilter: true),
);
}
void main() {
// Regression test for https://github.com/flutter/flutter/issues/87102
testWidgets('label position test - show hint', (WidgetTester tester) async {
int? value;
await tester.pumpWidget(
TestApp(
textDirection: TextDirection.ltr,
child: Material(
child: DropdownButtonFormField<int?>(
decoration: const InputDecoration(
labelText: 'labelText',
),
value: value,
hint: const Text('Hint'),
onChanged: (int? newValue) {
value = newValue;
},
items: const <DropdownMenuItem<int?>>[
DropdownMenuItem<int?>(
value: 1,
child: Text('One'),
),
DropdownMenuItem<int?>(
value: 2,
child: Text('Two'),
),
DropdownMenuItem<int?>(
value: 3,
child: Text('Three'),
),
],
),
),
),
);
expect(value, null);
final Offset hintEmptyLabel = tester.getTopLeft(find.text('labelText'));
// Select a item.
await tester.tap(find.text('Hint'), warnIfMissed: false);
await tester.pumpAndSettle();
await tester.tap(find.text('One').last);
await tester.pumpAndSettle();
expect(value, 1);
final Offset oneValueLabel = tester.getTopLeft(find.text('labelText'));
// The position of the label does not change.
expect(hintEmptyLabel, oneValueLabel);
});
testWidgets('label position test - show disabledHint: disable', (WidgetTester tester) async {
int? value;
await tester.pumpWidget(
TestApp(
textDirection: TextDirection.ltr,
child: Material(
child: DropdownButtonFormField<int?>(
decoration: const InputDecoration(
labelText: 'labelText',
),
value: value,
onChanged: null, // this disables the menu and shows the disabledHint.
disabledHint: const Text('disabledHint'),
items: const <DropdownMenuItem<int?>>[
DropdownMenuItem<int?>(
value: 1,
child: Text('One'),
),
DropdownMenuItem<int?>(
value: 2,
child: Text('Two'),
),
DropdownMenuItem<int?>(
value: 3,
child: Text('Three'),
),
],
),
),
),
);
expect(value, null); // disabledHint shown.
final Offset hintEmptyLabel = tester.getTopLeft(find.text('labelText'));
expect(hintEmptyLabel, const Offset(0.0, 8.0));
});
testWidgets('label position test - show disabledHint: enable + null item', (WidgetTester tester) async {
int? value;
await tester.pumpWidget(
TestApp(
textDirection: TextDirection.ltr,
child: Material(
child: DropdownButtonFormField<int?>(
decoration: const InputDecoration(
labelText: 'labelText',
),
value: value,
disabledHint: const Text('disabledHint'),
onChanged: (_) {},
items: null,
),
),
),
);
expect(value, null); // disabledHint shown.
final Offset hintEmptyLabel = tester.getTopLeft(find.text('labelText'));
expect(hintEmptyLabel, const Offset(0.0, 8.0));
});
testWidgets('label position test - show disabledHint: enable + empty item', (WidgetTester tester) async {
int? value;
await tester.pumpWidget(
TestApp(
textDirection: TextDirection.ltr,
child: Material(
child: DropdownButtonFormField<int?>(
decoration: const InputDecoration(
labelText: 'labelText',
),
value: value,
disabledHint: const Text('disabledHint'),
onChanged: (_) {},
items: const <DropdownMenuItem<int?>>[],
),
),
),
);
expect(value, null); // disabledHint shown.
final Offset hintEmptyLabel = tester.getTopLeft(find.text('labelText'));
expect(hintEmptyLabel, const Offset(0.0, 8.0));
});
testWidgets('label position test - show hint: enable + empty item', (WidgetTester tester) async {
int? value;
await tester.pumpWidget(
TestApp(
textDirection: TextDirection.ltr,
child: Material(
child: DropdownButtonFormField<int?>(
decoration: const InputDecoration(
labelText: 'labelText',
),
value: value,
hint: const Text('hint'),
onChanged: (_) {},
items: const <DropdownMenuItem<int?>>[],
),
),
),
);
expect(value, null); // hint shown.
final Offset hintEmptyLabel = tester.getTopLeft(find.text('labelText'));
expect(hintEmptyLabel, const Offset(0.0, 8.0));
});
testWidgets('label position test - no hint shown: enable + no selected + disabledHint', (WidgetTester tester) async {
int? value;
await tester.pumpWidget(
TestApp(
textDirection: TextDirection.ltr,
child: Material(
child: DropdownButtonFormField<int?>(
decoration: const InputDecoration(
labelText: 'labelText',
),
value: value,
disabledHint: const Text('disabledHint'),
onChanged: (_) {},
items: const <DropdownMenuItem<int?>>[
DropdownMenuItem<int?>(
value: 1,
child: Text('One'),
),
DropdownMenuItem<int?>(
value: 2,
child: Text('Two'),
),
DropdownMenuItem<int?>(
value: 3,
child: Text('Three'),
),
],
),
),
),
);
expect(value, null);
final Offset hintEmptyLabel = tester.getTopLeft(find.text('labelText'));
expect(hintEmptyLabel, const Offset(0.0, 20.0));
});
testWidgets('label position test - show selected item: disabled + hint + disabledHint', (WidgetTester tester) async {
const int value = 1;
await tester.pumpWidget(
TestApp(
textDirection: TextDirection.ltr,
child: Material(
child: DropdownButtonFormField<int?>(
decoration: const InputDecoration(
labelText: 'labelText',
),
value: value,
hint: const Text('hint'),
onChanged: null, // disabled
disabledHint: const Text('disabledHint'),
items: const <DropdownMenuItem<int?>>[
DropdownMenuItem<int?>(
value: 1,
child: Text('One'),
),
DropdownMenuItem<int?>(
value: 2,
child: Text('Two'),
),
DropdownMenuItem<int?>(
value: 3,
child: Text('Three'),
),
],
),
),
),
);
expect(value, 1);
final Offset hintEmptyLabel = tester.getTopLeft(find.text('labelText'));
expect(hintEmptyLabel, const Offset(0.0, 8.0));
});
// Regression test for https://github.com/flutter/flutter/issues/82910
testWidgets('null value test', (WidgetTester tester) async {
int? value = 1;
await tester.pumpWidget(
TestApp(
textDirection: TextDirection.ltr,
child: Material(
child: DropdownButtonFormField<int?>(
decoration: const InputDecoration(
labelText: 'labelText',
),
value: value,
onChanged: (int? newValue) {
value = newValue;
},
items: const <DropdownMenuItem<int?>>[
DropdownMenuItem<int?>(
child: Text('None'),
),
DropdownMenuItem<int?>(
value: 1,
child: Text('One'),
),
DropdownMenuItem<int?>(
value: 2,
child: Text('Two'),
),
DropdownMenuItem<int?>(
value: 3,
child: Text('Three'),
),
],
),
),
),
);
expect(value, 1);
final Offset nonEmptyLabel = tester.getTopLeft(find.text('labelText'));
// Switch to `null` value item from value 1.
await tester.tap(find.text('One'));
await tester.pumpAndSettle();
await tester.tap(find.text('None').last);
await tester.pump();
expect(value, null);
final Offset nullValueLabel = tester.getTopLeft(find.text('labelText'));
// The position of the label does not change.
expect(nonEmptyLabel, nullValueLabel);
});
testWidgets('DropdownButtonFormField with autovalidation test', (WidgetTester tester) async {
String? value = 'one';
int validateCalled = 0;
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MaterialApp(
home: Material(
child: DropdownButtonFormField<String>(
value: value,
hint: const Text('Select Value'),
decoration: const InputDecoration(
prefixIcon: Icon(Icons.fastfood),
),
items: menuItems.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (String? newValue) {
setState(() {
value = newValue;
});
},
validator: (String? currentValue) {
validateCalled++;
return currentValue == null ? 'Must select value' : null;
},
autovalidateMode: AutovalidateMode.always,
),
),
);
},
),
);
expect(validateCalled, 1);
expect(value, equals('one'));
await tester.tap(find.text('one'));
await tester.pumpAndSettle();
await tester.tap(find.text('three').last);
await tester.pump();
expect(validateCalled, 2);
await tester.pumpAndSettle();
expect(value, equals('three'));
});
testWidgets('DropdownButtonFormField arrow icon aligns with the edge of button when expanded', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
// There shouldn't be overflow when expanded although list contains longer items.
final List<String> items = <String>[
'1234567890',
'abcdefghijklmnopqrstuvwxyz1234567890abcdefghijklmnopqrstuvwxyz1234567890',
];
await tester.pumpWidget(
buildFormFrame(
buttonKey: buttonKey,
value: '1234567890',
isExpanded: true,
onChanged: onChanged,
items: items,
),
);
final RenderBox buttonBox = tester.renderObject<RenderBox>(
find.byKey(buttonKey),
);
expect(buttonBox.attached, isTrue);
final RenderBox arrowIcon = tester.renderObject<RenderBox>(
find.byIcon(Icons.arrow_drop_down),
);
expect(arrowIcon.attached, isTrue);
// Arrow icon should be aligned with far right of button when expanded
expect(
arrowIcon.localToGlobal(Offset.zero).dx,
buttonBox.size.centerRight(Offset(-arrowIcon.size.width, 0.0)).dx,
);
});
testWidgets('DropdownButtonFormField with isDense:true aligns selected menu item', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
await tester.pumpWidget(
buildFormFrame(
buttonKey: buttonKey,
onChanged: onChanged,
),
);
final RenderBox buttonBox = tester.renderObject<RenderBox>(
find.byKey(buttonKey),
);
expect(buttonBox.attached, isTrue);
await tester.tap(find.text('two'));
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
// The selected dropdown item is both in menu we just popped up, and in
// the IndexedStack contained by the dropdown button. Both of them should
// have the same vertical center as the button.
final List<RenderBox> itemBoxes = tester.renderObjectList<RenderBox>(
find.byKey(const ValueKey<String>('two')),
).toList();
expect(itemBoxes.length, equals(2));
// When isDense is true, the button's height is reduced. The menu items'
// heights are not.
final List<double> itemBoxesHeight = itemBoxes.map<double>((RenderBox box) => box.size.height).toList();
final double menuItemHeight = itemBoxesHeight.reduce(math.max);
expect(menuItemHeight, greaterThanOrEqualTo(buttonBox.size.height));
for (final RenderBox itemBox in itemBoxes) {
expect(itemBox.attached, isTrue);
final Offset buttonBoxCenter = buttonBox.size.center(buttonBox.localToGlobal(Offset.zero));
final Offset itemBoxCenter = itemBox.size.center(itemBox.localToGlobal(Offset.zero));
expect(buttonBoxCenter.dy, equals(itemBoxCenter.dy));
}
});
testWidgets('DropdownButtonFormField with isDense:true does not clip large scale text', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
const String value = 'two';
await tester.pumpWidget(
TestApp(
textDirection: TextDirection.ltr,
child: Builder(
builder: (BuildContext context) => MediaQuery.withClampedTextScaling(
minScaleFactor: 3.0,
maxScaleFactor: 3.0,
child: Material(
child: Center(
child: DropdownButtonFormField<String>(
key: buttonKey,
value: value,
onChanged: onChanged,
items: menuItems.map<DropdownMenuItem<String>>((String item) {
return DropdownMenuItem<String>(
key: ValueKey<String>(item),
value: item,
child: Text(
item,
key: ValueKey<String>('${item}Text'),
style: const TextStyle(fontSize: 20.0),
),
);
}).toList(),
),
),
),
),
),
),
);
final RenderBox box = tester.renderObject<RenderBox>(find.byType(DropdownButton<String>));
expect(box.size.height, 64.0);
});
testWidgets('DropdownButtonFormField.isDense is true by default', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/46844
final Key buttonKey = UniqueKey();
const String value = 'two';
await tester.pumpWidget(
TestApp(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: DropdownButtonFormField<String>(
key: buttonKey,
value: value,
onChanged: onChanged,
items: menuItems.map<DropdownMenuItem<String>>((String item) {
return DropdownMenuItem<String>(
key: ValueKey<String>(item),
value: item,
child: Text(item, key: ValueKey<String>('${item}Text')),
);
}).toList(),
),
),
),
),
);
final RenderBox box = tester.renderObject<RenderBox>(find.byType(DropdownButton<String>));
expect(box.size.height, 48.0);
});
testWidgets('DropdownButtonFormField - custom text style', (WidgetTester tester) async {
const String value = 'foo';
final UniqueKey itemKey = UniqueKey();
await tester.pumpWidget(
TestApp(
textDirection: TextDirection.ltr,
child: Material(
child: DropdownButtonFormField<String>(
value: value,
items: <DropdownMenuItem<String>>[
DropdownMenuItem<String>(
key: itemKey,
value: 'foo',
child: const Text(value),
),
],
onChanged: (_) { },
style: const TextStyle(
color: Colors.amber,
fontSize: 20.0,
),
),
),
),
);
final RichText richText = tester.widget<RichText>(
find.descendant(
of: find.byKey(itemKey),
matching: find.byType(RichText),
),
);
expect(richText.text.style!.color, Colors.amber);
expect(richText.text.style!.fontSize, 20.0);
});
testWidgets('DropdownButtonFormField - disabledHint displays when the items list is empty, when items is null', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
Widget build({ List<String>? items }) {
return buildFormFrame(
items: items,
buttonKey: buttonKey,
value: null,
hint: const Text('enabled'),
disabledHint: const Text('disabled'),
);
}
// [disabledHint] should display when [items] is null
await tester.pumpWidget(build());
expect(find.text('enabled'), findsNothing);
expect(find.text('disabled'), findsOneWidget);
// [disabledHint] should display when [items] is an empty list.
await tester.pumpWidget(build(items: <String>[]));
expect(find.text('enabled'), findsNothing);
expect(find.text('disabled'), findsOneWidget);
});
testWidgets(
'DropdownButtonFormField - hint displays when the items list is '
'empty, items is null, and disabledHint is null',
(WidgetTester tester) async {
final Key buttonKey = UniqueKey();
Widget build({ List<String>? items }) {
return buildFormFrame(
items: items,
buttonKey: buttonKey,
value: null,
hint: const Text('hint used when disabled'),
);
}
// [hint] should display when [items] is null and [disabledHint] is not defined
await tester.pumpWidget(build());
expect(find.text('hint used when disabled'), findsOneWidget);
// [hint] should display when [items] is an empty list and [disabledHint] is not defined.
await tester.pumpWidget(build(items: <String>[]));
expect(find.text('hint used when disabled'), findsOneWidget);
},
);
testWidgets('DropdownButtonFormField - disabledHint is null by default', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
Widget build({ List<String>? items }) {
return buildFormFrame(
items: items,
buttonKey: buttonKey,
value: null,
hint: const Text('hint used when disabled'),
);
}
// [hint] should display when [items] is null and [disabledHint] is not defined
await tester.pumpWidget(build());
expect(find.text('hint used when disabled'), findsOneWidget);
// [hint] should display when [items] is an empty list and [disabledHint] is not defined.
await tester.pumpWidget(build(items: <String>[]));
expect(find.text('hint used when disabled'), findsOneWidget);
});
testWidgets('DropdownButtonFormField - disabledHint is null by default', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
Widget build({ List<String>? items }) {
return buildFormFrame(
items: items,
buttonKey: buttonKey,
value: null,
hint: const Text('hint used when disabled'),
);
}
// [hint] should display when [items] is null and [disabledHint] is not defined
await tester.pumpWidget(build());
expect(find.text('hint used when disabled'), findsOneWidget);
// [hint] should display when [items] is an empty list and [disabledHint] is not defined.
await tester.pumpWidget(build(items: <String>[]));
expect(find.text('hint used when disabled'), findsOneWidget);
});
testWidgets('DropdownButtonFormField - disabledHint displays when onChanged is null', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
Widget build({ List<String>? items, ValueChanged<String?>? onChanged }) {
return buildFormFrame(
items: items,
buttonKey: buttonKey,
value: null,
onChanged: onChanged,
hint: const Text('enabled'),
disabledHint: const Text('disabled'),
);
}
await tester.pumpWidget(build(items: menuItems));
expect(find.text('enabled'), findsNothing);
expect(find.text('disabled'), findsOneWidget);
});
testWidgets('DropdownButtonFormField - disabled hint should be of same size as enabled hint', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
Widget build({ List<String>? items}) {
return buildFormFrame(
items: items,
buttonKey: buttonKey,
value: null,
hint: const Text('enabled'),
disabledHint: const Text('disabled'),
);
}
await tester.pumpWidget(build());
final RenderBox disabledHintBox = tester.renderObject<RenderBox>(
find.byKey(buttonKey),
);
await tester.pumpWidget(build(items: menuItems));
final RenderBox enabledHintBox = tester.renderObject<RenderBox>(
find.byKey(buttonKey),
);
expect(enabledHintBox.localToGlobal(Offset.zero), equals(disabledHintBox.localToGlobal(Offset.zero)));
expect(enabledHintBox.size, equals(disabledHintBox.size));
});
testWidgets('DropdownButtonFormField - Custom icon size and colors', (WidgetTester tester) async {
final Key iconKey = UniqueKey();
final Icon customIcon = Icon(Icons.assessment, key: iconKey);
await tester.pumpWidget(buildFormFrame(
icon: customIcon,
iconSize: 30.0,
iconEnabledColor: Colors.pink,
iconDisabledColor: Colors.orange,
onChanged: onChanged,
));
// test for size
final RenderBox icon = tester.renderObject(find.byKey(iconKey));
expect(icon.size, const Size(30.0, 30.0));
// test for enabled color
final RichText enabledRichText = tester.widget<RichText>(_iconRichText(iconKey));
expect(enabledRichText.text.style!.color, Colors.pink);
// test for disabled color
await tester.pumpWidget(buildFormFrame(
icon: customIcon,
iconSize: 30.0,
iconEnabledColor: Colors.pink,
iconDisabledColor: Colors.orange,
items: null,
));
final RichText disabledRichText = tester.widget<RichText>(_iconRichText(iconKey));
expect(disabledRichText.text.style!.color, Colors.orange);
});
testWidgets('DropdownButtonFormField - default elevation', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
debugDisableShadows = false;
await tester.pumpWidget(buildFormFrame(
buttonKey: buttonKey,
onChanged: onChanged,
));
await tester.tap(find.byKey(buttonKey));
await tester.pumpAndSettle();
final Finder customPaint = find.ancestor(
of: find.text('one').last,
matching: find.byType(CustomPaint),
).last;
// Verifying whether or not default elevation(i.e. 8) paints desired shadow
verifyPaintedShadow(customPaint, 8);
debugDisableShadows = true;
});
testWidgets('DropdownButtonFormField - custom elevation', (WidgetTester tester) async {
debugDisableShadows = false;
final Key buttonKeyOne = UniqueKey();
final Key buttonKeyTwo = UniqueKey();
await tester.pumpWidget(buildFormFrame(
buttonKey: buttonKeyOne,
elevation: 16,
onChanged: onChanged,
));
await tester.tap(find.byKey(buttonKeyOne));
await tester.pumpAndSettle();
final Finder customPaintOne = find.ancestor(
of: find.text('one').last,
matching: find.byType(CustomPaint),
).last;
verifyPaintedShadow(customPaintOne, 16);
await tester.tap(find.text('one').last);
await tester.pumpWidget(buildFormFrame(
buttonKey: buttonKeyTwo,
elevation: 24,
onChanged: onChanged,
));
await tester.tap(find.byKey(buttonKeyTwo));
await tester.pumpAndSettle();
final Finder customPaintTwo = find.ancestor(
of: find.text('one').last,
matching: find.byType(CustomPaint),
).last;
verifyPaintedShadow(customPaintTwo, 24);
debugDisableShadows = true;
});
testWidgets('DropdownButtonFormField does not allow duplicate item values', (WidgetTester tester) async {
final List<DropdownMenuItem<String>> itemsWithDuplicateValues = <String>['a', 'b', 'c', 'c']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList();
await expectLater(
() => tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DropdownButtonFormField<String>(
value: 'c',
onChanged: (String? newValue) {},
items: itemsWithDuplicateValues,
),
),
),
),
throwsA(isAssertionError.having(
(AssertionError error) => error.toString(),
'.toString()',
contains("There should be exactly one item with [DropdownButton]'s value"),
)),
);
});
testWidgets('DropdownButtonFormField value should only appear in one menu item', (WidgetTester tester) async {
final List<DropdownMenuItem<String>> itemsWithDuplicateValues = <String>['a', 'b', 'c', 'd']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList();
await expectLater(
() => tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: DropdownButton<String>(
value: 'e',
onChanged: (String? newValue) {},
items: itemsWithDuplicateValues,
),
),
),
),
throwsA(isAssertionError.having(
(AssertionError error) => error.toString(),
'.toString()',
contains("There should be exactly one item with [DropdownButton]'s value"),
)),
);
});
testWidgets('DropdownButtonFormField - selectedItemBuilder builds custom buttons', (WidgetTester tester) async {
const List<String> items = <String>[
'One',
'Two',
'Three',
];
String? selectedItem = items[0];
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MaterialApp(
home: Scaffold(
body: DropdownButtonFormField<String>(
value: selectedItem,
onChanged: (String? string) => setState(() => selectedItem = string),
selectedItemBuilder: (BuildContext context) {
int index = 0;
return items.map((String string) {
index += 1;
return Text('$string as an Arabic numeral: $index');
}).toList();
},
items: items.map((String string) {
return DropdownMenuItem<String>(
value: string,
child: Text(string),
);
}).toList(),
),
),
);
},
),
);
expect(find.text('One as an Arabic numeral: 1'), findsOneWidget);
await tester.tap(find.text('One as an Arabic numeral: 1'));
await tester.pumpAndSettle();
await tester.tap(find.text('Two'));
await tester.pumpAndSettle();
expect(find.text('Two as an Arabic numeral: 2'), findsOneWidget);
});
testWidgets('DropdownButton onTap callback is called when defined', (WidgetTester tester) async {
int dropdownButtonTapCounter = 0;
String? value = 'one';
void onChanged(String? newValue) {
value = newValue;
}
void onTap() { dropdownButtonTapCounter += 1; }
Widget build() => buildFormFrame(
value: value,
onChanged: onChanged,
onTap: onTap,
);
await tester.pumpWidget(build());
expect(dropdownButtonTapCounter, 0);
// Tap dropdown button.
await tester.tap(find.text('one'));
await tester.pumpAndSettle();
expect(value, equals('one'));
expect(dropdownButtonTapCounter, 1); // Should update counter.
// Tap dropdown menu item.
await tester.tap(find.text('three').last);
await tester.pumpAndSettle();
expect(value, equals('three'));
expect(dropdownButtonTapCounter, 1); // Should not change.
// Tap dropdown button again.
await tester.tap(find.text('three'));
await tester.pumpAndSettle();
expect(value, equals('three'));
expect(dropdownButtonTapCounter, 2); // Should update counter.
// Tap dropdown menu item.
await tester.tap(find.text('two').last);
await tester.pumpAndSettle();
expect(value, equals('two'));
expect(dropdownButtonTapCounter, 2); // Should not change.
});
testWidgets('DropdownButtonFormField should re-render if value param changes', (WidgetTester tester) async {
String currentValue = 'two';
await tester.pumpWidget(
StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return MaterialApp(
home: Material(
child: DropdownButtonFormField<String>(
value: currentValue,
onChanged: onChanged,
items: menuItems.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
onTap: () {
setState(() {
currentValue = value;
});
},
);
}).toList(),
),
),
);
},
),
);
// Make sure the rendered text value matches the initial state value.
expect(currentValue, equals('two'));
expect(find.text(currentValue), findsOneWidget);
// Tap the DropdownButtonFormField widget
await tester.tap(find.byType(DropdownButton<String>));
await tester.pumpAndSettle();
// Tap the first dropdown menu item.
await tester.tap(find.text('one').last);
await tester.pumpAndSettle();
// Make sure the rendered text value matches the updated state value.
expect(currentValue, equals('one'));
expect(find.text(currentValue), findsOneWidget);
});
testWidgets('autovalidateMode is passed to super', (WidgetTester tester) async {
int validateCalled = 0;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: DropdownButtonFormField<String>(
autovalidateMode: AutovalidateMode.always,
items: menuItems.map((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: onChanged,
validator: (String? value) {
validateCalled++;
return null;
},
),
),
),
),
);
expect(validateCalled, 1);
});
testWidgets('DropdownButtonFormField - Custom button alignment', (WidgetTester tester) async {
await tester.pumpWidget(buildFormFrame(
buttonAlignment: AlignmentDirectional.center,
items: <String>['one'],
value: 'one',
));
final RenderBox buttonBox = tester.renderObject<RenderBox>(find.byType(IndexedStack));
final RenderBox selectedItemBox = tester.renderObject(find.text('one'));
// Should be center-center aligned.
expect(
buttonBox.localToGlobal(Offset(buttonBox.size.width / 2.0, buttonBox.size.height / 2.0)),
selectedItemBox.localToGlobal(Offset(selectedItemBox.size.width / 2.0, selectedItemBox.size.height / 2.0)),
);
});
testWidgets('InputDecoration borders are used for clipping', (WidgetTester tester) async {
const BorderRadius errorBorderRadius = BorderRadius.all(Radius.circular(5.0));
const BorderRadius focusedErrorBorderRadius = BorderRadius.all(Radius.circular(6.0));
const BorderRadius focusedBorder = BorderRadius.all(Radius.circular(7.0));
const BorderRadius enabledBorder = BorderRadius.all(Radius.circular(9.0));
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
const String errorText = 'This is an error';
bool showError = false;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
inputDecorationTheme: const InputDecorationTheme(
errorBorder: OutlineInputBorder(
borderRadius: errorBorderRadius,
),
focusedErrorBorder: OutlineInputBorder(
borderRadius: focusedErrorBorderRadius,
),
focusedBorder: OutlineInputBorder(
borderRadius: focusedBorder,
),
enabledBorder: OutlineInputBorder(
borderRadius: enabledBorder,
),
),
),
home: Material(
child: Center(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return DropdownButtonFormField<String>(
value: 'two',
onChanged:(String? value) {
setState(() {
if (value == 'three') {
showError = true;
} else {
showError = false;
}
});
},
decoration: InputDecoration(
errorText: showError ? errorText : null,
),
focusNode: focusNode,
items: menuItems.map<DropdownMenuItem<String>>((String item) {
return DropdownMenuItem<String>(
key: ValueKey<String>(item),
value: item,
child: Text(item, key: ValueKey<String>('${item}Text')),
);
}).toList(),
);
}
),
),
),
),
);
// Test enabled border.
InkWell inkWell = tester.widget<InkWell>(find.byType(InkWell));
expect(inkWell.borderRadius, enabledBorder);
// Test focused border.
focusNode.requestFocus();
await tester.pump();
inkWell = tester.widget<InkWell>(find.byType(InkWell));
expect(inkWell.borderRadius, focusedBorder);
// Test focused error border.
await tester.tap(find.text('two'), warnIfMissed: false);
await tester.pumpAndSettle();
await tester.tap(find.text('three').last);
await tester.pumpAndSettle();
inkWell = tester.widget<InkWell>(find.byType(InkWell));
expect(inkWell.borderRadius, focusedErrorBorderRadius);
// Test error border with no focus.
focusNode.unfocus();
await tester.pump();
// Hovering over the widget should show the error border.
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(tester.getCenter(find.text('three').last));
await tester.pumpAndSettle();
inkWell = tester.widget<InkWell>(find.byType(InkWell));
expect(inkWell.borderRadius, errorBorderRadius);
});
testWidgets('DropdownButtonFormField onChanged is called when the form is reset', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/123009.
final GlobalKey<FormFieldState<String>> stateKey = GlobalKey<FormFieldState<String>>();
final GlobalKey<FormState> formKey = GlobalKey<FormState>();
String? value;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Form(
key: formKey,
child: DropdownButtonFormField<String>(
key: stateKey,
value: 'One',
items: <String>['One', 'Two', 'Free', 'Four']
.map<DropdownMenuItem<String>>((String value) {
return DropdownMenuItem<String>(
value: value,
child: Text(value),
);
}).toList(),
onChanged: (String? newValue) {
value = newValue;
},
),
),
),
),
);
// Initial value is 'One'.
expect(value, isNull);
expect(stateKey.currentState!.value, equals('One'));
// Select 'Two'.
await tester.tap(find.text('One'));
await tester.pumpAndSettle();
await tester.tap(find.text('Two').last);
await tester.pumpAndSettle();
expect(value, equals('Two'));
expect(stateKey.currentState!.value, equals('Two'));
// Should be back to 'One' when the form is reset.
formKey.currentState!.reset();
expect(value, equals('One'));
expect(stateKey.currentState!.value, equals('One'));
});
}
| flutter/packages/flutter/test/material/dropdown_form_field_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/dropdown_form_field_test.dart",
"repo_id": "flutter",
"token_count": 18350
} | 839 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
final Key blockKey = UniqueKey();
const double expandedAppbarHeight = 250.0;
final Key appbarContainerKey = UniqueKey();
void main() {
testWidgets('FlexibleSpaceBar collapse mode none', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: debugDefaultTargetPlatformOverride),
home: Scaffold(
body: CustomScrollView(
key: blockKey,
slivers: <Widget>[
SliverAppBar(
expandedHeight: expandedAppbarHeight,
pinned: true,
flexibleSpace: FlexibleSpaceBar(
background: Container(
key: appbarContainerKey,
),
collapseMode: CollapseMode.none,
),
),
SliverToBoxAdapter(
child: Container(
height: 10000.0,
),
),
],
),
),
),
);
final Finder appbarContainer = find.byKey(appbarContainerKey);
final Offset topBeforeScroll = tester.getTopLeft(appbarContainer);
await slowDrag(tester, blockKey, const Offset(0.0, -100.0));
final Offset topAfterScroll = tester.getTopLeft(appbarContainer);
expect(topBeforeScroll.dy, equals(0.0));
expect(topAfterScroll.dy, equals(0.0));
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.fuchsia }));
testWidgets('FlexibleSpaceBar collapse mode pin', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: debugDefaultTargetPlatformOverride),
home: Scaffold(
body: CustomScrollView(
key: blockKey,
slivers: <Widget>[
SliverAppBar(
expandedHeight: expandedAppbarHeight,
pinned: true,
flexibleSpace: FlexibleSpaceBar(
background: Container(
key: appbarContainerKey,
),
collapseMode: CollapseMode.pin,
),
),
SliverToBoxAdapter(
child: Container(
height: 10000.0,
),
),
],
),
),
),
);
final Finder appbarContainer = find.byKey(appbarContainerKey);
final Offset topBeforeScroll = tester.getTopLeft(appbarContainer);
await slowDrag(tester, blockKey, const Offset(0.0, -100.0));
final Offset topAfterScroll = tester.getTopLeft(appbarContainer);
expect(topBeforeScroll.dy, equals(0.0));
expect(topAfterScroll.dy, equals(-100.0));
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.fuchsia }));
testWidgets('FlexibleSpaceBar collapse mode parallax', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(platform: debugDefaultTargetPlatformOverride),
home: Scaffold(
body: CustomScrollView(
key: blockKey,
slivers: <Widget>[
SliverAppBar(
expandedHeight: expandedAppbarHeight,
pinned: true,
flexibleSpace: FlexibleSpaceBar(
background: Container(
key: appbarContainerKey,
),
),
),
SliverToBoxAdapter(
child: Container(
height: 10000.0,
),
),
],
),
),
),
);
final Finder appbarContainer = find.byKey(appbarContainerKey);
final Offset topBeforeScroll = tester.getTopLeft(appbarContainer);
await slowDrag(tester, blockKey, const Offset(0.0, -100.0));
final Offset topAfterScroll = tester.getTopLeft(appbarContainer);
expect(topBeforeScroll.dy, equals(0.0));
expect(topAfterScroll.dy, lessThan(10.0));
expect(topAfterScroll.dy, greaterThan(-50.0));
}, variant: TargetPlatformVariant.all(excluding: <TargetPlatform>{ TargetPlatform.fuchsia }));
}
Future<void> slowDrag(WidgetTester tester, Key widget, Offset offset) async {
final Offset target = tester.getCenter(find.byKey(widget));
final TestGesture gesture = await tester.startGesture(target);
await gesture.moveBy(offset);
await tester.pump(const Duration(milliseconds: 10));
await gesture.up();
}
| flutter/packages/flutter/test/material/flexible_space_bar_collapse_mode_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/flexible_space_bar_collapse_mode_test.dart",
"repo_id": "flutter",
"token_count": 2148
} | 840 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set'])
library;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
/// Adds the basic requirements for a Chip.
Widget wrapForChip({
required Widget child,
TextDirection textDirection = TextDirection.ltr,
double textScaleFactor = 1.0,
ThemeData? theme,
}) {
return MaterialApp(
theme: theme,
home: Directionality(
textDirection: textDirection,
child: MediaQuery.withClampedTextScaling(
minScaleFactor: textScaleFactor,
maxScaleFactor: textScaleFactor,
child: Material(child: child),
),
),
);
}
Widget selectedInputChip({
Color? checkmarkColor,
bool enabled = false,
}) {
return InputChip(
label: const Text('InputChip'),
selected: true,
isEnabled: enabled,
// When [enabled] is true we also need to provide one of the chip
// callbacks, otherwise the chip would have a 'disabled'
// [MaterialState], which is not the intention.
onSelected: enabled ? (_) {} : null,
showCheckmark: true,
checkmarkColor: checkmarkColor,
);
}
Future<void> pumpCheckmarkChip(
WidgetTester tester, {
required Widget chip,
Color? themeColor,
ThemeData? theme,
}) async {
await tester.pumpWidget(
wrapForChip(
theme: theme,
child: Builder(
builder: (BuildContext context) {
final ChipThemeData chipTheme = ChipTheme.of(context);
return ChipTheme(
data: themeColor == null ? chipTheme : chipTheme.copyWith(
checkmarkColor: themeColor,
),
child: chip,
);
},
),
),
);
}
void expectCheckmarkColor(Finder finder, Color color) {
expect(
finder,
paints
// Physical model layer path
..path()
// The first layer that is painted is the selection overlay. We do not care
// how it is painted but it has to be added it to this pattern so that the
// check mark can be checked next.
..rrect()
// The second layer that is painted is the check mark.
..path(color: color),
);
}
RenderBox getMaterialBox(WidgetTester tester) {
return tester.firstRenderObject<RenderBox>(
find.descendant(
of: find.byType(InputChip),
matching: find.byType(CustomPaint),
),
);
}
Material getMaterial(WidgetTester tester) {
return tester.widget<Material>(
find.descendant(
of: find.byType(InputChip),
matching: find.byType(Material),
),
);
}
IconThemeData getIconData(WidgetTester tester) {
final IconTheme iconTheme = tester.firstWidget(
find.descendant(
of: find.byType(RawChip),
matching: find.byType(IconTheme),
),
);
return iconTheme.data;
}
void checkChipMaterialClipBehavior(WidgetTester tester, Clip clipBehavior) {
final Iterable<Material> materials = tester.widgetList<Material>(find.byType(Material));
// There should be two Material widgets, first Material is from the "_wrapForChip" and
// last Material is from the "RawChip".
expect(materials.length, 2);
// The last Material from `RawChip` should have the clip behavior.
expect(materials.last.clipBehavior, clipBehavior);
}
// Finds any container of a tooltip.
Finder findTooltipContainer(String tooltipText) {
return find.ancestor(
of: find.text(tooltipText),
matching: find.byType(Container),
);
}
void main() {
testWidgets('InputChip.color resolves material states', (WidgetTester tester) async {
const Color disabledSelectedColor = Color(0xffffff00);
const Color disabledColor = Color(0xff00ff00);
const Color backgroundColor = Color(0xff0000ff);
const Color selectedColor = Color(0xffff0000);
Widget buildApp({ required bool enabled, required bool selected }) {
return wrapForChip(
child: InputChip(
onSelected: enabled ? (bool value) { } : null,
selected: selected,
color: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled) && states.contains(MaterialState.selected)) {
return disabledSelectedColor;
}
if (states.contains(MaterialState.disabled)) {
return disabledColor;
}
if (states.contains(MaterialState.selected)) {
return selectedColor;
}
return backgroundColor;
}),
label: const Text('InputChip'),
),
);
}
// Test enabled chip.
await tester.pumpWidget(buildApp(enabled: true, selected: false));
// Enabled chip should have the provided backgroundColor.
expect(getMaterialBox(tester), paints..rrect(color: backgroundColor));
// Test disabled chip.
await tester.pumpWidget(buildApp(enabled: false, selected: false));
await tester.pumpAndSettle();
// Disabled chip should have the provided disabledColor.
expect(getMaterialBox(tester), paints..rrect(color: disabledColor));
// Test enabled & selected chip.
await tester.pumpWidget(buildApp(enabled: true, selected: true));
await tester.pumpAndSettle();
// Enabled & selected chip should have the provided selectedColor.
expect(getMaterialBox(tester), paints..rrect(color: selectedColor));
// Test disabled & selected chip.
await tester.pumpWidget(buildApp(enabled: false, selected: true));
await tester.pumpAndSettle();
// Disabled & selected chip should have the provided disabledSelectedColor.
expect(getMaterialBox(tester), paints..rrect(color: disabledSelectedColor));
});
testWidgets('InputChip uses provided state color properties', (WidgetTester tester) async {
const Color disabledColor = Color(0xff00ff00);
const Color backgroundColor = Color(0xff0000ff);
const Color selectedColor = Color(0xffff0000);
Widget buildApp({ required bool enabled, required bool selected }) {
return wrapForChip(
child: InputChip(
onSelected: enabled ? (bool value) { } : null,
selected: selected,
disabledColor: disabledColor,
backgroundColor: backgroundColor,
selectedColor: selectedColor,
label: const Text('InputChip'),
),
);
}
// Test enabled chip.
await tester.pumpWidget(buildApp(enabled: true, selected: false));
// Enabled chip should have the provided backgroundColor.
expect(getMaterialBox(tester), paints..rrect(color: backgroundColor));
// Test disabled chip.
await tester.pumpWidget(buildApp(enabled: false, selected: false));
await tester.pumpAndSettle();
// Disabled chip should have the provided disabledColor.
expect(getMaterialBox(tester), paints..rrect(color: disabledColor));
// Test enabled & selected chip.
await tester.pumpWidget(buildApp(enabled: true, selected: true));
await tester.pumpAndSettle();
// Enabled & selected chip should have the provided selectedColor.
expect(getMaterialBox(tester), paints..rrect(color: selectedColor));
});
testWidgets('InputChip can be tapped', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Material(
child: InputChip(
label: Text('input chip'),
),
),
),
);
await tester.tap(find.byType(InputChip));
expect(tester.takeException(), null);
});
testWidgets('loses focus when disabled', (WidgetTester tester) async {
final FocusNode focusNode = FocusNode(debugLabel: 'InputChip');
await tester.pumpWidget(
wrapForChip(
child: InputChip(
focusNode: focusNode,
autofocus: true,
shape: const RoundedRectangleBorder(),
avatar: const CircleAvatar(child: Text('A')),
label: const Text('Chip A'),
onPressed: () { },
),
),
);
await tester.pump();
expect(focusNode.hasPrimaryFocus, isTrue);
await tester.pumpWidget(
wrapForChip(
child: InputChip(
focusNode: focusNode,
autofocus: true,
shape: const RoundedRectangleBorder(),
avatar: const CircleAvatar(child: Text('A')),
label: const Text('Chip A'),
),
),
);
await tester.pump();
expect(focusNode.hasPrimaryFocus, isFalse);
focusNode.dispose();
});
testWidgets('cannot be traversed to when disabled', (WidgetTester tester) async {
final FocusNode focusNode1 = FocusNode(debugLabel: 'InputChip 1');
final FocusNode focusNode2 = FocusNode(debugLabel: 'InputChip 2');
await tester.pumpWidget(
wrapForChip(
child: FocusScope(
child: Column(
children: <Widget>[
InputChip(
focusNode: focusNode1,
autofocus: true,
label: const Text('Chip A'),
onPressed: () { },
),
InputChip(
focusNode: focusNode2,
autofocus: true,
label: const Text('Chip B'),
),
],
),
),
),
);
await tester.pump();
expect(focusNode1.hasPrimaryFocus, isTrue);
expect(focusNode2.hasPrimaryFocus, isFalse);
expect(focusNode1.nextFocus(), isFalse);
await tester.pump();
expect(focusNode1.hasPrimaryFocus, isTrue);
expect(focusNode2.hasPrimaryFocus, isFalse);
focusNode1.dispose();
focusNode2.dispose();
});
testWidgets('Material2 - Input chip disabled check mark color is determined by platform brightness when light', (WidgetTester tester) async {
await pumpCheckmarkChip(
tester,
chip: selectedInputChip(),
theme: ThemeData(useMaterial3: false),
);
expectCheckmarkColor(find.byType(InputChip), Colors.black.withAlpha(0xde));
});
testWidgets('Material3 - Input chip disabled check mark color is determined by platform brightness when light', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
await pumpCheckmarkChip(tester, chip: selectedInputChip(), theme: theme);
expectCheckmarkColor(find.byType(InputChip), theme.colorScheme.onSurface);
});
testWidgets('Material2 - Input chip disabled check mark color is determined by platform brightness when dark', (WidgetTester tester) async {
await pumpCheckmarkChip(
tester,
chip: selectedInputChip(),
theme: ThemeData.dark(useMaterial3: false),
);
expectCheckmarkColor(find.byType(InputChip), Colors.white.withAlpha(0xde));
});
testWidgets('Material3 - Input chip disabled check mark color is determined by platform brightness when dark', (WidgetTester tester) async {
final ThemeData theme = ThemeData.dark();
await pumpCheckmarkChip(
tester,
chip: selectedInputChip(),
theme: theme,
);
expectCheckmarkColor(find.byType(InputChip), theme.colorScheme.onSurface);
});
testWidgets('Input chip check mark color can be set by the chip theme', (WidgetTester tester) async {
await pumpCheckmarkChip(
tester,
chip: selectedInputChip(),
themeColor: const Color(0xff00ff00),
);
expectCheckmarkColor(find.byType(InputChip), const Color(0xff00ff00));
});
testWidgets('Input chip check mark color can be set by the chip constructor', (WidgetTester tester) async {
await pumpCheckmarkChip(
tester,
chip: selectedInputChip(checkmarkColor: const Color(0xff00ff00)),
);
expectCheckmarkColor(find.byType(InputChip), const Color(0xff00ff00));
});
testWidgets('Input chip check mark color is set by chip constructor even when a theme color is specified', (WidgetTester tester) async {
await pumpCheckmarkChip(
tester,
chip: selectedInputChip(checkmarkColor: const Color(0xffff0000)),
themeColor: const Color(0xff00ff00),
);
expectCheckmarkColor(find.byType(InputChip), const Color(0xffff0000));
});
testWidgets('InputChip clipBehavior properly passes through to the Material', (WidgetTester tester) async {
const Text label = Text('label');
await tester.pumpWidget(wrapForChip(child: const InputChip(label: label)));
checkChipMaterialClipBehavior(tester, Clip.none);
await tester.pumpWidget(wrapForChip(child: const InputChip(label: label, clipBehavior: Clip.antiAlias)));
checkChipMaterialClipBehavior(tester, Clip.antiAlias);
});
testWidgets('Material3 - Input chip has correct selected color when enabled', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
await pumpCheckmarkChip(
tester,
chip: selectedInputChip(enabled: true),
theme: theme,
);
final RenderBox materialBox = getMaterialBox(tester);
expect(materialBox, paints..rrect(color: theme.colorScheme.secondaryContainer));
});
testWidgets('Material3 - Input chip has correct selected color when disabled', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
await pumpCheckmarkChip(
tester,
chip: selectedInputChip(),
theme: theme,
);
final RenderBox materialBox = getMaterialBox(tester);
expect(materialBox, paints..path(color: theme.colorScheme.onSurface));
});
testWidgets('InputChip uses provided iconTheme', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
Widget buildChip({ IconThemeData? iconTheme }) {
return MaterialApp(
theme: theme,
home: Material(
child: InputChip(
iconTheme: iconTheme,
avatar: const Icon(Icons.add),
label: const Text('Test'),
),
),
);
}
// Test default icon theme.
await tester.pumpWidget(buildChip());
expect(getIconData(tester).color, theme.colorScheme.onSurfaceVariant);
// Test provided icon theme.
await tester.pumpWidget(buildChip(iconTheme: const IconThemeData(color: Color(0xff00ff00))));
expect(getIconData(tester).color, const Color(0xff00ff00));
});
testWidgets('Delete button is visible on disabled InputChip', (WidgetTester tester) async {
await tester.pumpWidget(
wrapForChip(
child: InputChip(
isEnabled: false,
label: const Text('Label'),
onDeleted: () { },
)
),
);
// Delete button should be visible.
await expectLater(find.byType(RawChip), matchesGoldenFile('input_chip.disabled.delete_button.png'));
});
testWidgets('Delete button tooltip is not shown on disabled InputChip', (WidgetTester tester) async {
Widget buildChip({ bool enabled = true }) {
return wrapForChip(
child: InputChip(
isEnabled: enabled,
label: const Text('Label'),
onDeleted: () { },
)
);
}
// Test enabled chip.
await tester.pumpWidget(buildChip());
final Offset deleteButtonLocation = tester.getCenter(find.byType(Icon));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(deleteButtonLocation);
await tester.pump();
// Delete button tooltip should be visible.
expect(findTooltipContainer('Delete'), findsOneWidget);
// Test disabled chip.
await tester.pumpWidget(buildChip(enabled: false));
await tester.pump();
// Delete button tooltip should not be visible.
expect(findTooltipContainer('Delete'), findsNothing);
});
testWidgets('InputChip avatar layout constraints can be customized', (WidgetTester tester) async {
const double border = 1.0;
const double iconSize = 18.0;
const double labelPadding = 8.0;
const double padding = 8.0;
const Size labelSize = Size(100, 100);
Widget buildChip({BoxConstraints? avatarBoxConstraints}) {
return wrapForChip(
child: Center(
child: InputChip(
avatarBoxConstraints: avatarBoxConstraints,
avatar: const Icon(Icons.favorite),
label: Container(
width: labelSize.width,
height: labelSize.width,
color: const Color(0xFFFF0000),
),
),
),
);
}
// Test default avatar layout constraints.
await tester.pumpWidget(buildChip());
expect(tester.getSize(find.byType(InputChip)).width, equals(234.0));
expect(tester.getSize(find.byType(InputChip)).height, equals(118.0));
// Calculate the distance between avatar and chip edges.
Offset chipTopLeft = tester.getTopLeft(find.byWidget(getMaterial(tester)));
final Offset avatarCenter = tester.getCenter(find.byIcon(Icons.favorite));
expect(chipTopLeft.dx, avatarCenter.dx - (labelSize.width / 2) - padding - border);
expect(chipTopLeft.dy, avatarCenter.dy - (labelSize.width / 2) - padding - border);
// Calculate the distnance between avatar and label.
Offset labelTopLeft = tester.getTopLeft(find.byType(Container));
expect(labelTopLeft.dx, avatarCenter.dx + (labelSize.width / 2) + labelPadding);
// Test custom avatar layout constraints.
await tester.pumpWidget(buildChip(avatarBoxConstraints: const BoxConstraints.tightForFinite()));
await tester.pump();
expect(tester.getSize(find.byType(InputChip)).width, equals(152.0));
expect(tester.getSize(find.byType(InputChip)).height, equals(118.0));
// Calculate the distance between avatar and chip edges.
chipTopLeft = tester.getTopLeft(find.byWidget(getMaterial(tester)));
expect(chipTopLeft.dx, avatarCenter.dx - (iconSize / 2) - padding - border);
expect(chipTopLeft.dy, avatarCenter.dy - (labelSize.width / 2) - padding - border);
// Calculate the distnance between avatar and label.
labelTopLeft = tester.getTopLeft(find.byType(Container));
expect(labelTopLeft.dx, avatarCenter.dx + (iconSize / 2) + labelPadding);
});
testWidgets('InputChip delete icon layout constraints can be customized', (WidgetTester tester) async {
const double border = 1.0;
const double iconSize = 18.0;
const double labelPadding = 8.0;
const double padding = 8.0;
const Size labelSize = Size(100, 100);
Widget buildChip({BoxConstraints? deleteIconBoxConstraints}) {
return wrapForChip(
child: Center(
child: InputChip(
deleteIconBoxConstraints: deleteIconBoxConstraints,
onDeleted: () { },
label: Container(
width: labelSize.width,
height: labelSize.width,
color: const Color(0xFFFF0000),
),
),
),
);
}
// Test default delete icon layout constraints.
await tester.pumpWidget(buildChip());
expect(tester.getSize(find.byType(InputChip)).width, equals(234.0));
expect(tester.getSize(find.byType(InputChip)).height, equals(118.0));
// Calculate the distance between delete icon and chip edges.
Offset chipTopRight = tester.getTopRight(find.byWidget(getMaterial(tester)));
final Offset deleteIconCenter = tester.getCenter(find.byIcon(Icons.clear));
expect(chipTopRight.dx, deleteIconCenter.dx + (labelSize.width / 2) + padding + border);
expect(chipTopRight.dy, deleteIconCenter.dy - (labelSize.width / 2) - padding - border);
// Calculate the distance between delete icon and label.
Offset labelTopRight = tester.getTopRight(find.byType(Container));
expect(labelTopRight.dx, deleteIconCenter.dx - (labelSize.width / 2) - labelPadding);
// Test custom avatar layout constraints.
await tester.pumpWidget(buildChip(
deleteIconBoxConstraints: const BoxConstraints.tightForFinite(),
));
await tester.pump();
expect(tester.getSize(find.byType(InputChip)).width, equals(152.0));
expect(tester.getSize(find.byType(InputChip)).height, equals(118.0));
// Calculate the distance between delete icon and chip edges.
chipTopRight = tester.getTopRight(find.byWidget(getMaterial(tester)));
expect(chipTopRight.dx, deleteIconCenter.dx + (iconSize / 2) + padding + border);
expect(chipTopRight.dy, deleteIconCenter.dy - (labelSize.width / 2) - padding - border);
// Calculate the distance between delete icon and label.
labelTopRight = tester.getTopRight(find.byType(Container));
expect(labelTopRight.dx, deleteIconCenter.dx - (iconSize / 2) - labelPadding);
});
}
| flutter/packages/flutter/test/material/input_chip_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/input_chip_test.dart",
"repo_id": "flutter",
"token_count": 7536
} | 841 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
void onPressed(TestMenu item) {}
Finder findMenuPanels(Axis orientation) {
return find.byWidgetPredicate((Widget widget) {
return widget.runtimeType.toString() == '_MenuPanel' && (widget as dynamic).orientation == orientation;
});
}
Finder findMenuBarPanel() {
return findMenuPanels(Axis.horizontal);
}
Finder findSubmenuPanel() {
return findMenuPanels(Axis.vertical);
}
Finder findSubMenuItem() {
return find.descendant(of: findSubmenuPanel().last, matching: find.byType(MenuItemButton));
}
Material getMenuBarPanelMaterial(WidgetTester tester) {
return tester.widget<Material>(find.descendant(of: findMenuBarPanel(), matching: find.byType(Material)).first);
}
Material getSubmenuPanelMaterial(WidgetTester tester) {
return tester.widget<Material>(find.descendant(of: findSubmenuPanel(), matching: find.byType(Material)).first);
}
DefaultTextStyle getLabelStyle(WidgetTester tester, String labelText) {
return tester.widget<DefaultTextStyle>(
find
.ancestor(
of: find.text(labelText),
matching: find.byType(DefaultTextStyle),
)
.first,
);
}
test('MenuThemeData lerp special cases', () {
expect(MenuThemeData.lerp(null, null, 0), null);
const MenuThemeData data = MenuThemeData();
expect(identical(MenuThemeData.lerp(data, data, 0.5), data), true);
});
testWidgets('theme is honored', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Builder(builder: (BuildContext context) {
return MenuBarTheme(
data: const MenuBarThemeData(
style: MenuStyle(
backgroundColor: MaterialStatePropertyAll<Color?>(Colors.green),
elevation: MaterialStatePropertyAll<double?>(20.0),
),
),
child: MenuTheme(
data: const MenuThemeData(
style: MenuStyle(
backgroundColor: MaterialStatePropertyAll<Color?>(Colors.red),
elevation: MaterialStatePropertyAll<double?>(15.0),
shape: MaterialStatePropertyAll<OutlinedBorder?>(StadiumBorder()),
padding: MaterialStatePropertyAll<EdgeInsetsGeometry>(
EdgeInsetsDirectional.all(10.0),
),
),
),
child: Column(
children: <Widget>[
MenuBar(
children: createTestMenus(onPressed: onPressed),
),
const Expanded(child: Placeholder()),
],
),
),
);
}),
),
),
);
// Open a test menu.
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
expect(tester.getRect(findMenuBarPanel().first), equals(const Rect.fromLTRB(234.0, 0.0, 566.0, 48.0)));
final Material menuBarMaterial = getMenuBarPanelMaterial(tester);
expect(menuBarMaterial.elevation, equals(20));
expect(menuBarMaterial.color, equals(Colors.green));
final Material subMenuMaterial = getSubmenuPanelMaterial(tester);
expect(tester.getRect(findSubmenuPanel()), equals(const Rect.fromLTRB(336.0, 48.0, 570.0, 212.0)));
expect(subMenuMaterial.elevation, equals(15));
expect(subMenuMaterial.color, equals(Colors.red));
});
testWidgets('Constructor parameters override theme parameters',
(WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Builder(
builder: (BuildContext context) {
return MenuBarTheme(
data: const MenuBarThemeData(
style: MenuStyle(
backgroundColor: MaterialStatePropertyAll<Color?>(Colors.green),
elevation: MaterialStatePropertyAll<double?>(20.0),
),
),
child: MenuTheme(
data: const MenuThemeData(
style: MenuStyle(
backgroundColor: MaterialStatePropertyAll<Color?>(Colors.red),
elevation: MaterialStatePropertyAll<double?>(15.0),
shape: MaterialStatePropertyAll<OutlinedBorder?>(StadiumBorder()),
padding: MaterialStatePropertyAll<EdgeInsetsGeometry>(
EdgeInsetsDirectional.all(10.0),
),
),
),
child: Column(
children: <Widget>[
MenuBar(
style: const MenuStyle(
backgroundColor: MaterialStatePropertyAll<Color?>(Colors.blue),
elevation: MaterialStatePropertyAll<double?>(10.0),
padding: MaterialStatePropertyAll<EdgeInsetsGeometry>(
EdgeInsetsDirectional.all(12.0),
),
),
children: createTestMenus(
onPressed: onPressed,
menuBackground: Colors.cyan,
menuElevation: 18.0,
menuPadding: const EdgeInsetsDirectional.all(14.0),
menuShape: const BeveledRectangleBorder(),
itemBackground: Colors.amber,
itemForeground: Colors.grey,
itemOverlay: Colors.blueGrey,
itemPadding: const EdgeInsetsDirectional.all(11.0),
itemShape: const StadiumBorder(),
),
),
const Expanded(child: Placeholder()),
],
),
),
);
},
),
),
),
);
// Open a test menu.
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
expect(tester.getRect(findMenuBarPanel().first), equals(const Rect.fromLTRB(226.0, 0.0, 574.0, 72.0)));
final Material menuBarMaterial = getMenuBarPanelMaterial(tester);
expect(menuBarMaterial.elevation, equals(10.0));
expect(menuBarMaterial.color, equals(Colors.blue));
final Material subMenuMaterial = getSubmenuPanelMaterial(tester);
expect(tester.getRect(findSubmenuPanel()), equals(const Rect.fromLTRB(332.0, 60.0, 574.0, 232.0)));
expect(subMenuMaterial.elevation, equals(18));
expect(subMenuMaterial.color, equals(Colors.cyan));
expect(subMenuMaterial.shape, equals(const BeveledRectangleBorder()));
final Finder menuItem = findSubMenuItem();
expect(tester.getRect(menuItem.first), equals(const Rect.fromLTRB(346.0, 74.0, 560.0, 122.0)));
final Material menuItemMaterial = tester.widget<Material>(
find.ancestor(of: find.text(TestMenu.subMenu10.label), matching: find.byType(Material)).first);
expect(menuItemMaterial.color, equals(Colors.amber));
expect(menuItemMaterial.elevation, equals(0.0));
expect(menuItemMaterial.shape, equals(const StadiumBorder()));
expect(getLabelStyle(tester, TestMenu.subMenu10.label).style.color, equals(Colors.grey));
final ButtonStyle? textButtonStyle = tester
.widget<TextButton>(find
.ancestor(
of: find.text(TestMenu.subMenu10.label),
matching: find.byType(TextButton),
)
.first)
.style;
expect(textButtonStyle?.overlayColor?.resolve(<MaterialState>{MaterialState.hovered}), equals(Colors.blueGrey));
});
}
List<Widget> createTestMenus({
void Function(TestMenu)? onPressed,
void Function(TestMenu)? onOpen,
void Function(TestMenu)? onClose,
Map<TestMenu, MenuSerializableShortcut> shortcuts = const <TestMenu, MenuSerializableShortcut>{},
bool includeStandard = false,
Color? itemOverlay,
Color? itemBackground,
Color? itemForeground,
EdgeInsetsDirectional? itemPadding,
Color? menuBackground,
EdgeInsetsDirectional? menuPadding,
OutlinedBorder? menuShape,
double? menuElevation,
OutlinedBorder? itemShape,
}) {
final MenuStyle menuStyle = MenuStyle(
padding: menuPadding != null ? MaterialStatePropertyAll<EdgeInsetsGeometry>(menuPadding) : null,
backgroundColor: menuBackground != null ? MaterialStatePropertyAll<Color>(menuBackground) : null,
elevation: menuElevation != null ? MaterialStatePropertyAll<double>(menuElevation) : null,
shape: menuShape != null ? MaterialStatePropertyAll<OutlinedBorder>(menuShape) : null,
);
final ButtonStyle itemStyle = ButtonStyle(
padding: itemPadding != null ? MaterialStatePropertyAll<EdgeInsetsGeometry>(itemPadding) : null,
shape: itemShape != null ? MaterialStatePropertyAll<OutlinedBorder>(itemShape) : null,
foregroundColor: itemForeground != null ? MaterialStatePropertyAll<Color>(itemForeground) : null,
backgroundColor: itemBackground != null ? MaterialStatePropertyAll<Color>(itemBackground) : null,
overlayColor: itemOverlay != null ? MaterialStatePropertyAll<Color>(itemOverlay) : null,
);
final List<Widget> result = <Widget>[
SubmenuButton(
onOpen: onOpen != null ? () => onOpen(TestMenu.mainMenu0) : null,
onClose: onClose != null ? () => onClose(TestMenu.mainMenu0) : null,
menuChildren: <Widget>[
MenuItemButton(
onPressed: onPressed != null ? () => onPressed(TestMenu.subMenu00) : null,
shortcut: shortcuts[TestMenu.subMenu00],
child: Text(TestMenu.subMenu00.label),
),
],
child: Text(TestMenu.mainMenu0.label),
),
SubmenuButton(
onOpen: onOpen != null ? () => onOpen(TestMenu.mainMenu1) : null,
onClose: onClose != null ? () => onClose(TestMenu.mainMenu1) : null,
menuStyle: menuStyle,
menuChildren: <Widget>[
MenuItemButton(
onPressed: onPressed != null ? () => onPressed(TestMenu.subMenu10) : null,
shortcut: shortcuts[TestMenu.subMenu10],
style: itemStyle,
child: Text(TestMenu.subMenu10.label),
),
SubmenuButton(
onOpen: onOpen != null ? () => onOpen(TestMenu.subMenu11) : null,
onClose: onClose != null ? () => onClose(TestMenu.subMenu11) : null,
menuChildren: <Widget>[
MenuItemButton(
onPressed: onPressed != null ? () => onPressed(TestMenu.subSubMenu110) : null,
shortcut: shortcuts[TestMenu.subSubMenu110],
child: Text(TestMenu.subSubMenu110.label),
),
MenuItemButton(
onPressed: onPressed != null ? () => onPressed(TestMenu.subSubMenu111) : null,
shortcut: shortcuts[TestMenu.subSubMenu111],
child: Text(TestMenu.subSubMenu111.label),
),
MenuItemButton(
onPressed: onPressed != null ? () => onPressed(TestMenu.subSubMenu112) : null,
shortcut: shortcuts[TestMenu.subSubMenu112],
child: Text(TestMenu.subSubMenu112.label),
),
MenuItemButton(
onPressed: onPressed != null ? () => onPressed(TestMenu.subSubMenu113) : null,
shortcut: shortcuts[TestMenu.subSubMenu113],
child: Text(TestMenu.subSubMenu113.label),
),
],
child: Text(TestMenu.subMenu11.label),
),
MenuItemButton(
onPressed: onPressed != null ? () => onPressed(TestMenu.subMenu12) : null,
shortcut: shortcuts[TestMenu.subMenu12],
child: Text(TestMenu.subMenu12.label),
),
],
child: Text(TestMenu.mainMenu1.label),
),
SubmenuButton(
onOpen: onOpen != null ? () => onOpen(TestMenu.mainMenu2) : null,
onClose: onClose != null ? () => onClose(TestMenu.mainMenu2) : null,
menuChildren: <Widget>[
MenuItemButton(
// Always disabled.
shortcut: shortcuts[TestMenu.subMenu20],
// Always disabled.
child: Text(TestMenu.subMenu20.label),
),
],
child: Text(TestMenu.mainMenu2.label),
),
];
return result;
}
enum TestMenu {
mainMenu0('Menu 0'),
mainMenu1('Menu 1'),
mainMenu2('Menu 2'),
subMenu00('Sub Menu 00'),
subMenu10('Sub Menu 10'),
subMenu11('Sub Menu 11'),
subMenu12('Sub Menu 12'),
subMenu20('Sub Menu 20'),
subSubMenu110('Sub Sub Menu 110'),
subSubMenu111('Sub Sub Menu 111'),
subSubMenu112('Sub Sub Menu 112'),
subSubMenu113('Sub Sub Menu 113');
const TestMenu(this.label);
final String label;
}
| flutter/packages/flutter/test/material/menu_theme_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/menu_theme_test.dart",
"repo_id": "flutter",
"token_count": 5795
} | 842 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
PopupMenuThemeData _popupMenuThemeM2() {
return PopupMenuThemeData(
color: Colors.orange,
shape: const BeveledRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(12))),
elevation: 12.0,
textStyle: const TextStyle(color: Color(0xffffffff), textBaseline: TextBaseline.alphabetic),
mouseCursor: MaterialStateProperty.resolveWith<MouseCursor?>((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return SystemMouseCursors.contextMenu;
}
return SystemMouseCursors.alias;
}),
);
}
PopupMenuThemeData _popupMenuThemeM3() {
return PopupMenuThemeData(
color: Colors.orange,
shape: const BeveledRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(12))),
elevation: 12.0,
shadowColor: const Color(0xff00ff00),
surfaceTintColor: const Color(0xff00ff00),
labelTextStyle: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return const TextStyle(color: Color(0xfff99ff0), fontSize: 12.0);
}
return const TextStyle(color: Color(0xfff12099), fontSize: 17.0);
}),
mouseCursor: MaterialStateProperty.resolveWith<MouseCursor?>((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return SystemMouseCursors.contextMenu;
}
return SystemMouseCursors.alias;
}),
iconColor: const Color(0xfff12099),
iconSize: 17.0,
);
}
void main() {
test('PopupMenuThemeData copyWith, ==, hashCode basics', () {
expect(const PopupMenuThemeData(), const PopupMenuThemeData().copyWith());
expect(const PopupMenuThemeData().hashCode, const PopupMenuThemeData().copyWith().hashCode);
});
test('PopupMenuThemeData lerp special cases', () {
expect(PopupMenuThemeData.lerp(null, null, 0), null);
const PopupMenuThemeData data = PopupMenuThemeData();
expect(identical(PopupMenuThemeData.lerp(data, data, 0.5), data), true);
});
test('PopupMenuThemeData null fields by default', () {
const PopupMenuThemeData popupMenuTheme = PopupMenuThemeData();
expect(popupMenuTheme.color, null);
expect(popupMenuTheme.shape, null);
expect(popupMenuTheme.elevation, null);
expect(popupMenuTheme.shadowColor, null);
expect(popupMenuTheme.surfaceTintColor, null);
expect(popupMenuTheme.textStyle, null);
expect(popupMenuTheme.labelTextStyle, null);
expect(popupMenuTheme.enableFeedback, null);
expect(popupMenuTheme.mouseCursor, null);
});
testWidgets('Default PopupMenuThemeData debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const PopupMenuThemeData().debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(description, <String>[]);
});
testWidgets('PopupMenuThemeData implements debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
PopupMenuThemeData(
color: const Color(0xfffffff1),
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2.0))),
elevation: 2.0,
shadowColor: const Color(0xfffffff2),
surfaceTintColor: const Color(0xfffffff3),
textStyle: const TextStyle(color: Color(0xfffffff4)),
labelTextStyle: MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled)) {
return const TextStyle(color: Color(0xfffffff5), fontSize: 12.0);
}
return const TextStyle(color: Color(0xfffffff6), fontSize: 17.0);
}),
enableFeedback: false,
mouseCursor: MaterialStateMouseCursor.clickable,
position: PopupMenuPosition.over,
iconColor: const Color(0xfffffff8),
iconSize: 31.0,
).debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(description, <String>[
'color: Color(0xfffffff1)',
'shape: RoundedRectangleBorder(BorderSide(width: 0.0, style: none), BorderRadius.circular(2.0))',
'elevation: 2.0',
'shadowColor: Color(0xfffffff2)',
'surfaceTintColor: Color(0xfffffff3)',
'text style: TextStyle(inherit: true, color: Color(0xfffffff4))',
"labelTextStyle: Instance of '_WidgetStatePropertyWith<TextStyle?>'",
'enableFeedback: false',
'mouseCursor: WidgetStateMouseCursor(clickable)',
'position: over',
'iconColor: Color(0xfffffff8)',
'iconSize: 31.0'
]);
});
testWidgets('Passing no PopupMenuThemeData returns defaults', (WidgetTester tester) async {
final Key popupButtonKey = UniqueKey();
final Key popupButtonApp = UniqueKey();
final Key enabledPopupItemKey = UniqueKey();
final Key disabledPopupItemKey = UniqueKey();
final ThemeData theme = ThemeData(useMaterial3: true);
await tester.pumpWidget(MaterialApp(
theme: theme,
key: popupButtonApp,
home: Material(
child: Column(
children: <Widget>[
Padding(
// The padding makes sure the menu has enough space around it to
// get properly aligned when displayed (`_kMenuScreenPadding`).
padding: const EdgeInsets.all(8.0),
child: PopupMenuButton<void>(
key: popupButtonKey,
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<void>>[
PopupMenuItem<void>(
key: enabledPopupItemKey,
child: const Text('Enabled PopupMenuItem'),
),
const PopupMenuDivider(),
PopupMenuItem<void>(
key: disabledPopupItemKey,
enabled: false,
child: const Text('Disabled PopupMenuItem'),
),
const CheckedPopupMenuItem<void>(
child: Text('Unchecked item'),
),
const CheckedPopupMenuItem<void>(
checked: true,
child: Text('Checked item'),
),
];
},
),
),
],
),
),
));
// Test default button icon color.
expect(_iconStyle(tester, Icons.adaptive.more)?.color, theme.iconTheme.color);
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
/// The last Material widget under popupButtonApp is the [PopupMenuButton]
/// specified above, so by finding the last descendent of popupButtonApp
/// that is of type Material, this code retrieves the built
/// [PopupMenuButton].
final Material button = tester.widget<Material>(
find.descendant(
of: find.byKey(popupButtonApp),
matching: find.byType(Material),
).last,
);
expect(button.color, theme.colorScheme.surfaceContainer);
expect(button.shadowColor, theme.colorScheme.shadow);
expect(button.surfaceTintColor, Colors.transparent);
expect(button.shape, RoundedRectangleBorder(borderRadius: BorderRadius.circular(4.0)));
expect(button.elevation, 3.0);
/// The last DefaultTextStyle widget under popupItemKey is the
/// [PopupMenuItem] specified above, so by finding the last descendent of
/// popupItemKey that is of type DefaultTextStyle, this code retrieves the
/// built [PopupMenuItem].
DefaultTextStyle popupMenuItemLabel = tester.widget<DefaultTextStyle>(
find.descendant(
of: find.byKey(enabledPopupItemKey),
matching: find.byType(DefaultTextStyle),
).last,
);
expect(popupMenuItemLabel.style.fontFamily, 'Roboto');
expect(popupMenuItemLabel.style.color, theme.colorScheme.onSurface);
/// Test disabled text color
popupMenuItemLabel = tester.widget<DefaultTextStyle>(
find.descendant(
of: find.byKey(disabledPopupItemKey),
matching: find.byType(DefaultTextStyle),
).last,
);
expect(popupMenuItemLabel.style.color, theme.colorScheme.onSurface.withOpacity(0.38));
final Offset topLeftButton = tester.getTopLeft(find.byType(PopupMenuButton<void>));
final Offset topLeftMenu = tester.getTopLeft(find.byWidget(button));
expect(topLeftMenu, topLeftButton);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
addTearDown(gesture.removePointer);
await gesture.moveTo(tester.getCenter(find.byKey(disabledPopupItemKey)));
await tester.pumpAndSettle();
expect(
RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1),
SystemMouseCursors.basic,
);
await gesture.down(tester.getCenter(find.byKey(enabledPopupItemKey)));
await tester.pumpAndSettle();
expect(
RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1),
SystemMouseCursors.click,
);
// Test unchecked CheckedPopupMenuItem label.
ListTile listTile = tester.widget<ListTile>(find.byType(ListTile).first);
expect(listTile.titleTextStyle?.color, theme.colorScheme.onSurface);
// Test checked CheckedPopupMenuItem label.
listTile = tester.widget<ListTile>(find.byType(ListTile).last);
expect(listTile.titleTextStyle?.color, theme.colorScheme.onSurface);
});
testWidgets('Popup menu uses values from PopupMenuThemeData', (WidgetTester tester) async {
final PopupMenuThemeData popupMenuTheme = _popupMenuThemeM3();
final Key popupButtonKey = UniqueKey();
final Key popupButtonApp = UniqueKey();
final Key enabledPopupItemKey = UniqueKey();
final Key disabledPopupItemKey = UniqueKey();
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: true, popupMenuTheme: popupMenuTheme),
key: popupButtonApp,
home: Material(
child: Column(
children: <Widget>[
PopupMenuButton<void>(
// The padding is used in the positioning of the menu when the
// position is `PopupMenuPosition.under`. Setting it to zero makes
// it easier to test.
padding: EdgeInsets.zero,
key: popupButtonKey,
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<Object>>[
PopupMenuItem<Object>(
key: disabledPopupItemKey,
enabled: false,
child: const Text('disabled'),
),
const PopupMenuDivider(),
PopupMenuItem<Object>(
key: enabledPopupItemKey,
onTap: () { },
child: const Text('enabled'),
),
const CheckedPopupMenuItem<Object>(
child: Text('Unchecked item'),
),
const CheckedPopupMenuItem<Object>(
checked: true,
child: Text('Checked item'),
),
];
},
),
],
),
),
));
expect(_iconStyle(tester, Icons.adaptive.more)?.color, popupMenuTheme.iconColor);
expect(tester.getSize(find.byIcon(Icons.adaptive.more)), Size(popupMenuTheme.iconSize!, popupMenuTheme.iconSize!));
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
/// The last Material widget under popupButtonApp is the [PopupMenuButton]
/// specified above, so by finding the last descendent of popupButtonApp
/// that is of type Material, this code retrieves the built
/// [PopupMenuButton].
final Material button = tester.widget<Material>(
find.descendant(
of: find.byKey(popupButtonApp),
matching: find.byType(Material),
).last,
);
expect(button.color, Colors.orange);
expect(button.surfaceTintColor, const Color(0xff00ff00));
expect(button.shadowColor, const Color(0xff00ff00));
expect(button.shape, const BeveledRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(12))));
expect(button.elevation, 12.0);
DefaultTextStyle popupMenuItemLabel = tester.widget<DefaultTextStyle>(
find.descendant(
of: find.byKey(enabledPopupItemKey),
matching: find.byType(DefaultTextStyle),
).last,
);
expect(
popupMenuItemLabel.style,
popupMenuTheme.labelTextStyle?.resolve(enabled),
);
/// Test disabled text color
popupMenuItemLabel = tester.widget<DefaultTextStyle>(
find.descendant(
of: find.byKey(disabledPopupItemKey),
matching: find.byType(DefaultTextStyle),
).last,
);
expect(
popupMenuItemLabel.style,
popupMenuTheme.labelTextStyle?.resolve(disabled),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
addTearDown(gesture.removePointer);
await gesture.moveTo(tester.getCenter(find.byKey(disabledPopupItemKey)));
await tester.pumpAndSettle();
expect(
RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1),
popupMenuTheme.mouseCursor?.resolve(disabled),
);
await gesture.down(tester.getCenter(find.byKey(enabledPopupItemKey)));
await tester.pumpAndSettle();
expect(
RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1),
popupMenuTheme.mouseCursor?.resolve(enabled),
);
// Test unchecked CheckedPopupMenuItem label.
ListTile listTile = tester.widget<ListTile>(find.byType(ListTile).first);
expect(listTile.titleTextStyle, popupMenuTheme.labelTextStyle?.resolve(enabled));
// Test checked CheckedPopupMenuItem label.
listTile = tester.widget<ListTile>(find.byType(ListTile).last);
expect(listTile.titleTextStyle, popupMenuTheme.labelTextStyle?.resolve(enabled));
});
testWidgets('Popup menu widget properties take priority over theme', (WidgetTester tester) async {
final PopupMenuThemeData popupMenuTheme = _popupMenuThemeM3();
final Key popupButtonKey = UniqueKey();
final Key popupButtonApp = UniqueKey();
final Key popupItemKey = UniqueKey();
const Color color = Color(0xfff11fff);
const Color surfaceTintColor = Color(0xfff12fff);
const Color shadowColor = Color(0xfff13fff);
const ShapeBorder shape = RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(9.0)),
);
const double elevation = 7.0;
const TextStyle textStyle = TextStyle(color: Color(0xfff14fff), fontSize: 19.0);
const MouseCursor cursor = SystemMouseCursors.forbidden;
const Color iconColor = Color(0xfff15fff);
const double iconSize = 21.5;
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: true, popupMenuTheme: popupMenuTheme),
key: popupButtonApp,
home: Material(
child: Column(
children: <Widget>[
PopupMenuButton<void>(
key: popupButtonKey,
elevation: elevation,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
color: color,
shape: shape,
iconColor: iconColor,
iconSize: iconSize,
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<void>>[
PopupMenuItem<void>(
key: popupItemKey,
labelTextStyle: MaterialStateProperty.all<TextStyle>(textStyle),
mouseCursor: cursor,
child: const Text('Example'),
),
CheckedPopupMenuItem<void>(
checked: true,
labelTextStyle: MaterialStateProperty.all<TextStyle>(textStyle),
child: const Text('Checked item'),
)
];
},
),
],
),
),
));
expect(_iconStyle(tester, Icons.adaptive.more)?.color, iconColor);
expect(tester.getSize(find.byIcon(Icons.adaptive.more)), const Size(iconSize, iconSize));
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
/// The last Material widget under popupButtonApp is the [PopupMenuButton]
/// specified above, so by finding the last descendent of popupButtonApp
/// that is of type Material, this code retrieves the built
/// [PopupMenuButton].
final Material button = tester.widget<Material>(
find.descendant(
of: find.byKey(popupButtonApp),
matching: find.byType(Material),
).last,
);
expect(button.color, color);
expect(button.shape, shape);
expect(button.elevation, elevation);
expect(button.shadowColor, shadowColor);
expect(button.surfaceTintColor, surfaceTintColor);
/// The last DefaultTextStyle widget under popupItemKey is the
/// [PopupMenuItem] specified above, so by finding the last descendent of
/// popupItemKey that is of type DefaultTextStyle, this code retrieves the
/// built [PopupMenuItem].
final DefaultTextStyle text = tester.widget<DefaultTextStyle>(
find.descendant(
of: find.byKey(popupItemKey),
matching: find.byType(DefaultTextStyle),
).last,
);
expect(text.style, textStyle);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
addTearDown(gesture.removePointer);
await gesture.moveTo(tester.getCenter(find.byKey(popupItemKey)));
await tester.pumpAndSettle();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), cursor);
// Test CheckedPopupMenuItem label.
final ListTile listTile = tester.widget<ListTile>(find.byType(ListTile).first);
expect(listTile.titleTextStyle, textStyle);
});
group('Material 2', () {
// These tests are only relevant for Material 2. Once Material 2
// support is deprecated and the APIs are removed, these tests
// can be deleted.
testWidgets('Passing no PopupMenuThemeData returns defaults', (WidgetTester tester) async {
final Key popupButtonKey = UniqueKey();
final Key popupButtonApp = UniqueKey();
final Key enabledPopupItemKey = UniqueKey();
final Key disabledPopupItemKey = UniqueKey();
final ThemeData theme = ThemeData(useMaterial3: false);
await tester.pumpWidget(MaterialApp(
theme: theme,
key: popupButtonApp,
home: Material(
child: Column(
children: <Widget>[
Padding(
// The padding makes sure the menu has enough space around it to
// get properly aligned when displayed (`_kMenuScreenPadding`).
padding: const EdgeInsets.all(8.0),
child: PopupMenuButton<void>(
key: popupButtonKey,
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<void>>[
PopupMenuItem<void>(
key: enabledPopupItemKey,
child: const Text('Enabled PopupMenuItem'),
),
const PopupMenuDivider(),
PopupMenuItem<void>(
key: disabledPopupItemKey,
enabled: false,
child: const Text('Disabled PopupMenuItem'),
),
];
},
),
),
],
),
),
));
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
/// The last Material widget under popupButtonApp is the [PopupMenuButton]
/// specified above, so by finding the last descendent of popupButtonApp
/// that is of type Material, this code retrieves the built
/// [PopupMenuButton].
final Material button = tester.widget<Material>(
find.descendant(
of: find.byKey(popupButtonApp),
matching: find.byType(Material),
).last,
);
expect(button.color, null);
expect(button.shape, null);
expect(button.elevation, 8.0);
/// The last DefaultTextStyle widget under popupItemKey is the
/// [PopupMenuItem] specified above, so by finding the last descendent of
/// popupItemKey that is of type DefaultTextStyle, this code retrieves the
/// built [PopupMenuItem].
final DefaultTextStyle enabledText = tester.widget<DefaultTextStyle>(
find.descendant(
of: find.byKey(enabledPopupItemKey),
matching: find.byType(DefaultTextStyle),
).last,
);
expect(enabledText.style.fontFamily, 'Roboto');
expect(enabledText.style.color, const Color(0xdd000000));
/// Test disabled text color
final DefaultTextStyle disabledText = tester.widget<DefaultTextStyle>(
find.descendant(
of: find.byKey(disabledPopupItemKey),
matching: find.byType(DefaultTextStyle),
).last,
);
expect(disabledText.style.color, theme.disabledColor);
final Offset topLeftButton = tester.getTopLeft(find.byType(PopupMenuButton<void>));
final Offset topLeftMenu = tester.getTopLeft(find.byWidget(button));
expect(topLeftMenu, topLeftButton);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
addTearDown(gesture.removePointer);
await gesture.moveTo(tester.getCenter(find.byKey(disabledPopupItemKey)));
await tester.pumpAndSettle();
expect(
RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1),
SystemMouseCursors.basic,
);
await gesture.down(tester.getCenter(find.byKey(enabledPopupItemKey)));
await tester.pumpAndSettle();
expect(
RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1),
SystemMouseCursors.click,
);
});
testWidgets('Popup menu uses values from PopupMenuThemeData', (WidgetTester tester) async {
final PopupMenuThemeData popupMenuTheme = _popupMenuThemeM2();
final Key popupButtonKey = UniqueKey();
final Key popupButtonApp = UniqueKey();
final Key enabledPopupItemKey = UniqueKey();
final Key disabledPopupItemKey = UniqueKey();
await tester.pumpWidget(MaterialApp(
theme: ThemeData(popupMenuTheme: popupMenuTheme, useMaterial3: false),
key: popupButtonApp,
home: Material(
child: Column(
children: <Widget>[
PopupMenuButton<void>(
// The padding is used in the positioning of the menu when the
// position is `PopupMenuPosition.under`. Setting it to zero makes
// it easier to test.
padding: EdgeInsets.zero,
key: popupButtonKey,
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<Object>>[
PopupMenuItem<Object>(
key: disabledPopupItemKey,
enabled: false,
child: const Text('disabled'),
),
const PopupMenuDivider(),
PopupMenuItem<Object>(
key: enabledPopupItemKey,
onTap: () { },
child: const Text('enabled'),
),
];
},
),
],
),
),
));
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
/// The last Material widget under popupButtonApp is the [PopupMenuButton]
/// specified above, so by finding the last descendent of popupButtonApp
/// that is of type Material, this code retrieves the built
/// [PopupMenuButton].
final Material button = tester.widget<Material>(
find.descendant(
of: find.byKey(popupButtonApp),
matching: find.byType(Material),
).last,
);
expect(button.color, popupMenuTheme.color);
expect(button.shape, popupMenuTheme.shape);
expect(button.elevation, popupMenuTheme.elevation);
/// The last DefaultTextStyle widget under popupItemKey is the
/// [PopupMenuItem] specified above, so by finding the last descendent of
/// popupItemKey that is of type DefaultTextStyle, this code retrieves the
/// built [PopupMenuItem].
final DefaultTextStyle text = tester.widget<DefaultTextStyle>(
find.descendant(
of: find.byKey(enabledPopupItemKey),
matching: find.byType(DefaultTextStyle),
).last,
);
expect(text.style, popupMenuTheme.textStyle);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
addTearDown(gesture.removePointer);
await gesture.moveTo(tester.getCenter(find.byKey(disabledPopupItemKey)));
await tester.pumpAndSettle();
expect(
RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1),
popupMenuTheme.mouseCursor?.resolve(disabled),
);
await gesture.down(tester.getCenter(find.byKey(enabledPopupItemKey)));
await tester.pumpAndSettle();
expect(
RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1),
popupMenuTheme.mouseCursor?.resolve(enabled),
);
});
testWidgets('Popup menu widget properties take priority over theme', (WidgetTester tester) async {
final PopupMenuThemeData popupMenuTheme = _popupMenuThemeM2();
final Key popupButtonKey = UniqueKey();
final Key popupButtonApp = UniqueKey();
final Key popupItemKey = UniqueKey();
const Color color = Colors.purple;
const Color surfaceTintColor = Colors.amber;
const Color shadowColor = Colors.green;
const ShapeBorder shape = RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(9.0)),
);
const double elevation = 7.0;
const TextStyle textStyle = TextStyle(color: Color(0xffffffef), fontSize: 19.0);
const MouseCursor cursor = SystemMouseCursors.forbidden;
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: true, popupMenuTheme: popupMenuTheme),
key: popupButtonApp,
home: Material(
child: Column(
children: <Widget>[
PopupMenuButton<void>(
key: popupButtonKey,
elevation: elevation,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
color: color,
shape: shape,
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<void>>[
PopupMenuItem<void>(
key: popupItemKey,
labelTextStyle: MaterialStateProperty.all<TextStyle>(textStyle),
mouseCursor: cursor,
child: const Text('Example'),
),
];
},
),
],
),
),
));
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
/// The last Material widget under popupButtonApp is the [PopupMenuButton]
/// specified above, so by finding the last descendent of popupButtonApp
/// that is of type Material, this code retrieves the built
/// [PopupMenuButton].
final Material button = tester.widget<Material>(
find.descendant(
of: find.byKey(popupButtonApp),
matching: find.byType(Material),
).last,
);
expect(button.color, color);
expect(button.shape, shape);
expect(button.elevation, elevation);
expect(button.shadowColor, shadowColor);
expect(button.surfaceTintColor, surfaceTintColor);
/// The last DefaultTextStyle widget under popupItemKey is the
/// [PopupMenuItem] specified above, so by finding the last descendent of
/// popupItemKey that is of type DefaultTextStyle, this code retrieves the
/// built [PopupMenuItem].
final DefaultTextStyle text = tester.widget<DefaultTextStyle>(
find.descendant(
of: find.byKey(popupItemKey),
matching: find.byType(DefaultTextStyle),
).last,
);
expect(text.style, textStyle);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
addTearDown(gesture.removePointer);
await gesture.moveTo(tester.getCenter(find.byKey(popupItemKey)));
await tester.pumpAndSettle();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), cursor);
});
});
}
Set<MaterialState> enabled = <MaterialState>{};
Set<MaterialState> disabled = <MaterialState>{MaterialState.disabled};
TextStyle? _iconStyle(WidgetTester tester, IconData icon) {
return tester.widget<RichText>(find.descendant(
of: find.byIcon(icon),
matching: find.byType(RichText),
)).text.style;
}
| flutter/packages/flutter/test/material/popup_menu_theme_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/popup_menu_theme_test.dart",
"repo_id": "flutter",
"token_count": 12421
} | 843 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/clipboard_utils.dart';
import '../widgets/semantics_tester.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final MockClipboard mockClipboard = MockClipboard();
setUp(() async {
// Fill the clipboard so that the Paste option is available in the text
// selection menu.
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall);
await Clipboard.setData(const ClipboardData(text: 'Clipboard data'));
});
tearDown(() {
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, null);
});
testWidgets('Changing query moves cursor to the end of query', (WidgetTester tester) async {
final _TestSearchDelegate delegate = _TestSearchDelegate();
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(delegate: delegate));
await tester.tap(find.byTooltip('Search'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
delegate.query = 'Foo';
final TextField textField = tester.widget<TextField>(find.byType(TextField));
expect(
textField.controller!.selection,
TextSelection(
baseOffset: delegate.query.length,
extentOffset: delegate.query.length,
),
);
});
testWidgets('Can open and close search', (WidgetTester tester) async {
final _TestSearchDelegate delegate = _TestSearchDelegate();
addTearDown(() => delegate.dispose());
final List<String> selectedResults = <String>[];
await tester.pumpWidget(TestHomePage(
delegate: delegate,
results: selectedResults,
));
// We are on the homepage
expect(find.text('HomeBody'), findsOneWidget);
expect(find.text('HomeTitle'), findsOneWidget);
expect(find.text('Suggestions'), findsNothing);
// Open search
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
expect(find.text('HomeBody'), findsNothing);
expect(find.text('HomeTitle'), findsNothing);
expect(find.text('Suggestions'), findsOneWidget);
expect(selectedResults, hasLength(0));
final TextField textField = tester.widget(find.byType(TextField));
expect(textField.focusNode!.hasFocus, isTrue);
// Close search
await tester.tap(find.byTooltip('Back'));
await tester.pumpAndSettle();
expect(find.text('HomeBody'), findsOneWidget);
expect(find.text('HomeTitle'), findsOneWidget);
expect(find.text('Suggestions'), findsNothing);
expect(selectedResults, <String>['Result']);
});
testWidgets('Can close search with system back button to return null', (WidgetTester tester) async {
// regression test for https://github.com/flutter/flutter/issues/18145
final _TestSearchDelegate delegate = _TestSearchDelegate();
addTearDown(() => delegate.dispose());
final List<String?> selectedResults = <String?>[];
await tester.pumpWidget(TestHomePage(
delegate: delegate,
results: selectedResults,
));
// We are on the homepage
expect(find.text('HomeBody'), findsOneWidget);
expect(find.text('HomeTitle'), findsOneWidget);
expect(find.text('Suggestions'), findsNothing);
// Open search
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
expect(find.text('HomeBody'), findsNothing);
expect(find.text('HomeTitle'), findsNothing);
expect(find.text('Suggestions'), findsOneWidget);
expect(find.text('Bottom'), findsOneWidget);
// Simulate system back button
final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute'));
await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { });
await tester.pumpAndSettle();
expect(selectedResults, <String?>[null]);
// We are on the homepage again
expect(find.text('HomeBody'), findsOneWidget);
expect(find.text('HomeTitle'), findsOneWidget);
expect(find.text('Suggestions'), findsNothing);
// Open search again
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
expect(find.text('HomeBody'), findsNothing);
expect(find.text('HomeTitle'), findsNothing);
expect(find.text('Suggestions'), findsOneWidget);
});
testWidgets('Hint text color overridden', (WidgetTester tester) async {
const String searchHintText = 'Enter search terms';
final _TestSearchDelegate delegate = _TestSearchDelegate(searchHint: searchHintText);
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(
delegate: delegate,
));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
final Text hintText = tester.widget(find.text(searchHintText));
expect(hintText.style!.color, _TestSearchDelegate.hintTextColor);
});
testWidgets('Requests suggestions', (WidgetTester tester) async {
final _TestSearchDelegate delegate = _TestSearchDelegate();
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(
delegate: delegate,
));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
expect(delegate.query, '');
expect(delegate.queriesForSuggestions.last, '');
expect(delegate.queriesForResults, hasLength(0));
// Type W o w into search field
delegate.queriesForSuggestions.clear();
await tester.enterText(find.byType(TextField), 'W');
await tester.pumpAndSettle();
expect(delegate.query, 'W');
await tester.enterText(find.byType(TextField), 'Wo');
await tester.pumpAndSettle();
expect(delegate.query, 'Wo');
await tester.enterText(find.byType(TextField), 'Wow');
await tester.pumpAndSettle();
expect(delegate.query, 'Wow');
expect(delegate.queriesForSuggestions, <String>['W', 'Wo', 'Wow']);
expect(delegate.queriesForResults, hasLength(0));
});
testWidgets('Shows Results and closes search', (WidgetTester tester) async {
final _TestSearchDelegate delegate = _TestSearchDelegate();
addTearDown(() => delegate.dispose());
final List<String> selectedResults = <String>[];
await tester.pumpWidget(TestHomePage(
delegate: delegate,
results: selectedResults,
));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
await tester.enterText(find.byType(TextField), 'Wow');
await tester.pumpAndSettle();
await tester.tap(find.text('Suggestions'));
await tester.pumpAndSettle();
// We are on the results page for Wow
expect(find.text('HomeBody'), findsNothing);
expect(find.text('HomeTitle'), findsNothing);
expect(find.text('Suggestions'), findsNothing);
expect(find.text('Results'), findsOneWidget);
final TextField textField = tester.widget(find.byType(TextField));
expect(textField.focusNode!.hasFocus, isFalse);
expect(delegate.queriesForResults, <String>['Wow']);
// Close search
await tester.tap(find.byTooltip('Back'));
await tester.pumpAndSettle();
expect(find.text('HomeBody'), findsOneWidget);
expect(find.text('HomeTitle'), findsOneWidget);
expect(find.text('Suggestions'), findsNothing);
expect(find.text('Results'), findsNothing);
expect(selectedResults, <String>['Result']);
});
testWidgets('Can switch between results and suggestions', (WidgetTester tester) async {
final _TestSearchDelegate delegate = _TestSearchDelegate();
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(
delegate: delegate,
));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
// Showing suggestions
expect(find.text('Suggestions'), findsOneWidget);
expect(find.text('Results'), findsNothing);
// Typing query Wow
delegate.queriesForSuggestions.clear();
await tester.enterText(find.byType(TextField), 'Wow');
await tester.pumpAndSettle();
expect(delegate.query, 'Wow');
expect(delegate.queriesForSuggestions, <String>['Wow']);
expect(delegate.queriesForResults, hasLength(0));
await tester.tap(find.text('Suggestions'));
await tester.pumpAndSettle();
// Showing Results
expect(find.text('Suggestions'), findsNothing);
expect(find.text('Results'), findsOneWidget);
expect(delegate.query, 'Wow');
expect(delegate.queriesForSuggestions, <String>['Wow']);
expect(delegate.queriesForResults, <String>['Wow']);
TextField textField = tester.widget(find.byType(TextField));
expect(textField.focusNode!.hasFocus, isFalse);
// Tapping search field to go back to suggestions
await tester.tap(find.byType(TextField));
await tester.pumpAndSettle();
textField = tester.widget(find.byType(TextField));
expect(textField.focusNode!.hasFocus, isTrue);
expect(find.text('Suggestions'), findsOneWidget);
expect(find.text('Results'), findsNothing);
expect(delegate.queriesForSuggestions, <String>['Wow', 'Wow']);
expect(delegate.queriesForResults, <String>['Wow']);
await tester.enterText(find.byType(TextField), 'Foo');
await tester.pumpAndSettle();
expect(delegate.query, 'Foo');
expect(delegate.queriesForSuggestions, <String>['Wow', 'Wow', 'Foo']);
expect(delegate.queriesForResults, <String>['Wow']);
// Go to results again
await tester.tap(find.text('Suggestions'));
await tester.pumpAndSettle();
expect(find.text('Suggestions'), findsNothing);
expect(find.text('Results'), findsOneWidget);
expect(delegate.query, 'Foo');
expect(delegate.queriesForSuggestions, <String>['Wow', 'Wow', 'Foo']);
expect(delegate.queriesForResults, <String>['Wow', 'Foo']);
textField = tester.widget(find.byType(TextField));
expect(textField.focusNode!.hasFocus, isFalse);
});
testWidgets('Fresh search always starts with empty query', (WidgetTester tester) async {
final _TestSearchDelegate delegate = _TestSearchDelegate();
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(
delegate: delegate,
));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
expect(delegate.query, '');
delegate.query = 'Foo';
await tester.tap(find.byTooltip('Back'));
await tester.pumpAndSettle();
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
expect(delegate.query, '');
});
testWidgets('Initial queries are honored', (WidgetTester tester) async {
final _TestSearchDelegate delegate = _TestSearchDelegate();
addTearDown(() => delegate.dispose());
expect(delegate.query, '');
await tester.pumpWidget(TestHomePage(
delegate: delegate,
passInInitialQuery: true,
initialQuery: 'Foo',
));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
expect(delegate.query, 'Foo');
});
testWidgets('Initial query null re-used previous query', (WidgetTester tester) async {
final _TestSearchDelegate delegate = _TestSearchDelegate();
addTearDown(() => delegate.dispose());
delegate.query = 'Foo';
await tester.pumpWidget(TestHomePage(
delegate: delegate,
passInInitialQuery: true,
));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
expect(delegate.query, 'Foo');
});
testWidgets('Changing query shows up in search field', (WidgetTester tester) async {
final _TestSearchDelegate delegate = _TestSearchDelegate();
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(
delegate: delegate,
passInInitialQuery: true,
));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
delegate.query = 'Foo';
expect(find.text('Foo'), findsOneWidget);
expect(find.text('Bar'), findsNothing);
delegate.query = 'Bar';
expect(find.text('Foo'), findsNothing);
expect(find.text('Bar'), findsOneWidget);
});
testWidgets('transitionAnimation runs while search fades in/out', (WidgetTester tester) async {
final _TestSearchDelegate delegate = _TestSearchDelegate();
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(
delegate: delegate,
passInInitialQuery: true,
));
// runs while search fades in
expect(delegate.transitionAnimation.status, AnimationStatus.dismissed);
await tester.tap(find.byTooltip('Search'));
expect(delegate.transitionAnimation.status, AnimationStatus.forward);
await tester.pumpAndSettle();
expect(delegate.transitionAnimation.status, AnimationStatus.completed);
// does not run while switching to results
await tester.tap(find.text('Suggestions'));
expect(delegate.transitionAnimation.status, AnimationStatus.completed);
await tester.pumpAndSettle();
expect(delegate.transitionAnimation.status, AnimationStatus.completed);
// runs while search fades out
await tester.tap(find.byTooltip('Back'));
expect(delegate.transitionAnimation.status, AnimationStatus.reverse);
await tester.pumpAndSettle();
expect(delegate.transitionAnimation.status, AnimationStatus.dismissed);
});
testWidgets('Closing nested search returns to search', (WidgetTester tester) async {
final List<String?> nestedSearchResults = <String?>[];
final _TestSearchDelegate nestedSearchDelegate = _TestSearchDelegate(
suggestions: 'Nested Suggestions',
result: 'Nested Result',
);
addTearDown(nestedSearchDelegate.dispose);
final List<String> selectedResults = <String>[];
final _TestSearchDelegate delegate = _TestSearchDelegate(
actions: <Widget>[
Builder(
builder: (BuildContext context) {
return IconButton(
tooltip: 'Nested Search',
icon: const Icon(Icons.search),
onPressed: () async {
final String? result = await showSearch(
context: context,
delegate: nestedSearchDelegate,
);
nestedSearchResults.add(result);
},
);
},
),
],
);
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(
delegate: delegate,
results: selectedResults,
));
expect(find.text('HomeBody'), findsOneWidget);
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
expect(find.text('HomeBody'), findsNothing);
expect(find.text('Suggestions'), findsOneWidget);
expect(find.text('Nested Suggestions'), findsNothing);
await tester.tap(find.byTooltip('Nested Search'));
await tester.pumpAndSettle();
expect(find.text('HomeBody'), findsNothing);
expect(find.text('Suggestions'), findsNothing);
expect(find.text('Nested Suggestions'), findsOneWidget);
await tester.tap(find.byTooltip('Back'));
await tester.pumpAndSettle();
expect(nestedSearchResults, <String>['Nested Result']);
expect(find.text('HomeBody'), findsNothing);
expect(find.text('Suggestions'), findsOneWidget);
expect(find.text('Nested Suggestions'), findsNothing);
await tester.tap(find.byTooltip('Back'));
await tester.pumpAndSettle();
expect(find.text('HomeBody'), findsOneWidget);
expect(find.text('Suggestions'), findsNothing);
expect(find.text('Nested Suggestions'), findsNothing);
expect(selectedResults, <String>['Result']);
});
testWidgets('Closing search with nested search shown goes back to underlying route', (WidgetTester tester) async {
late _TestSearchDelegate delegate;
addTearDown(() => delegate.dispose());
final List<String?> nestedSearchResults = <String?>[];
final _TestSearchDelegate nestedSearchDelegate = _TestSearchDelegate(
suggestions: 'Nested Suggestions',
result: 'Nested Result',
actions: <Widget>[
Builder(
builder: (BuildContext context) {
return IconButton(
tooltip: 'Close Search',
icon: const Icon(Icons.close),
onPressed: () async {
delegate.close(context, 'Result Foo');
},
);
},
),
],
);
addTearDown(nestedSearchDelegate.dispose);
final List<String> selectedResults = <String>[];
delegate = _TestSearchDelegate(
actions: <Widget>[
Builder(
builder: (BuildContext context) {
return IconButton(
tooltip: 'Nested Search',
icon: const Icon(Icons.search),
onPressed: () async {
final String? result = await showSearch(
context: context,
delegate: nestedSearchDelegate,
);
nestedSearchResults.add(result);
},
);
},
),
],
);
await tester.pumpWidget(TestHomePage(
delegate: delegate,
results: selectedResults,
));
expect(find.text('HomeBody'), findsOneWidget);
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
expect(find.text('HomeBody'), findsNothing);
expect(find.text('Suggestions'), findsOneWidget);
expect(find.text('Nested Suggestions'), findsNothing);
await tester.tap(find.byTooltip('Nested Search'));
await tester.pumpAndSettle();
expect(find.text('HomeBody'), findsNothing);
expect(find.text('Suggestions'), findsNothing);
expect(find.text('Nested Suggestions'), findsOneWidget);
await tester.tap(find.byTooltip('Close Search'));
await tester.pumpAndSettle();
expect(find.text('HomeBody'), findsOneWidget);
expect(find.text('Suggestions'), findsNothing);
expect(find.text('Nested Suggestions'), findsNothing);
expect(nestedSearchResults, <String?>[null]);
expect(selectedResults, <String>['Result Foo']);
});
testWidgets('Custom searchFieldLabel value', (WidgetTester tester) async {
const String searchHint = 'custom search hint';
final String defaultSearchHint = const DefaultMaterialLocalizations().searchFieldLabel;
final _TestSearchDelegate delegate = _TestSearchDelegate(searchHint: searchHint);
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(
delegate: delegate,
));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
expect(find.text(searchHint), findsOneWidget);
expect(find.text(defaultSearchHint), findsNothing);
});
testWidgets('Default searchFieldLabel is used when it is set to null', (WidgetTester tester) async {
final String searchHint = const DefaultMaterialLocalizations().searchFieldLabel;
final _TestSearchDelegate delegate = _TestSearchDelegate();
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(
delegate: delegate,
));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
expect(find.text(searchHint), findsOneWidget);
});
testWidgets('Custom searchFieldStyle value', (WidgetTester tester) async {
const String searchHintText = 'Enter search terms';
const TextStyle searchFieldStyle = TextStyle(color: Colors.red, fontSize: 3);
final _TestSearchDelegate delegate = _TestSearchDelegate(searchHint: searchHintText, searchFieldStyle: searchFieldStyle);
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(delegate: delegate));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
final Text hintText = tester.widget(find.text(searchHintText));
final TextField textField = tester.widget<TextField>(find.byType(TextField));
expect(hintText.style?.color, delegate.searchFieldStyle?.color);
expect(hintText.style?.fontSize, delegate.searchFieldStyle?.fontSize);
expect(textField.style?.color, delegate.searchFieldStyle?.color);
expect(textField.style?.fontSize, delegate.searchFieldStyle?.fontSize);
});
testWidgets('keyboard show search button by default', (WidgetTester tester) async {
final _TestSearchDelegate delegate = _TestSearchDelegate();
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(
delegate: delegate,
));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
await tester.showKeyboard(find.byType(TextField));
expect(tester.testTextInput.setClientArgs!['inputAction'], TextInputAction.search.toString());
});
testWidgets('Custom textInputAction results in keyboard with corresponding button', (WidgetTester tester) async {
final _TestSearchDelegate delegate = _TestSearchDelegate(textInputAction: TextInputAction.done);
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(
delegate: delegate,
));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
await tester.showKeyboard(find.byType(TextField));
expect(tester.testTextInput.setClientArgs!['inputAction'], TextInputAction.done.toString());
});
testWidgets('Custom flexibleSpace value', (WidgetTester tester) async {
const Widget flexibleSpace = Text('custom flexibleSpace');
final _TestSearchDelegate delegate = _TestSearchDelegate(flexibleSpace: flexibleSpace);
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(delegate: delegate));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
expect(find.byWidget(flexibleSpace), findsOneWidget);
});
group('contributes semantics with custom flexibleSpace', () {
const Widget flexibleSpace = Text('FlexibleSpace');
TestSemantics buildExpected({ required String routeName }) {
final bool isDesktop = debugDefaultTargetPlatformOverride == TargetPlatform.macOS ||
debugDefaultTargetPlatformOverride == TargetPlatform.windows ||
debugDefaultTargetPlatformOverride == TargetPlatform.linux;
return TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
id: 1,
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
id: 2,
children: <TestSemantics>[
TestSemantics(
id: 3,
flags: <SemanticsFlag>[
SemanticsFlag.scopesRoute,
SemanticsFlag.namesRoute,
],
label: routeName,
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
id: 4,
children: <TestSemantics>[
TestSemantics(
id: 6,
children: <TestSemantics>[
TestSemantics(
id: 8,
flags: <SemanticsFlag>[
SemanticsFlag.hasEnabledState,
SemanticsFlag.isButton,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[SemanticsAction.tap],
tooltip: 'Back',
textDirection: TextDirection.ltr,
),
TestSemantics(
id: 9,
flags: <SemanticsFlag>[
SemanticsFlag.isTextField,
SemanticsFlag.hasEnabledState,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocused,
SemanticsFlag.isHeader,
if (debugDefaultTargetPlatformOverride != TargetPlatform.iOS &&
debugDefaultTargetPlatformOverride != TargetPlatform.macOS) SemanticsFlag.namesRoute,
],
actions: <SemanticsAction>[
if (isDesktop)
SemanticsAction.didGainAccessibilityFocus,
if (isDesktop)
SemanticsAction.didLoseAccessibilityFocus,
SemanticsAction.tap,
SemanticsAction.setSelection,
SemanticsAction.setText,
SemanticsAction.paste,
],
label: 'Search',
textDirection: TextDirection.ltr,
textSelection: const TextSelection(baseOffset: 0, extentOffset: 0),
),
TestSemantics(
id: 10,
label: 'Bottom',
textDirection: TextDirection.ltr,
),
],
),
TestSemantics(
id: 7,
children: <TestSemantics>[
TestSemantics(
id: 11,
label: 'FlexibleSpace',
textDirection: TextDirection.ltr,
),
],
),
],
),
TestSemantics(
id: 5,
flags: <SemanticsFlag>[
SemanticsFlag.hasEnabledState,
SemanticsFlag.isButton,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[SemanticsAction.tap],
label: 'Suggestions',
textDirection: TextDirection.ltr,
),
],
),
],
),
],
),
],
);
}
testWidgets('includes routeName on Android', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final _TestSearchDelegate delegate = _TestSearchDelegate(flexibleSpace: flexibleSpace);
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(
delegate: delegate,
));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
expect(semantics, hasSemantics(
buildExpected(routeName: 'Search'),
ignoreId: true,
ignoreRect: true,
ignoreTransform: true,
));
semantics.dispose();
});
testWidgets('does not include routeName', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final _TestSearchDelegate delegate = _TestSearchDelegate(flexibleSpace: flexibleSpace);
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(
delegate: delegate,
));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
expect(semantics, hasSemantics(
buildExpected(routeName: ''),
ignoreId: true,
ignoreRect: true,
ignoreTransform: true,
));
semantics.dispose();
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
});
group('contributes semantics', () {
TestSemantics buildExpected({ required String routeName }) {
final bool isDesktop = debugDefaultTargetPlatformOverride == TargetPlatform.macOS ||
debugDefaultTargetPlatformOverride == TargetPlatform.windows ||
debugDefaultTargetPlatformOverride == TargetPlatform.linux;
return TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
id: 1,
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
id: 2,
children: <TestSemantics>[
TestSemantics(
id: 7,
flags: <SemanticsFlag>[
SemanticsFlag.scopesRoute,
SemanticsFlag.namesRoute,
],
label: routeName,
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
id: 9,
children: <TestSemantics>[
TestSemantics(
id: 10,
flags: <SemanticsFlag>[
SemanticsFlag.hasEnabledState,
SemanticsFlag.isButton,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[SemanticsAction.tap],
tooltip: 'Back',
textDirection: TextDirection.ltr,
),
TestSemantics(
id: 11,
flags: <SemanticsFlag>[
SemanticsFlag.isTextField,
SemanticsFlag.hasEnabledState,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocused,
SemanticsFlag.isHeader,
if (debugDefaultTargetPlatformOverride != TargetPlatform.iOS &&
debugDefaultTargetPlatformOverride != TargetPlatform.macOS) SemanticsFlag.namesRoute,
],
actions: <SemanticsAction>[
if (isDesktop)
SemanticsAction.didGainAccessibilityFocus,
if (isDesktop)
SemanticsAction.didLoseAccessibilityFocus,
SemanticsAction.tap,
SemanticsAction.setSelection,
SemanticsAction.setText,
SemanticsAction.paste,
],
label: 'Search',
textDirection: TextDirection.ltr,
textSelection: const TextSelection(baseOffset: 0, extentOffset: 0),
),
TestSemantics(
id: 14,
label: 'Bottom',
textDirection: TextDirection.ltr,
),
],
),
TestSemantics(
id: 8,
flags: <SemanticsFlag>[
SemanticsFlag.hasEnabledState,
SemanticsFlag.isButton,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[SemanticsAction.tap],
label: 'Suggestions',
textDirection: TextDirection.ltr,
),
],
),
],
),
],
),
],
);
}
testWidgets('includes routeName on Android', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final _TestSearchDelegate delegate = _TestSearchDelegate();
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(
delegate: delegate,
));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
expect(semantics, hasSemantics(
buildExpected(routeName: 'Search'),
ignoreId: true,
ignoreRect: true,
ignoreTransform: true,
));
semantics.dispose();
});
testWidgets('does not include routeName', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final _TestSearchDelegate delegate = _TestSearchDelegate();
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(
delegate: delegate,
));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
expect(semantics, hasSemantics(
buildExpected(routeName: ''),
ignoreId: true,
ignoreRect: true,
ignoreTransform: true,
));
semantics.dispose();
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
});
testWidgets('Custom searchFieldDecorationTheme value', (WidgetTester tester) async {
const InputDecorationTheme searchFieldDecorationTheme = InputDecorationTheme(
hintStyle: TextStyle(color: _TestSearchDelegate.hintTextColor),
);
final _TestSearchDelegate delegate = _TestSearchDelegate(
searchFieldDecorationTheme: searchFieldDecorationTheme,
);
addTearDown(() => delegate.dispose());
await tester.pumpWidget(TestHomePage(delegate: delegate));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
final ThemeData textFieldTheme = Theme.of(tester.element(find.byType(TextField)));
expect(textFieldTheme.inputDecorationTheme, searchFieldDecorationTheme);
});
// Regression test for: https://github.com/flutter/flutter/issues/66781
testWidgets('text in search bar contrasts background (light mode)', (WidgetTester tester) async {
final ThemeData themeData = ThemeData(useMaterial3: false);
final _TestSearchDelegate delegate = _TestSearchDelegate(defaultAppBarTheme: true);
addTearDown(() => delegate.dispose());
const String query = 'search query';
await tester.pumpWidget(TestHomePage(
delegate: delegate,
passInInitialQuery: true,
initialQuery: query,
themeData: themeData,
));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
final Material appBarBackground = tester.widgetList<Material>(find.descendant(
of: find.byType(AppBar),
matching: find.byType(Material),
)).first;
expect(appBarBackground.color, Colors.white);
final TextField textField = tester.widget<TextField>(find.byType(TextField));
expect(textField.style!.color, themeData.textTheme.bodyLarge!.color);
expect(textField.style!.color, isNot(equals(Colors.white)));
});
// Regression test for: https://github.com/flutter/flutter/issues/66781
testWidgets('text in search bar contrasts background (dark mode)', (WidgetTester tester) async {
final ThemeData themeData = ThemeData.dark(useMaterial3: false);
final _TestSearchDelegate delegate = _TestSearchDelegate(defaultAppBarTheme: true);
addTearDown(() => delegate.dispose());
const String query = 'search query';
await tester.pumpWidget(TestHomePage(
delegate: delegate,
passInInitialQuery: true,
initialQuery: query,
themeData: themeData,
));
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
final Material appBarBackground = tester.widgetList<Material>(find.descendant(
of: find.byType(AppBar),
matching: find.byType(Material),
)).first;
expect(appBarBackground.color, themeData.primaryColor);
final TextField textField = tester.widget<TextField>(find.byType(TextField));
expect(textField.style!.color, themeData.textTheme.bodyLarge!.color);
expect(textField.style!.color, isNot(equals(themeData.primaryColor)));
});
// Regression test for: https://github.com/flutter/flutter/issues/78144
testWidgets('`Leading`, `Actions` and `FlexibleSpace` nullable test', (WidgetTester tester) async {
// The search delegate page is displayed with no issues
// even with a null return values for [buildLeading], [buildActions] and [flexibleSpace].
final _TestEmptySearchDelegate delegate = _TestEmptySearchDelegate();
addTearDown(delegate.dispose);
final List<String> selectedResults = <String>[];
await tester.pumpWidget(TestHomePage(
delegate: delegate,
results: selectedResults,
));
// We are on the homepage.
expect(find.text('HomeBody'), findsOneWidget);
expect(find.text('HomeTitle'), findsOneWidget);
expect(find.text('Suggestions'), findsNothing);
// Open the search page.
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
expect(find.text('HomeBody'), findsNothing);
expect(find.text('HomeTitle'), findsNothing);
expect(find.text('Suggestions'), findsOneWidget);
expect(selectedResults, hasLength(0));
final TextField textField = tester.widget(find.byType(TextField));
expect(textField.focusNode!.hasFocus, isTrue);
// Close the search page.
await tester.tap(find.byTooltip('Close'));
await tester.pumpAndSettle();
expect(find.text('HomeBody'), findsOneWidget);
expect(find.text('HomeTitle'), findsOneWidget);
expect(find.text('Suggestions'), findsNothing);
expect(selectedResults, <String>['Result']);
});
testWidgets('Leading width size is 16', (WidgetTester tester) async {
final _TestSearchDelegate delegate = _TestSearchDelegate();
final List<String> selectedResults = <String>[];
delegate.leadingWidth = 16;
await tester.pumpWidget(TestHomePage(
delegate: delegate,
results: selectedResults,
));
// Open the search page with check leading width smaller than 16.
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
await tester.tapAt(const Offset(16, 16));
expect(find.text('Suggestions'), findsOneWidget);
final Finder appBarFinder = find.byType(AppBar);
final AppBar appBar = tester.widget<AppBar>(appBarFinder);
expect(appBar.leadingWidth, 16);
await tester.tapAt(const Offset(8, 16));
await tester.pumpAndSettle();
expect(find.text('Suggestions'), findsNothing);
expect(find.text('HomeBody'), findsOneWidget);
});
testWidgets('showSearch with useRootNavigator', (WidgetTester tester) async {
final _MyNavigatorObserver rootObserver = _MyNavigatorObserver();
final _MyNavigatorObserver localObserver = _MyNavigatorObserver();
final _TestEmptySearchDelegate delegate = _TestEmptySearchDelegate();
addTearDown(delegate.dispose);
await tester.pumpWidget(MaterialApp(
navigatorObservers: <NavigatorObserver>[rootObserver],
home: Navigator(
observers: <NavigatorObserver>[localObserver],
onGenerateRoute: (RouteSettings settings) {
if (settings.name == 'nested') {
return MaterialPageRoute<dynamic>(
builder: (BuildContext context) => Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextButton(
onPressed: () async {
await showSearch(context: context, delegate: delegate, useRootNavigator: true);
},
child: const Text('showSearchRootNavigator')),
TextButton(
onPressed: () async {
await showSearch(context: context, delegate: delegate);
},
child: const Text('showSearchLocalNavigator')),
],
),
settings: settings,
);
}
throw UnimplementedError();
},
initialRoute: 'nested',
),
));
expect(rootObserver.pushCount, 0);
expect(localObserver.pushCount, 0);
// showSearch normal and back.
await tester.tap(find.text('showSearchLocalNavigator'));
await tester.pumpAndSettle();
final Finder backButtonFinder = find.byType(BackButton);
expect(backButtonFinder, findsWidgets);
await tester.tap(find.byTooltip('Close'));
await tester.pumpAndSettle();
expect(rootObserver.pushCount, 0);
expect(localObserver.pushCount, 1);
// showSearch with rootNavigator.
await tester.tap(find.text('showSearchRootNavigator'));
await tester.pumpAndSettle();
await tester.tap(find.byTooltip('Close'));
await tester.pumpAndSettle();
// showSearch without back button.
delegate.automaticallyImplyLeading = false;
await tester.tap(find.text('showSearchRootNavigator'));
await tester.pumpAndSettle();
final Finder appBarFinder = find.byType(AppBar);
final AppBar appBar = tester.widget<AppBar>(appBarFinder);
expect(appBar.automaticallyImplyLeading, false);
expect(find.byTooltip('Back'), findsNothing);
await tester.tap(find.byTooltip('Close'));
await tester.pumpAndSettle();
expect(rootObserver.pushCount, 2);
expect(localObserver.pushCount, 1);
});
testWidgets('Query text field shows toolbar initially', (WidgetTester tester) async {
// This is a regression test for https://github.com/flutter/flutter/issues/95588
final _TestSearchDelegate delegate = _TestSearchDelegate();
addTearDown(() => delegate.dispose());
final List<String> selectedResults = <String>[];
await tester.pumpWidget(TestHomePage(
delegate: delegate,
results: selectedResults,
));
// Open search.
await tester.tap(find.byTooltip('Search'));
await tester.pumpAndSettle();
final Finder textFieldFinder = find.byType(TextField);
final TextField textField = tester.widget<TextField>(textFieldFinder);
expect(textField.controller!.text.length, 0);
mockClipboard.handleMethodCall(const MethodCall(
'Clipboard.setData',
<String, dynamic>{
'text': 'pasteablestring',
},
));
// Long press shows toolbar.
await tester.longPress(textFieldFinder);
await tester.pump();
expect(find.text('Paste'), findsOneWidget);
await tester.tap(find.text('Paste'));
await tester.pump();
expect(textField.controller!.text.length, 15);
}, skip: kIsWeb); // [intended] We do not use Flutter-rendered context menu on the Web.
}
class TestHomePage extends StatelessWidget {
const TestHomePage({
super.key,
this.results,
required this.delegate,
this.passInInitialQuery = false,
this.initialQuery,
this.themeData,
});
final List<String?>? results;
final SearchDelegate<String> delegate;
final bool passInInitialQuery;
final ThemeData? themeData;
final String? initialQuery;
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: themeData,
home: Builder(builder: (BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('HomeTitle'),
actions: <Widget>[
IconButton(
tooltip: 'Search',
icon: const Icon(Icons.search),
onPressed: () async {
String? selectedResult;
if (passInInitialQuery) {
selectedResult = await showSearch<String>(
context: context,
delegate: delegate,
query: initialQuery,
);
} else {
selectedResult = await showSearch<String>(
context: context,
delegate: delegate,
);
}
results?.add(selectedResult);
},
),
],
),
body: const Text('HomeBody'),
);
}),
);
}
}
class _TestSearchDelegate extends SearchDelegate<String> {
_TestSearchDelegate({
this.suggestions = 'Suggestions',
this.result = 'Result',
this.actions = const <Widget>[],
this.flexibleSpace ,
this.defaultAppBarTheme = false,
super.searchFieldDecorationTheme,
super.searchFieldStyle,
String? searchHint,
super.textInputAction,
}) : super(
searchFieldLabel: searchHint,
);
final bool defaultAppBarTheme;
final String suggestions;
final String result;
final List<Widget> actions;
final Widget? flexibleSpace;
static const Color hintTextColor = Colors.green;
@override
ThemeData appBarTheme(BuildContext context) {
if (defaultAppBarTheme) {
return super.appBarTheme(context);
}
final ThemeData theme = Theme.of(context);
return theme.copyWith(
inputDecorationTheme: searchFieldDecorationTheme ??
InputDecorationTheme(
hintStyle: searchFieldStyle ??
const TextStyle(
color: hintTextColor,
),
),
);
}
@override
Widget buildLeading(BuildContext context) {
return IconButton(
tooltip: 'Back',
icon: const Icon(Icons.arrow_back),
onPressed: () {
close(context, result);
},
);
}
final List<String> queriesForSuggestions = <String>[];
final List<String> queriesForResults = <String>[];
@override
Widget buildSuggestions(BuildContext context) {
queriesForSuggestions.add(query);
return ElevatedButton(
onPressed: () {
showResults(context);
},
child: Text(suggestions),
);
}
@override
Widget buildResults(BuildContext context) {
queriesForResults.add(query);
return const Text('Results');
}
@override
List<Widget> buildActions(BuildContext context) {
return actions;
}
@override
Widget? buildFlexibleSpace(BuildContext context) {
return flexibleSpace;
}
@override
PreferredSizeWidget buildBottom(BuildContext context) {
return const PreferredSize(
preferredSize: Size.fromHeight(56.0),
child: Text('Bottom'),
);
}
}
class _TestEmptySearchDelegate extends SearchDelegate<String> {
@override
Widget? buildLeading(BuildContext context) => null;
@override
List<Widget>? buildActions(BuildContext context) => null;
@override
Widget buildSuggestions(BuildContext context) {
return ElevatedButton(
onPressed: () {
showResults(context);
},
child: const Text('Suggestions'),
);
}
@override
Widget buildResults(BuildContext context) {
return const Text('Results');
}
@override
PreferredSizeWidget buildBottom(BuildContext context) {
return PreferredSize(
preferredSize: const Size.fromHeight(56.0),
child: IconButton(
tooltip: 'Close',
icon: const Icon(Icons.arrow_back),
onPressed: () {
close(context, 'Result');
},
),
);
}
}
class _MyNavigatorObserver extends NavigatorObserver {
int pushCount = 0;
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
// don't count the root route
if (<String>['nested', '/'].contains(route.settings.name)) {
return;
}
pushCount++;
}
}
| flutter/packages/flutter/test/material/search_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/search_test.dart",
"repo_id": "flutter",
"token_count": 20313
} | 844 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
void main() {
testWidgets('$TabController dispatches creation in constructor.', (WidgetTester widgetTester) async {
await expectLater(
await memoryEvents(() async => TabController(length: 1, vsync: const TestVSync()).dispose(), TabController),
areCreateAndDispose,
);
});
}
| flutter/packages/flutter/test/material/tab_controller_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/tab_controller_test.dart",
"repo_id": "flutter",
"token_count": 201
} | 845 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
testWidgets('position in the toolbar changes width', (WidgetTester tester) async {
late StateSetter setState;
int index = 1;
int total = 3;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setter) {
setState = setter;
return TextSelectionToolbarTextButton(
padding: TextSelectionToolbarTextButton.getPadding(index, total),
child: const Text('button'),
);
},
),
),
),
),
);
final Size middleSize = tester.getSize(find.byType(TextSelectionToolbarTextButton));
setState(() {
index = 0;
total = 3;
});
await tester.pump();
final Size firstSize = tester.getSize(find.byType(TextSelectionToolbarTextButton));
expect(firstSize.width, greaterThan(middleSize.width));
setState(() {
index = 2;
total = 3;
});
await tester.pump();
final Size lastSize = tester.getSize(find.byType(TextSelectionToolbarTextButton));
expect(lastSize.width, greaterThan(middleSize.width));
expect(lastSize.width, equals(firstSize.width));
setState(() {
index = 0;
total = 1;
});
await tester.pump();
final Size onlySize = tester.getSize(find.byType(TextSelectionToolbarTextButton));
expect(onlySize.width, greaterThan(middleSize.width));
expect(onlySize.width, greaterThan(firstSize.width));
expect(onlySize.width, greaterThan(lastSize.width));
});
for (final ColorScheme colorScheme in <ColorScheme>[ThemeData.light().colorScheme, ThemeData.dark().colorScheme]) {
testWidgets('foreground color by default', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
colorScheme: colorScheme,
),
home: Scaffold(
body: Center(
child: TextSelectionToolbarTextButton(
padding: TextSelectionToolbarTextButton.getPadding(0, 1),
child: const Text('button'),
),
),
),
),
);
expect(find.byType(TextButton), findsOneWidget);
final TextButton textButton = tester.widget(find.byType(TextButton));
// The foreground color is hardcoded to black or white by default, not the
// default value from ColorScheme.onSurface.
expect(
textButton.style!.foregroundColor!.resolve(<MaterialState>{}),
switch (colorScheme.brightness) {
Brightness.light => const Color(0xff000000),
Brightness.dark => const Color(0xffffffff),
},
);
});
testWidgets('custom foreground color', (WidgetTester tester) async {
const Color customForegroundColor = Colors.red;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
colorScheme: colorScheme.copyWith(
onSurface: customForegroundColor,
),
),
home: Scaffold(
body: Center(
child: TextSelectionToolbarTextButton(
padding: TextSelectionToolbarTextButton.getPadding(0, 1),
child: const Text('button'),
),
),
),
),
);
expect(find.byType(TextButton), findsOneWidget);
final TextButton textButton = tester.widget(find.byType(TextButton));
expect(
textButton.style!.foregroundColor!.resolve(<MaterialState>{}),
customForegroundColor,
);
});
testWidgets('background color by default', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/133027
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
colorScheme: colorScheme,
),
home: Scaffold(
body: Center(
child: TextSelectionToolbarTextButton(
padding: TextSelectionToolbarTextButton.getPadding(0, 1),
child: const Text('button'),
),
),
),
),
);
expect(find.byType(TextButton), findsOneWidget);
final TextButton textButton = tester.widget(find.byType(TextButton));
// The background color is hardcoded to transparent by default so the buttons
// are the color of the container behind them. For example TextSelectionToolbar
// hardcodes the color value, and TextSelectionToolbarTextButton that are its
// children should be that color.
expect(
textButton.style!.backgroundColor!.resolve(<MaterialState>{}),
Colors.transparent,
);
});
testWidgets('textButtonTheme should not override default background color', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/133027
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
colorScheme: colorScheme,
textButtonTheme: const TextButtonThemeData(
style: ButtonStyle(
backgroundColor: MaterialStatePropertyAll<Color>(Colors.blue),
),
),
),
home: Scaffold(
body: Center(
child: TextSelectionToolbarTextButton(
padding: TextSelectionToolbarTextButton.getPadding(0, 1),
child: const Text('button'),
),
),
),
),
);
expect(find.byType(TextButton), findsOneWidget);
final TextButton textButton = tester.widget(find.byType(TextButton));
// The background color is hardcoded to transparent by default so the buttons
// are the color of the container behind them. For example TextSelectionToolbar
// hardcodes the color value, and TextSelectionToolbarTextButton that are its
// children should be that color.
expect(
textButton.style!.backgroundColor!.resolve(<MaterialState>{}),
Colors.transparent,
);
});
}
}
| flutter/packages/flutter/test/material/text_selection_toolbar_text_button_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/text_selection_toolbar_text_button_test.dart",
"repo_id": "flutter",
"token_count": 2777
} | 846 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
bool willPopValue = false;
class SamplePage extends StatefulWidget {
const SamplePage({ super.key });
@override
SamplePageState createState() => SamplePageState();
}
class SamplePageState extends State<SamplePage> {
ModalRoute<void>? _route;
Future<bool> _callback() async => willPopValue;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_route?.removeScopedWillPopCallback(_callback);
_route = ModalRoute.of(context);
_route?.addScopedWillPopCallback(_callback);
}
@override
void dispose() {
super.dispose();
_route?.removeScopedWillPopCallback(_callback);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sample Page')),
);
}
}
int willPopCount = 0;
class SampleForm extends StatelessWidget {
const SampleForm({ super.key, required this.callback });
final WillPopCallback callback;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Sample Form')),
body: SizedBox.expand(
child: Form(
onWillPop: () {
willPopCount += 1;
return callback();
},
child: const TextField(),
),
),
);
}
}
// Expose the protected hasScopedWillPopCallback getter
class _TestPageRoute<T> extends MaterialPageRoute<T> {
_TestPageRoute({
super.settings,
required super.builder,
}) : super(maintainState: true);
bool get hasCallback => super.hasScopedWillPopCallback;
}
class _TestPage extends Page<dynamic> {
_TestPage({
required this.builder,
required LocalKey key,
}) : _key = GlobalKey(),
super(key: key);
final WidgetBuilder builder;
final GlobalKey<dynamic> _key;
@override
Route<dynamic> createRoute(BuildContext context) {
return _TestPageRoute<dynamic>(
settings: this,
builder: (BuildContext context) {
// keep state during move to another location in tree
return KeyedSubtree(key: _key, child: builder.call(context));
});
}
}
void main() {
testWidgets('ModalRoute scopedWillPopupCallback can inhibit back button', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Builder(
builder: (BuildContext context) {
return Center(
child: TextButton(
child: const Text('X'),
onPressed: () {
showDialog<void>(
context: context,
builder: (BuildContext context) => const SamplePage(),
);
},
),
);
},
),
),
),
);
expect(find.byTooltip('Back'), findsNothing);
expect(find.text('Sample Page'), findsNothing);
await tester.tap(find.text('X'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('Sample Page'), findsOneWidget);
willPopValue = false;
await tester.tap(find.byTooltip('Back'));
await tester.pump();
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('Sample Page'), findsOneWidget);
// Use didPopRoute() to simulate the system back button. Check that
// didPopRoute() indicates that the notification was handled.
final dynamic widgetsAppState = tester.state(find.byType(WidgetsApp));
// ignore: avoid_dynamic_calls
expect(await widgetsAppState.didPopRoute(), isTrue);
expect(find.text('Sample Page'), findsOneWidget);
willPopValue = true;
await tester.tap(find.byTooltip('Back'));
await tester.pump();
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('Sample Page'), findsNothing);
});
testWidgets('willPop will only pop if the callback returns true', (WidgetTester tester) async {
Widget buildFrame() {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Builder(
builder: (BuildContext context) {
return Center(
child: TextButton(
child: const Text('X'),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute<void>(
builder: (BuildContext context) {
return SampleForm(
callback: () => Future<bool>.value(willPopValue),
);
},
));
},
),
);
},
),
),
);
}
await tester.pumpWidget(buildFrame());
await tester.tap(find.text('X'));
await tester.pumpAndSettle();
expect(find.text('Sample Form'), findsOneWidget);
// Should pop if callback returns true
willPopValue = true;
await tester.tap(find.byTooltip('Back'));
await tester.pumpAndSettle();
expect(find.text('Sample Form'), findsNothing);
});
testWidgets('Form.willPop can inhibit back button', (WidgetTester tester) async {
Widget buildFrame() {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Builder(
builder: (BuildContext context) {
return Center(
child: TextButton(
child: const Text('X'),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute<void>(
builder: (BuildContext context) {
return SampleForm(
callback: () => Future<bool>.value(willPopValue),
);
},
));
},
),
);
},
),
),
);
}
await tester.pumpWidget(buildFrame());
await tester.tap(find.text('X'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('Sample Form'), findsOneWidget);
willPopValue = false;
willPopCount = 0;
await tester.tap(find.byTooltip('Back'));
await tester.pump(); // Start the pop "back" operation.
await tester.pump(); // Complete the willPop() Future.
await tester.pump(const Duration(seconds: 1)); // Wait until it has finished.
expect(find.text('Sample Form'), findsOneWidget);
expect(willPopCount, 1);
willPopValue = true;
willPopCount = 0;
await tester.tap(find.byTooltip('Back'));
await tester.pump(); // Start the pop "back" operation.
await tester.pump(); // Complete the willPop() Future.
await tester.pump(const Duration(seconds: 1)); // Wait until it has finished.
expect(find.text('Sample Form'), findsNothing);
expect(willPopCount, 1);
});
testWidgets('Form.willPop callbacks do not accumulate', (WidgetTester tester) async {
Future<bool> showYesNoAlert(BuildContext context) async {
return (await showDialog<bool>(
context: context,
builder: (BuildContext context) {
return AlertDialog(
actions: <Widget> [
TextButton(
child: const Text('YES'),
onPressed: () { Navigator.of(context).pop(true); },
),
TextButton(
child: const Text('NO'),
onPressed: () { Navigator.of(context).pop(false); },
),
],
);
},
))!;
}
Widget buildFrame() {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Builder(
builder: (BuildContext context) {
return Center(
child: TextButton(
child: const Text('X'),
onPressed: () {
Navigator.of(context).push(MaterialPageRoute<void>(
builder: (BuildContext context) {
return SampleForm(
callback: () => showYesNoAlert(context),
);
},
));
},
),
);
},
),
),
);
}
await tester.pumpWidget(buildFrame());
await tester.tap(find.text('X'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('Sample Form'), findsOneWidget);
// Press the Scaffold's back button. This causes the willPop callback
// to run, which shows the YES/NO Alert Dialog. Veto the back operation
// by pressing the Alert's NO button.
await tester.tap(find.byTooltip('Back'));
await tester.pump(); // Start the pop "back" operation.
await tester.pump(); // Call willPop which will show an Alert.
await tester.tap(find.text('NO'));
await tester.pump(); // Start the dismiss animation.
await tester.pump(); // Resolve the willPop callback.
await tester.pump(const Duration(seconds: 1)); // Wait until it has finished.
expect(find.text('Sample Form'), findsOneWidget);
// Do it again.
// Each time the Alert is shown and dismissed the FormState's
// didChangeDependencies() method runs. We're making sure that the
// didChangeDependencies() method doesn't add an extra willPop callback.
await tester.tap(find.byTooltip('Back'));
await tester.pump(); // Start the pop "back" operation.
await tester.pump(); // Call willPop which will show an Alert.
await tester.tap(find.text('NO'));
await tester.pump(); // Start the dismiss animation.
await tester.pump(); // Resolve the willPop callback.
await tester.pump(const Duration(seconds: 1)); // Wait until it has finished.
expect(find.text('Sample Form'), findsOneWidget);
// This time really dismiss the SampleForm by pressing the Alert's
// YES button.
await tester.tap(find.byTooltip('Back'));
await tester.pump(); // Start the pop "back" operation.
await tester.pump(); // Call willPop which will show an Alert.
await tester.tap(find.text('YES'));
await tester.pump(); // Start the dismiss animation.
await tester.pump(); // Resolve the willPop callback.
await tester.pump(const Duration(seconds: 1)); // Wait until it has finished.
expect(find.text('Sample Form'), findsNothing);
});
testWidgets('Route.scopedWillPop callbacks do not accumulate', (WidgetTester tester) async {
late StateSetter contentsSetState; // call this to rebuild the route's SampleForm contents
bool contentsEmpty = false; // when true, don't include the SampleForm in the route
final _TestPageRoute<void> route = _TestPageRoute<void>(
builder: (BuildContext context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
contentsSetState = setState;
return contentsEmpty ? Container() : SampleForm(key: UniqueKey(), callback: () async => false);
},
);
},
);
Widget buildFrame() {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Home')),
body: Builder(
builder: (BuildContext context) {
return Center(
child: TextButton(
child: const Text('X'),
onPressed: () {
Navigator.of(context).push(route);
},
),
);
},
),
),
);
}
await tester.pumpWidget(buildFrame());
await tester.tap(find.text('X'));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(find.text('Sample Form'), findsOneWidget);
expect(route.hasCallback, isTrue);
// Rebuild the route's SampleForm child an additional 3x for good measure.
contentsSetState(() { });
await tester.pump();
contentsSetState(() { });
await tester.pump();
contentsSetState(() { });
await tester.pump();
// Now build the route's contents without the sample form.
contentsEmpty = true;
contentsSetState(() { });
await tester.pump();
expect(route.hasCallback, isFalse);
});
testWidgets('should handle new route if page moved from one navigator to another', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/89133
late StateSetter contentsSetState;
bool moveToAnotherNavigator = false;
final List<Page<dynamic>> pages = <Page<dynamic>>[
_TestPage(
key: UniqueKey(),
builder: (BuildContext context) {
return WillPopScope(
onWillPop: () async => true,
child: const Text('anchor'),
);
},
),
];
Widget buildNavigator(Key? key, List<Page<dynamic>> pages) {
return Navigator(
key: key,
pages: pages,
onPopPage: (Route<dynamic> route, dynamic result) {
return route.didPop(result);
},
);
}
Widget buildFrame() {
return MaterialApp(
home: Scaffold(
body: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
contentsSetState = setState;
if (moveToAnotherNavigator) {
return buildNavigator(const ValueKey<int>(1), pages);
}
return buildNavigator(const ValueKey<int>(2), pages);
},
),
),
);
}
await tester.pumpWidget(buildFrame());
await tester.pump();
final _TestPageRoute<dynamic> route1 = ModalRoute.of(tester.element(find.text('anchor')))! as _TestPageRoute<dynamic>;
expect(route1.hasCallback, isTrue);
moveToAnotherNavigator = true;
contentsSetState(() {});
await tester.pump();
final _TestPageRoute<dynamic> route2 = ModalRoute.of(tester.element(find.text('anchor')))! as _TestPageRoute<dynamic>;
expect(route1.hasCallback, isFalse);
expect(route2.hasCallback, isTrue);
});
}
| flutter/packages/flutter/test/material/will_pop_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/will_pop_test.dart",
"repo_id": "flutter",
"token_count": 6213
} | 847 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
final Matcher isUnitCircle = isPathThat(
includes: <Offset>[
const Offset(-0.6035617555492896, 0.2230970398703236),
const Offset(-0.7738478165627277, 0.5640447581420576),
const Offset(-0.46090034164788385, -0.692017006684612),
const Offset(-0.2138540316101296, -0.09997005339529785),
const Offset(-0.46919827227410416, 0.29581721423767027),
const Offset(-0.43628713652733153, 0.5065324817995975),
Offset.zero,
const Offset(0.49296904381712725, -0.5922438805080081),
const Offset(0.2901141594861445, -0.3181478162967859),
const Offset(0.45229946324502146, 0.4324593232323706),
const Offset(0.11827752132593572, 0.806442226027837),
const Offset(0.8854165569581154, -0.08604230149167624),
],
excludes: <Offset>[
const Offset(-100.0, -100.0),
const Offset(-100.0, 100.0),
const Offset(-1.1104403014186688, -1.1234939207590569),
const Offset(-1.1852827482514838, -0.5029551986333607),
const Offset(-1.0253256532179804, -0.02034402043932526),
const Offset(-1.4488532714237397, 0.4948740308904742),
const Offset(-1.03142206223176, 0.81070400258819),
const Offset(-1.006747917852356, 1.3712062218039343),
const Offset(-0.5241429900291878, -1.2852518410112541),
const Offset(-0.8879593765104428, -0.9999680025850874),
const Offset(-0.9120835110799488, -0.4361605900585557),
const Offset(-0.8184877240407303, 1.1202520775469589),
const Offset(-0.15746058420492282, -1.1905035795387513),
const Offset(-0.11519948876183506, 1.3848147258237393),
const Offset(0.0035741796943844495, -1.3383908620447724),
const Offset(0.34408827443814394, 1.4514436242950461),
const Offset(0.709487222145941, -1.3468012918181573),
const Offset(0.6287522653614315, -0.8315879623940617),
const Offset(0.9716071801865485, 0.24311969613525442),
const Offset(0.7632982576031955, 0.8329765574976169),
const Offset(0.9923766847309081, 1.0592617071813715),
const Offset(1.2696730082820435, -1.0353385446957046),
const Offset(1.4266154921521208, -0.8382633931857755),
const Offset(1.298035226938996, -0.11544603567954526),
const Offset(1.4143230992455558, 0.10842501221141165),
const Offset(1.465352952354424, 0.6999947490821032),
const Offset(1.0462985816010146, 1.3874230508561505),
const Offset(100.0, -100.0),
const Offset(100.0, 100.0),
],
);
| flutter/packages/flutter/test/painting/common_matchers.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/common_matchers.dart",
"repo_id": "flutter",
"token_count": 1195
} | 848 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui show Image;
import 'package:flutter/painting.dart';
import 'package:flutter_test/flutter_test.dart';
Future<void> main() async {
final ui.Image smallImage = await createTestImage(width: 10, height: 20);
final ui.Image middleImage = await createTestImage(width: 20, height: 100);
final ui.Image bigImage = await createTestImage(width: 100, height: 200);
test('ImageInfo sizeBytes', () {
ImageInfo imageInfo = ImageInfo(image: smallImage);
expect(imageInfo.sizeBytes, equals(800));
imageInfo = ImageInfo(image: middleImage);
expect(imageInfo.sizeBytes, equals(8000));
imageInfo = ImageInfo(image: bigImage);
expect(imageInfo.sizeBytes, equals(80000));
});
}
| flutter/packages/flutter/test/painting/image_info_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/image_info_test.dart",
"repo_id": "flutter",
"token_count": 280
} | 849 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/painting.dart';
import 'package:flutter_test/flutter_test.dart';
import 'common_matchers.dart';
void main() {
test('RoundedRectangleBorder defaults', () {
const RoundedRectangleBorder border = RoundedRectangleBorder();
expect(border.side, BorderSide.none);
expect(border.borderRadius, BorderRadius.zero);
});
test('RoundedRectangleBorder copyWith, ==, hashCode', () {
expect(const RoundedRectangleBorder(), const RoundedRectangleBorder().copyWith());
expect(const RoundedRectangleBorder().hashCode, const RoundedRectangleBorder().copyWith().hashCode);
const BorderSide side = BorderSide(width: 10.0, color: Color(0xff123456));
const BorderRadius radius = BorderRadius.all(Radius.circular(16.0));
const BorderRadiusDirectional directionalRadius = BorderRadiusDirectional.all(Radius.circular(16.0));
expect(
const RoundedRectangleBorder().copyWith(side: side, borderRadius: radius),
const RoundedRectangleBorder(side: side, borderRadius: radius),
);
expect(
const RoundedRectangleBorder().copyWith(side: side, borderRadius: directionalRadius),
const RoundedRectangleBorder(side: side, borderRadius: directionalRadius),
);
});
test('RoundedRectangleBorder', () {
const RoundedRectangleBorder c10 = RoundedRectangleBorder(side: BorderSide(width: 10.0), borderRadius: BorderRadius.all(Radius.circular(100.0)));
const RoundedRectangleBorder c15 = RoundedRectangleBorder(side: BorderSide(width: 15.0), borderRadius: BorderRadius.all(Radius.circular(150.0)));
const RoundedRectangleBorder c20 = RoundedRectangleBorder(side: BorderSide(width: 20.0), borderRadius: BorderRadius.all(Radius.circular(200.0)));
expect(c10.dimensions, const EdgeInsets.all(10.0));
expect(c10.scale(2.0), c20);
expect(c20.scale(0.5), c10);
expect(ShapeBorder.lerp(c10, c20, 0.0), c10);
expect(ShapeBorder.lerp(c10, c20, 0.5), c15);
expect(ShapeBorder.lerp(c10, c20, 1.0), c20);
const RoundedRectangleBorder c1 = RoundedRectangleBorder(side: BorderSide(), borderRadius: BorderRadius.all(Radius.circular(1.0)));
const RoundedRectangleBorder c2 = RoundedRectangleBorder(side: BorderSide(), borderRadius: BorderRadius.all(Radius.circular(2.0)));
expect(c2.getInnerPath(Rect.fromCircle(center: Offset.zero, radius: 2.0)), isUnitCircle);
expect(c1.getOuterPath(Rect.fromCircle(center: Offset.zero, radius: 1.0)), isUnitCircle);
const Rect rect = Rect.fromLTRB(10.0, 20.0, 80.0, 190.0);
expect(
(Canvas canvas) => c10.paint(canvas, rect),
paints
..drrect(
outer: RRect.fromRectAndRadius(rect, const Radius.circular(100.0)),
inner: RRect.fromRectAndRadius(rect.deflate(10.0), const Radius.circular(90.0)),
strokeWidth: 0.0,
),
);
const RoundedRectangleBorder directional = RoundedRectangleBorder(
borderRadius: BorderRadiusDirectional.only(topStart: Radius.circular(20)),
);
expect(
ShapeBorder.lerp(directional, c10, 1.0),
ShapeBorder.lerp(c10, directional, 0.0),
);
});
test('RoundedRectangleBorder and CircleBorder', () {
const RoundedRectangleBorder r = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10.0)));
const CircleBorder c = CircleBorder();
const Rect rect = Rect.fromLTWH(0.0, 0.0, 100.0, 20.0); // center is x=40..60 y=10
final Matcher looksLikeR = isPathThat(
includes: const <Offset>[ Offset(30.0, 10.0), Offset(50.0, 10.0), ],
excludes: const <Offset>[ Offset(1.0, 1.0), Offset(99.0, 19.0), ],
);
final Matcher looksLikeC = isPathThat(
includes: const <Offset>[ Offset(50.0, 10.0), ],
excludes: const <Offset>[ Offset(1.0, 1.0), Offset(30.0, 10.0), Offset(99.0, 19.0), ],
);
expect(r.getOuterPath(rect), looksLikeR);
expect(c.getOuterPath(rect), looksLikeC);
expect(ShapeBorder.lerp(r, c, 0.1)!.getOuterPath(rect), looksLikeR);
expect(ShapeBorder.lerp(r, c, 0.9)!.getOuterPath(rect), looksLikeC);
expect(ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.9), r, 0.1)!.getOuterPath(rect), looksLikeC);
expect(ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.9), r, 0.9)!.getOuterPath(rect), looksLikeR);
expect(ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.1), c, 0.1)!.getOuterPath(rect), looksLikeR);
expect(ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.1), c, 0.9)!.getOuterPath(rect), looksLikeC);
expect(ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.1), ShapeBorder.lerp(r, c, 0.9), 0.1)!.getOuterPath(rect), looksLikeR);
expect(ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.1), ShapeBorder.lerp(r, c, 0.9), 0.9)!.getOuterPath(rect), looksLikeC);
expect(ShapeBorder.lerp(r, ShapeBorder.lerp(r, c, 0.9), 0.1)!.getOuterPath(rect), looksLikeR);
expect(ShapeBorder.lerp(r, ShapeBorder.lerp(r, c, 0.9), 0.9)!.getOuterPath(rect), looksLikeC);
expect(ShapeBorder.lerp(c, ShapeBorder.lerp(r, c, 0.1), 0.1)!.getOuterPath(rect), looksLikeC);
expect(ShapeBorder.lerp(c, ShapeBorder.lerp(r, c, 0.1), 0.9)!.getOuterPath(rect), looksLikeR);
expect(
ShapeBorder.lerp(r, c, 0.1).toString(),
'RoundedRectangleBorder(BorderSide(width: 0.0, style: none), BorderRadius.circular(10.0), 10.0% of the way to being a CircleBorder)',
);
expect(
ShapeBorder.lerp(r, c, 0.2).toString(),
'RoundedRectangleBorder(BorderSide(width: 0.0, style: none), BorderRadius.circular(10.0), 20.0% of the way to being a CircleBorder)',
);
expect(
ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.1), ShapeBorder.lerp(r, c, 0.9), 0.9).toString(),
'RoundedRectangleBorder(BorderSide(width: 0.0, style: none), BorderRadius.circular(10.0), 82.0% of the way to being a CircleBorder)',
);
expect(
ShapeBorder.lerp(c, r, 0.9).toString(),
'RoundedRectangleBorder(BorderSide(width: 0.0, style: none), BorderRadius.circular(10.0), 10.0% of the way to being a CircleBorder)',
);
expect(
ShapeBorder.lerp(c, r, 0.8).toString(),
'RoundedRectangleBorder(BorderSide(width: 0.0, style: none), BorderRadius.circular(10.0), 20.0% of the way to being a CircleBorder)',
);
expect(
ShapeBorder.lerp(ShapeBorder.lerp(r, c, 0.9), ShapeBorder.lerp(r, c, 0.1), 0.1).toString(),
'RoundedRectangleBorder(BorderSide(width: 0.0, style: none), BorderRadius.circular(10.0), 82.0% of the way to being a CircleBorder)',
);
expect(ShapeBorder.lerp(r, c, 0.1), ShapeBorder.lerp(r, c, 0.1));
expect(ShapeBorder.lerp(r, c, 0.1).hashCode, ShapeBorder.lerp(r, c, 0.1).hashCode);
final ShapeBorder direct50 = ShapeBorder.lerp(r, c, 0.5)!;
final ShapeBorder indirect50 = ShapeBorder.lerp(ShapeBorder.lerp(c, r, 0.1), ShapeBorder.lerp(c, r, 0.9), 0.5)!;
expect(direct50, indirect50);
expect(direct50.hashCode, indirect50.hashCode);
expect(direct50.toString(), indirect50.toString());
});
test('RoundedRectangleBorder.dimensions and CircleBorder.dimensions', () {
const RoundedRectangleBorder insideRoundedRectangleBorder = RoundedRectangleBorder(side: BorderSide(width: 10));
expect(insideRoundedRectangleBorder.dimensions, const EdgeInsets.all(10));
const RoundedRectangleBorder centerRoundedRectangleBorder = RoundedRectangleBorder(side: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignCenter));
expect(centerRoundedRectangleBorder.dimensions, const EdgeInsets.all(5));
const RoundedRectangleBorder outsideRoundedRectangleBorder = RoundedRectangleBorder(side: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignOutside));
expect(outsideRoundedRectangleBorder.dimensions, EdgeInsets.zero);
const CircleBorder insideCircleBorder = CircleBorder(side: BorderSide(width: 10));
expect(insideCircleBorder.dimensions, const EdgeInsets.all(10));
const CircleBorder centerCircleBorder = CircleBorder(side: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignCenter));
expect(centerCircleBorder.dimensions, const EdgeInsets.all(5));
const CircleBorder outsideCircleBorder = CircleBorder(side: BorderSide(width: 10, strokeAlign: BorderSide.strokeAlignOutside));
expect(outsideCircleBorder.dimensions, EdgeInsets.zero);
});
test('RoundedRectangleBorder.lerp with different StrokeAlign', () {
const RoundedRectangleBorder rInside = RoundedRectangleBorder(side: BorderSide(width: 10.0));
const RoundedRectangleBorder rOutside = RoundedRectangleBorder(side: BorderSide(width: 20.0, strokeAlign: BorderSide.strokeAlignOutside));
const RoundedRectangleBorder rCenter = RoundedRectangleBorder(side: BorderSide(width: 15.0, strokeAlign: BorderSide.strokeAlignCenter));
expect(ShapeBorder.lerp(rInside, rOutside, 0.5), rCenter);
});
}
| flutter/packages/flutter/test/painting/rounded_rectangle_border_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/rounded_rectangle_border_test.dart",
"repo_id": "flutter",
"token_count": 3354
} | 850 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/physics.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('test_friction', () {
expect(nearEqual(5.0, 6.0, 2.0), isTrue);
expect(nearEqual(6.0, 5.0, 2.0), isTrue);
expect(nearEqual(5.0, 6.0, 0.5), isFalse);
expect(nearEqual(6.0, 5.0, 0.5), isFalse);
});
test('test_null', () {
expect(nearEqual(5.0, null, 2.0), isFalse);
expect(nearEqual(null, 5.0, 2.0), isFalse);
expect(nearEqual(null, null, 2.0), isTrue);
});
}
| flutter/packages/flutter/test/physics/near_equal_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/physics/near_equal_test.dart",
"repo_id": "flutter",
"token_count": 276
} | 851 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:vector_math/vector_math_64.dart';
import 'rendering_tester.dart';
void main() {
TestRenderingFlutterBinding.ensureInitialized();
test('Describe transform control test', () {
final Matrix4 identity = Matrix4.identity();
final List<String> description = debugDescribeTransform(identity);
expect(description, <String>[
'[0] 1.0,0.0,0.0,0.0',
'[1] 0.0,1.0,0.0,0.0',
'[2] 0.0,0.0,1.0,0.0',
'[3] 0.0,0.0,0.0,1.0',
]);
});
test('transform property test', () {
final Matrix4 transform = Matrix4.diagonal3(Vector3.all(2.0));
final TransformProperty simple = TransformProperty(
'transform',
transform,
);
expect(simple.name, equals('transform'));
expect(simple.value, same(transform));
expect(
simple.toString(parentConfiguration: sparseTextConfiguration),
equals(
'transform:\n'
' [0] 2.0,0.0,0.0,0.0\n'
' [1] 0.0,2.0,0.0,0.0\n'
' [2] 0.0,0.0,2.0,0.0\n'
' [3] 0.0,0.0,0.0,1.0',
),
);
expect(
simple.toString(parentConfiguration: singleLineTextConfiguration),
equals('transform: [2.0,0.0,0.0,0.0; 0.0,2.0,0.0,0.0; 0.0,0.0,2.0,0.0; 0.0,0.0,0.0,1.0]'),
);
final TransformProperty nullProperty = TransformProperty(
'transform',
null,
);
expect(nullProperty.name, equals('transform'));
expect(nullProperty.value, isNull);
expect(nullProperty.toString(), equals('transform: null'));
final TransformProperty hideNull = TransformProperty(
'transform',
null,
defaultValue: null,
);
expect(hideNull.value, isNull);
expect(hideNull.toString(), equals('transform: null'));
});
test('debugPaintPadding', () {
expect((Canvas canvas) {
debugPaintPadding(canvas, const Rect.fromLTRB(10.0, 10.0, 20.0, 20.0), null);
}, paints..rect(color: const Color(0x90909090)));
expect((Canvas canvas) {
debugPaintPadding(canvas, const Rect.fromLTRB(10.0, 10.0, 20.0, 20.0), const Rect.fromLTRB(11.0, 11.0, 19.0, 19.0));
}, paints..path(color: const Color(0x900090FF))..path(color: const Color(0xFF0090FF)));
expect((Canvas canvas) {
debugPaintPadding(canvas, const Rect.fromLTRB(10.0, 10.0, 20.0, 20.0), const Rect.fromLTRB(15.0, 15.0, 15.0, 15.0));
}, paints..rect(rect: const Rect.fromLTRB(10.0, 10.0, 20.0, 20.0), color: const Color(0x90909090)));
});
test('debugPaintPadding from render objects', () {
debugPaintSizeEnabled = true;
RenderSliver s;
RenderBox b;
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
children: <RenderSliver>[
s = RenderSliverPadding(
padding: const EdgeInsets.all(10.0),
child: RenderSliverToBoxAdapter(
child: b = RenderPadding(
padding: const EdgeInsets.all(10.0),
),
),
),
],
);
layout(root);
expect(b.debugPaint, paints..rect(color: const Color(0xFF00FFFF))..rect(color: const Color(0x90909090)));
expect(b.debugPaint, isNot(paints..path()));
expect(
s.debugPaint,
paints
..circle(hasMaskFilter: true)
..line(hasMaskFilter: true)
..path(hasMaskFilter: true)
..path(hasMaskFilter: true)
..path(color: const Color(0x900090FF))
..path(color: const Color(0xFF0090FF)),
);
expect(s.debugPaint, isNot(paints..rect()));
debugPaintSizeEnabled = false;
});
test('debugPaintPadding from render objects', () {
debugPaintSizeEnabled = true;
RenderSliver s;
final RenderBox b = RenderPadding(
padding: const EdgeInsets.all(10.0),
child: RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
children: <RenderSliver>[
s = RenderSliverPadding(
padding: const EdgeInsets.all(10.0),
),
],
),
);
layout(b);
expect(s.debugPaint, paints..rect(color: const Color(0x90909090)));
expect(
s.debugPaint,
isNot(
paints
..circle(hasMaskFilter: true)
..line(hasMaskFilter: true)
..path(hasMaskFilter: true)
..path(hasMaskFilter: true)
..path(color: const Color(0x900090FF))
..path(color: const Color(0xFF0090FF)),
),
);
expect(b.debugPaint, paints..rect(color: const Color(0xFF00FFFF))..path(color: const Color(0x900090FF))..path(color: const Color(0xFF0090FF)));
expect(b.debugPaint, isNot(paints..rect(color: const Color(0x90909090))));
debugPaintSizeEnabled = false;
});
test('debugPaintPadding from render objects with inverted direction vertical', () {
debugPaintSizeEnabled = true;
RenderSliver s;
final RenderViewport root = RenderViewport(
axisDirection: AxisDirection.up,
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
children: <RenderSliver>[
s = RenderSliverPadding(
padding: const EdgeInsets.all(10.0),
child: RenderSliverToBoxAdapter(
child: RenderPadding(
padding: const EdgeInsets.all(10.0),
),
),
),
],
);
layout(root);
dynamic error;
final PaintingContext context = PaintingContext(ContainerLayer(), const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0));
try {
s.debugPaint(
context,
const Offset(0.0, 500),
);
} catch (e) {
error = e;
}
expect(error, isNull);
debugPaintSizeEnabled = false;
});
test('debugPaintPadding from render objects with inverted direction horizontal', () {
debugPaintSizeEnabled = true;
RenderSliver s;
final RenderViewport root = RenderViewport(
axisDirection: AxisDirection.left,
crossAxisDirection: AxisDirection.down,
offset: ViewportOffset.zero(),
children: <RenderSliver>[
s = RenderSliverPadding(
padding: const EdgeInsets.all(10.0),
child: RenderSliverToBoxAdapter(
child: RenderPadding(
padding: const EdgeInsets.all(10.0),
),
),
),
],
);
layout(root);
dynamic error;
final PaintingContext context = PaintingContext(ContainerLayer(), const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0));
try {
s.debugPaint(
context,
const Offset(0.0, 500),
);
} catch (e) {
error = e;
}
expect(error, isNull);
debugPaintSizeEnabled = false;
});
test('debugDisableOpacity keeps things in the right spot', () {
debugDisableOpacityLayers = true;
final RenderDecoratedBox blackBox = RenderDecoratedBox(
decoration: const BoxDecoration(color: Color(0xff000000)),
child: RenderConstrainedBox(
additionalConstraints: BoxConstraints.tight(const Size.square(20.0)),
),
);
final RenderOpacity root = RenderOpacity(
opacity: .5,
child: RenderRepaintBoundary(child: blackBox),
);
layout(root, phase: EnginePhase.compositingBits);
final OffsetLayer rootLayer = OffsetLayer();
final PaintingContext context = PaintingContext(
rootLayer,
const Rect.fromLTWH(0, 0, 500, 500),
);
context.paintChild(root, const Offset(40, 40));
final OpacityLayer opacityLayer = rootLayer.firstChild! as OpacityLayer;
expect(opacityLayer.offset, const Offset(40, 40));
debugDisableOpacityLayers = false;
});
test('debugAssertAllRenderVarsUnset warns when debugProfileLayoutsEnabled set', () {
debugProfileLayoutsEnabled = true;
expect(() => debugAssertAllRenderVarsUnset('ERROR'), throwsFlutterError);
debugProfileLayoutsEnabled = false;
});
test('debugAssertAllRenderVarsUnset warns when debugDisableClipLayers set', () {
debugDisableClipLayers = true;
expect(() => debugAssertAllRenderVarsUnset('ERROR'), throwsFlutterError);
debugDisableClipLayers = false;
});
test('debugAssertAllRenderVarsUnset warns when debugDisablePhysicalShapeLayers set', () {
debugDisablePhysicalShapeLayers = true;
expect(() => debugAssertAllRenderVarsUnset('ERROR'), throwsFlutterError);
debugDisablePhysicalShapeLayers = false;
});
test('debugAssertAllRenderVarsUnset warns when debugDisableOpacityLayers set', () {
debugDisableOpacityLayers = true;
expect(() => debugAssertAllRenderVarsUnset('ERROR'), throwsFlutterError);
debugDisableOpacityLayers = false;
});
test('debugCheckHasBoundedAxis warns for vertical and horizontal axis', () {
expect(
() => debugCheckHasBoundedAxis(Axis.vertical, const BoxConstraints()),
throwsFlutterError,
);
expect(
() => debugCheckHasBoundedAxis(Axis.horizontal, const BoxConstraints()),
throwsFlutterError,
);
});
}
| flutter/packages/flutter/test/rendering/debug_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/debug_test.dart",
"repo_id": "flutter",
"token_count": 3814
} | 852 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
void main() {
// LeakTesting is turned off because it adds subscriptions to
// [FlutterMemoryAllocations], that may interfere with the tests.
LeakTesting.settings = LeakTesting.settings.withIgnoredAll();
final FlutterMemoryAllocations ma = FlutterMemoryAllocations.instance;
setUp(() {
assert(!ma.hasListeners);
});
test('Publishers dispatch events in debug mode', () async {
int eventCount = 0;
void listener(ObjectEvent event) => eventCount++;
ma.addListener(listener);
final int expectedEventCount = await _activateFlutterObjectsAndReturnCountOfEvents();
expect(eventCount, expectedEventCount);
ma.removeListener(listener);
expect(ma.hasListeners, isFalse);
});
}
class _TestRenderObject extends RenderObject {
@override
void debugAssertDoesMeetConstraints() {}
@override
Rect get paintBounds => throw UnimplementedError();
@override
void performLayout() {}
@override
void performResize() {}
@override
Rect get semanticBounds => throw UnimplementedError();
}
class _TestLayer extends Layer{
@override
void addToScene(ui.SceneBuilder builder) {}
}
/// Create and dispose Flutter objects to fire memory allocation events.
Future<int> _activateFlutterObjectsAndReturnCountOfEvents() async {
int count = 0;
final RenderObject renderObject = _TestRenderObject(); count++;
final Layer layer = _TestLayer(); count++;
renderObject.dispose(); count++;
layer.dispose(); count++;
return count;
}
| flutter/packages/flutter/test/rendering/memory_allocations_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/memory_allocations_test.dart",
"repo_id": "flutter",
"token_count": 567
} | 853 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:ui' as ui;
import 'package:fake_async/fake_async.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import '../services/fake_platform_views.dart';
import 'rendering_tester.dart';
void main() {
final TestRenderingFlutterBinding binding = TestRenderingFlutterBinding.ensureInitialized();
group('PlatformViewRenderBox', () {
late FakePlatformViewController fakePlatformViewController;
late PlatformViewRenderBox platformViewRenderBox;
setUp(() {
fakePlatformViewController = FakePlatformViewController(0);
platformViewRenderBox = PlatformViewRenderBox(
controller: fakePlatformViewController,
hitTestBehavior: PlatformViewHitTestBehavior.opaque,
gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{
Factory<VerticalDragGestureRecognizer>(
() {
return VerticalDragGestureRecognizer();
},
),
},
);
});
test('layout should size to max constraint', () {
layout(platformViewRenderBox);
platformViewRenderBox.layout(const BoxConstraints(minWidth: 50, minHeight: 50, maxWidth: 100, maxHeight: 100));
expect(platformViewRenderBox.size, const Size(100, 100));
});
test('send semantics update if id is changed', () {
final RenderConstrainedBox tree = RenderConstrainedBox(
additionalConstraints: const BoxConstraints.tightFor(height: 20.0, width: 20.0),
child: platformViewRenderBox,
);
int semanticsUpdateCount = 0;
final SemanticsHandle semanticsHandle = TestRenderingFlutterBinding.instance.rootPipelineOwner.ensureSemantics(
listener: () {
++semanticsUpdateCount;
},
);
layout(tree, phase: EnginePhase.flushSemantics);
// Initial semantics update
expect(semanticsUpdateCount, 1);
semanticsUpdateCount = 0;
// Request semantics update even though nothing changed.
platformViewRenderBox.markNeedsSemanticsUpdate();
pumpFrame(phase: EnginePhase.flushSemantics);
expect(semanticsUpdateCount, 0);
semanticsUpdateCount = 0;
final FakePlatformViewController updatedFakePlatformViewController = FakePlatformViewController(10);
platformViewRenderBox.controller = updatedFakePlatformViewController;
pumpFrame(phase: EnginePhase.flushSemantics);
// Update id should update the semantics.
expect(semanticsUpdateCount, 1);
semanticsHandle.dispose();
});
test('mouse hover events are dispatched via PlatformViewController.dispatchPointerEvent', () {
layout(platformViewRenderBox);
pumpFrame(phase: EnginePhase.flushSemantics);
RendererBinding.instance.platformDispatcher.onPointerDataPacket!(ui.PointerDataPacket(data: <ui.PointerData>[
_pointerData(ui.PointerChange.add, Offset.zero),
_pointerData(ui.PointerChange.hover, const Offset(10, 10)),
_pointerData(ui.PointerChange.remove, const Offset(10, 10)),
]));
expect(fakePlatformViewController.dispatchedPointerEvents, isNotEmpty);
});
test('touch hover events are dispatched via PlatformViewController.dispatchPointerEvent', () {
layout(platformViewRenderBox);
pumpFrame(phase: EnginePhase.flushSemantics);
RendererBinding.instance.platformDispatcher.onPointerDataPacket!(ui.PointerDataPacket(data: <ui.PointerData>[
_pointerData(ui.PointerChange.add, Offset.zero),
_pointerData(ui.PointerChange.hover, const Offset(10, 10)),
_pointerData(ui.PointerChange.remove, const Offset(10, 10)),
]));
expect(fakePlatformViewController.dispatchedPointerEvents, isNotEmpty);
});
});
// Regression test for https://github.com/flutter/flutter/issues/69431
test('multi-finger touch test', () {
final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController();
viewsController.registerViewType('webview');
final AndroidViewController viewController =
PlatformViewsService.initAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.rtl);
final PlatformViewRenderBox platformViewRenderBox = PlatformViewRenderBox(
controller: viewController,
hitTestBehavior: PlatformViewHitTestBehavior.opaque,
gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{
Factory<VerticalDragGestureRecognizer>(
() => VerticalDragGestureRecognizer(),
),
},
);
layout(platformViewRenderBox);
pumpFrame(phase: EnginePhase.flushSemantics);
viewController.pointTransformer = (Offset offset) => platformViewRenderBox.globalToLocal(offset);
FakeAsync().run((FakeAsync async) {
// Put one pointer down.
RendererBinding.instance.platformDispatcher.onPointerDataPacket!(ui.PointerDataPacket(data: <ui.PointerData>[
_pointerData(ui.PointerChange.add, Offset.zero, pointer: 1, kind: PointerDeviceKind.touch),
_pointerData(ui.PointerChange.down, const Offset(10, 10), pointer: 1, kind: PointerDeviceKind.touch),
_pointerData(ui.PointerChange.remove, const Offset(10, 10), pointer: 1, kind: PointerDeviceKind.touch),
]));
async.flushMicrotasks();
// Put another pointer down and then cancel it.
RendererBinding.instance.platformDispatcher.onPointerDataPacket!(ui.PointerDataPacket(data: <ui.PointerData>[
_pointerData(ui.PointerChange.add, Offset.zero, pointer: 2, kind: PointerDeviceKind.touch),
_pointerData(ui.PointerChange.down, const Offset(20, 10), pointer: 2, kind: PointerDeviceKind.touch),
_pointerData(ui.PointerChange.cancel, const Offset(20, 10), pointer: 2, kind: PointerDeviceKind.touch),
]));
async.flushMicrotasks();
// The first pointer can still moving without crashing.
RendererBinding.instance.platformDispatcher.onPointerDataPacket!(ui.PointerDataPacket(data: <ui.PointerData>[
_pointerData(ui.PointerChange.add, Offset.zero, pointer: 1, kind: PointerDeviceKind.touch),
_pointerData(ui.PointerChange.move, const Offset(10, 10), pointer: 1, kind: PointerDeviceKind.touch),
_pointerData(ui.PointerChange.remove, const Offset(10, 10), pointer: 1, kind: PointerDeviceKind.touch),
]));
async.flushMicrotasks();
});
// Passes if no crashes.
});
test('created callback is reset when controller is changed', () {
final FakeAndroidPlatformViewsController viewsController = FakeAndroidPlatformViewsController();
viewsController.registerViewType('webview');
final AndroidViewController firstController = PlatformViewsService.initAndroidView(
id: 0,
viewType: 'webview',
layoutDirection: TextDirection.rtl,
);
final RenderAndroidView renderBox = RenderAndroidView(
viewController: firstController,
hitTestBehavior: PlatformViewHitTestBehavior.opaque,
gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{},
);
layout(renderBox);
pumpFrame(phase: EnginePhase.flushSemantics);
expect(firstController.createdCallbacks, isNotEmpty);
expect(firstController.createdCallbacks.length, 1);
final AndroidViewController secondController = PlatformViewsService.initAndroidView(
id: 0,
viewType: 'webview',
layoutDirection: TextDirection.rtl,
);
// Reset controller.
renderBox.controller = secondController;
expect(firstController.createdCallbacks, isEmpty);
expect(secondController.createdCallbacks, isNotEmpty);
expect(secondController.createdCallbacks.length, 1);
});
test('render object changed its visual appearance after texture is created', () {
FakeAsync().run((FakeAsync async) {
final AndroidViewController viewController =
PlatformViewsService.initAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.rtl);
final RenderAndroidView renderBox = RenderAndroidView(
viewController: viewController,
hitTestBehavior: PlatformViewHitTestBehavior.opaque,
gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{},
);
final Completer<void> viewCreation = Completer<void>();
const MethodChannel channel = MethodChannel('flutter/platform_views');
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (MethodCall methodCall) async {
assert(methodCall.method == 'create', 'Unexpected method call');
await viewCreation.future;
return /*textureId=*/ 0;
});
layout(renderBox);
pumpFrame(phase: EnginePhase.paint);
expect(renderBox.debugLayer, isNotNull);
expect(renderBox.debugLayer!.hasChildren, isFalse);
expect(viewController.isCreated, isFalse);
expect(renderBox.debugNeedsPaint, isFalse);
viewCreation.complete();
async.flushMicrotasks();
expect(viewController.isCreated, isTrue);
expect(renderBox.debugNeedsPaint, isTrue);
expect(renderBox.debugLayer!.hasChildren, isFalse);
pumpFrame(phase: EnginePhase.paint);
expect(renderBox.debugLayer!.hasChildren, isTrue);
expect(renderBox.debugLayer!.firstChild, isA<TextureLayer>());
});
});
test('markNeedsPaint does not get called on a disposed RO', () async {
FakeAsync().run((FakeAsync async) {
final AndroidViewController viewController =
PlatformViewsService.initAndroidView(id: 0, viewType: 'webview', layoutDirection: TextDirection.rtl);
final RenderAndroidView renderBox = RenderAndroidView(
viewController: viewController,
hitTestBehavior: PlatformViewHitTestBehavior.opaque,
gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{},
);
final Completer<void> viewCreation = Completer<void>();
const MethodChannel channel = MethodChannel('flutter/platform_views');
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (MethodCall methodCall) async {
assert(methodCall.method == 'create', 'Unexpected method call');
await viewCreation.future;
return /*textureId=*/ 0;
});
layout(renderBox);
pumpFrame(phase: EnginePhase.paint);
expect(renderBox.debugLayer, isNotNull);
expect(renderBox.debugLayer!.hasChildren, isFalse);
expect(viewController.isCreated, isFalse);
expect(renderBox.debugNeedsPaint, isFalse);
renderBox.dispose();
viewCreation.complete();
async.flushMicrotasks();
expect(viewController.isCreated, isTrue);
expect(renderBox.debugNeedsPaint, isFalse);
expect(renderBox.debugLayer, isNull);
pumpFrame(phase: EnginePhase.paint);
expect(renderBox.debugLayer, isNull);
});
});
test('markNeedsPaint does not get called when setting the same viewController', () {
FakeAsync().run((FakeAsync async) {
final Completer<void> viewCreation = Completer<void>();
const MethodChannel channel = MethodChannel('flutter/platform_views');
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, (MethodCall methodCall) async {
assert(methodCall.method == 'create', 'Unexpected method call');
await viewCreation.future;
return /*textureId=*/ 0;
});
bool futureCallbackRan = false;
PlatformViewsService.initUiKitView(id: 0, viewType: 'webview', layoutDirection: TextDirection.ltr).then((UiKitViewController viewController) {
final RenderUiKitView renderBox = RenderUiKitView(
viewController: viewController,
hitTestBehavior: PlatformViewHitTestBehavior.opaque,
gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{},
);
layout(renderBox);
pumpFrame(phase: EnginePhase.paint);
expect(renderBox.debugNeedsPaint, isFalse);
renderBox.viewController = viewController;
expect(renderBox.debugNeedsPaint, isFalse);
futureCallbackRan = true;
});
viewCreation.complete();
async.flushMicrotasks();
expect(futureCallbackRan, true);
});
});
}
ui.PointerData _pointerData(
ui.PointerChange change,
Offset logicalPosition, {
int device = 0,
PointerDeviceKind kind = PointerDeviceKind.mouse,
int pointer = 0,
}) {
final double devicePixelRatio = RendererBinding.instance.platformDispatcher.implicitView!.devicePixelRatio;
return ui.PointerData(
pointerIdentifier: pointer,
embedderId: pointer,
change: change,
physicalX: logicalPosition.dx * devicePixelRatio,
physicalY: logicalPosition.dy * devicePixelRatio,
kind: kind,
device: device,
);
}
| flutter/packages/flutter/test/rendering/platform_view_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/platform_view_test.dart",
"repo_id": "flutter",
"token_count": 4554
} | 854 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'rendering_tester.dart';
void main() {
TestRenderingFlutterBinding.ensureInitialized();
test('RenderSliverFixedExtentList layout test - rounding error', () {
final List<RenderBox> children = <RenderBox>[
RenderSizedBox(const Size(400.0, 100.0)),
RenderSizedBox(const Size(400.0, 100.0)),
RenderSizedBox(const Size(400.0, 100.0)),
];
final TestRenderSliverBoxChildManager childManager = TestRenderSliverBoxChildManager(
children: children,
);
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
cacheExtent: 0,
children: <RenderSliver>[
childManager.createRenderSliverFillViewport(),
],
);
layout(root);
expect(children[0].attached, true);
expect(children[1].attached, false);
root.offset = ViewportOffset.fixed(600);
pumpFrame();
expect(children[0].attached, false);
expect(children[1].attached, true);
// Simulate double precision error.
root.offset = ViewportOffset.fixed(1199.999999999998);
pumpFrame();
expect(children[1].attached, false);
expect(children[2].attached, true);
});
group('getMaxChildIndexForScrollOffset', () {
// Regression test for https://github.com/flutter/flutter/issues/68182
const double genericItemExtent = 600.0;
const double extraValueToNotHaveRoundingIssues = 1e-10;
const double extraValueToHaveRoundingIssues = 1e-11;
test('should be 0 when item extent is 0', () {
const double offsetValueWhichDoesntCare = 1234;
final int actual = testGetMaxChildIndexForScrollOffset(offsetValueWhichDoesntCare, 0);
expect(actual, 0);
});
test('should be 0 when offset is 0', () {
final int actual = testGetMaxChildIndexForScrollOffset(0, genericItemExtent);
expect(actual, 0);
});
test('should be 0 when offset is equal to item extent', () {
final int actual = testGetMaxChildIndexForScrollOffset(genericItemExtent, genericItemExtent);
expect(actual, 0);
});
test('should be 1 when offset is greater than item extent', () {
final int actual = testGetMaxChildIndexForScrollOffset(genericItemExtent + 1, genericItemExtent);
expect(actual, 1);
});
test('should be 1 when offset is slightly greater than item extent', () {
final int actual = testGetMaxChildIndexForScrollOffset(
genericItemExtent + extraValueToNotHaveRoundingIssues,
genericItemExtent,
);
expect(actual, 1);
});
test('should be 4 when offset is four times and a half greater than item extent', () {
final int actual = testGetMaxChildIndexForScrollOffset(genericItemExtent * 4.5, genericItemExtent);
expect(actual, 4);
});
test('should be 5 when offset is 6 times greater than item extent', () {
const double anotherGenericItemExtent = 414.0;
final int actual = testGetMaxChildIndexForScrollOffset(
anotherGenericItemExtent * 6,
anotherGenericItemExtent,
);
expect(actual, 5);
});
test('should be 5 when offset is 6 times greater than a specific item extent where the division will return more than 13 zero decimals', () {
const double itemExtentSpecificForAProblematicScreenSize = 411.42857142857144;
final int actual = testGetMaxChildIndexForScrollOffset(
itemExtentSpecificForAProblematicScreenSize * 6 + extraValueToHaveRoundingIssues,
itemExtentSpecificForAProblematicScreenSize,
);
expect(actual, 5);
});
test('should be 0 when offset is a bit greater than item extent', () {
final int actual = testGetMaxChildIndexForScrollOffset(
genericItemExtent + extraValueToHaveRoundingIssues,
genericItemExtent,
);
expect(actual, 0);
});
});
test('Implements paintsChild correctly', () {
final List<RenderBox> children = <RenderBox>[
RenderSizedBox(const Size(400.0, 100.0)),
RenderSizedBox(const Size(400.0, 100.0)),
RenderSizedBox(const Size(400.0, 100.0)),
];
final TestRenderSliverBoxChildManager childManager = TestRenderSliverBoxChildManager(
children: children,
);
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
cacheExtent: 0,
children: <RenderSliver>[
childManager.createRenderSliverFillViewport(),
],
);
layout(root);
expect(children.first.parent, isA<RenderSliverMultiBoxAdaptor>());
final RenderSliverMultiBoxAdaptor parent = children.first.parent! as RenderSliverMultiBoxAdaptor;
expect(parent.paintsChild(children[0]), true);
expect(parent.paintsChild(children[1]), false);
expect(parent.paintsChild(children[2]), false);
root.offset = ViewportOffset.fixed(600);
pumpFrame();
expect(parent.paintsChild(children[0]), false);
expect(parent.paintsChild(children[1]), true);
expect(parent.paintsChild(children[2]), false);
root.offset = ViewportOffset.fixed(1200);
pumpFrame();
expect(parent.paintsChild(children[0]), false);
expect(parent.paintsChild(children[1]), false);
expect(parent.paintsChild(children[2]), true);
});
test('RenderSliverFillViewport correctly references itemExtent, non-zero offset', () {
final List<RenderBox> children = <RenderBox>[
RenderSizedBox(const Size(400.0, 100.0)),
RenderSizedBox(const Size(400.0, 100.0)),
RenderSizedBox(const Size(400.0, 100.0)),
];
final TestRenderSliverBoxChildManager childManager = TestRenderSliverBoxChildManager(
children: children,
);
final RenderSliverFillViewport sliver = childManager.createRenderSliverFillViewport();
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.fixed(1200.0),
cacheExtent: 100,
children: <RenderSliver>[ sliver ],
);
layout(root);
// These are a bogus itemExtents, and motivate the deprecation. The sliver
// knows its itemExtent, and should use its configured extent rather than
// whatever is provided through these methods.
// Also, the API is a bit redundant, so we clean!
// In this case, the true item extent is 600 to fill the viewport.
expect(
sliver.constraints.scrollOffset,
1200.0
);
expect(sliver.itemExtent, 600.0);
final double layoutOffset = sliver.indexToLayoutOffset(
150.0, // itemExtent
10,
);
expect(layoutOffset, 6000.0);
final int minIndex = sliver.getMinChildIndexForScrollOffset(
sliver.constraints.scrollOffset,
150.0, // itemExtent
);
expect(minIndex, 2);
final int maxIndex = sliver.getMaxChildIndexForScrollOffset(
sliver.constraints.scrollOffset,
150, // itemExtent
);
expect(maxIndex, 1);
final double maxScrollOffset = sliver.computeMaxScrollOffset(
sliver.constraints,
150, // itemExtent
);
expect(maxScrollOffset, 1800.0);
});
test('RenderSliverFillViewport correctly references itemExtent, zero offset', () {
final List<RenderBox> children = <RenderBox>[
RenderSizedBox(const Size(400.0, 100.0)),
RenderSizedBox(const Size(400.0, 100.0)),
RenderSizedBox(const Size(400.0, 100.0)),
];
final TestRenderSliverBoxChildManager childManager = TestRenderSliverBoxChildManager(
children: children,
);
final RenderSliverFillViewport sliver = childManager.createRenderSliverFillViewport();
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
cacheExtent: 100,
children: <RenderSliver>[ sliver ],
);
layout(root);
// These are a bogus itemExtents, and motivate the deprecation. The sliver
// knows its itemExtent, and should use its configured extent rather than
// whatever is provided through these methods.
// Also, the API is a bit redundant, so we clean!
// In this case, the true item extent is 600 to fill the viewport.
expect(
sliver.constraints.scrollOffset,
0.0
);
expect(sliver.itemExtent, 600.0);
final double layoutOffset = sliver.indexToLayoutOffset(
150.0, // itemExtent
10,
);
expect(layoutOffset, 6000.0);
final int minIndex = sliver.getMinChildIndexForScrollOffset(
sliver.constraints.scrollOffset,
150.0, // itemExtent
);
expect(minIndex, 0);
final int maxIndex = sliver.getMaxChildIndexForScrollOffset(
sliver.constraints.scrollOffset,
150, // itemExtent
);
expect(maxIndex, 0);
final double maxScrollOffset = sliver.computeMaxScrollOffset(
sliver.constraints,
150, // itemExtent
);
expect(maxScrollOffset, 1800.0);
});
test('RenderSliverFixedExtentList correctly references itemExtent, non-zero offset', () {
final List<RenderBox> children = <RenderBox>[
RenderSizedBox(const Size(400.0, 100.0)),
RenderSizedBox(const Size(400.0, 100.0)),
RenderSizedBox(const Size(400.0, 100.0)),
];
final TestRenderSliverBoxChildManager childManager = TestRenderSliverBoxChildManager(
children: children,
);
final RenderSliverFixedExtentList sliver = childManager.createRenderSliverFixedExtentList(30.0);
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.fixed(45.0),
cacheExtent: 100,
children: <RenderSliver>[ sliver ],
);
layout(root);
// These are a bogus itemExtents, and motivate the deprecation. The sliver
// knows its itemExtent, and should use its configured extent rather than
// whatever is provided through these methods.
// Also, the API is a bit redundant, so we clean!
// In this case, the true item extent is 30.0.
expect(
sliver.constraints.scrollOffset,
45.0
);
expect(sliver.constraints.viewportMainAxisExtent, 600.0);
expect(sliver.itemExtent, 30.0);
final double layoutOffset = sliver.indexToLayoutOffset(
150.0, // itemExtent
10,
);
expect(layoutOffset, 300.0);
final int minIndex = sliver.getMinChildIndexForScrollOffset(
sliver.constraints.scrollOffset,
150.0, // itemExtent
);
expect(minIndex, 1);
final int maxIndex = sliver.getMaxChildIndexForScrollOffset(
sliver.constraints.scrollOffset,
150, // itemExtent
);
expect(maxIndex, 1);
final double maxScrollOffset = sliver.computeMaxScrollOffset(
sliver.constraints,
150, // itemExtent
);
expect(maxScrollOffset, 90.0);
});
test('RenderSliverFixedExtentList correctly references itemExtent, zero offset', () {
final List<RenderBox> children = <RenderBox>[
RenderSizedBox(const Size(400.0, 100.0)),
RenderSizedBox(const Size(400.0, 100.0)),
RenderSizedBox(const Size(400.0, 100.0)),
];
final TestRenderSliverBoxChildManager childManager = TestRenderSliverBoxChildManager(
children: children,
);
final RenderSliverFixedExtentList sliver = childManager.createRenderSliverFixedExtentList(30.0);
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
cacheExtent: 100,
children: <RenderSliver>[ sliver ],
);
layout(root);
// These are a bogus itemExtents, and motivate the deprecation. The sliver
// knows its itemExtent, and should use its configured extent rather than
// whatever is provided through these methods.
// Also, the API is a bit redundant, so we clean!
// In this case, the true item extent is 30.0.
expect(
sliver.constraints.scrollOffset,
0.0
);
expect(sliver.constraints.viewportMainAxisExtent, 600.0);
expect(sliver.itemExtent, 30.0);
final double layoutOffset = sliver.indexToLayoutOffset(
150.0, // itemExtent
10,
);
expect(layoutOffset, 300.0);
final int minIndex = sliver.getMinChildIndexForScrollOffset(
sliver.constraints.scrollOffset,
150.0, // itemExtent
);
expect(minIndex, 0);
final int maxIndex = sliver.getMaxChildIndexForScrollOffset(
sliver.constraints.scrollOffset,
150, // itemExtent
);
expect(maxIndex, 0);
final double maxScrollOffset = sliver.computeMaxScrollOffset(
sliver.constraints,
150, // itemExtent
);
expect(maxScrollOffset, 90.0);
});
test('RenderSliverMultiBoxAdaptor has calculate leading and trailing garbage', () {
final List<RenderBox> children = <RenderBox>[
RenderSizedBox(const Size(400.0, 100.0)),
RenderSizedBox(const Size(400.0, 100.0)),
RenderSizedBox(const Size(400.0, 100.0)),
];
final TestRenderSliverBoxChildManager childManager = TestRenderSliverBoxChildManager(
children: children,
);
final RenderSliverFixedExtentList sliver = childManager.createRenderSliverFixedExtentList(30.0);
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
cacheExtent: 100,
children: <RenderSliver>[ sliver ],
);
layout(root);
// There are 3 children. If I want to garbage collect based on keeping only
// the middle child, then I should get 1 for leading and 1 for trailing.
expect(sliver.calculateLeadingGarbage(firstIndex: 1), 1);
expect(sliver.calculateTrailingGarbage(lastIndex: 1), 1);
});
}
int testGetMaxChildIndexForScrollOffset(double scrollOffset, double itemExtent) {
final TestRenderSliverFixedExtentBoxAdaptor renderSliver = TestRenderSliverFixedExtentBoxAdaptor(itemExtent: itemExtent);
return renderSliver.getMaxChildIndexForScrollOffset(scrollOffset, itemExtent);
}
class TestRenderSliverBoxChildManager extends RenderSliverBoxChildManager {
TestRenderSliverBoxChildManager({
required this.children,
});
RenderSliverMultiBoxAdaptor? _renderObject;
List<RenderBox> children;
RenderSliverFillViewport createRenderSliverFillViewport() {
assert(_renderObject == null);
_renderObject = RenderSliverFillViewport(
childManager: this,
);
return _renderObject! as RenderSliverFillViewport;
}
RenderSliverFixedExtentList createRenderSliverFixedExtentList(double itemExtent) {
assert(_renderObject == null);
_renderObject = RenderSliverFixedExtentList(
childManager: this,
itemExtent: itemExtent,
);
return _renderObject! as RenderSliverFixedExtentList;
}
int? _currentlyUpdatingChildIndex;
@override
void createChild(int index, { required RenderBox? after }) {
if (index < 0 || index >= children.length) {
return;
}
try {
_currentlyUpdatingChildIndex = index;
_renderObject!.insert(children[index], after: after);
} finally {
_currentlyUpdatingChildIndex = null;
}
}
@override
void removeChild(RenderBox child) {
_renderObject!.remove(child);
}
@override
double estimateMaxScrollOffset(
SliverConstraints constraints, {
int? firstIndex,
int? lastIndex,
double? leadingScrollOffset,
double? trailingScrollOffset,
}) {
assert(lastIndex! >= firstIndex!);
return children.length * (trailingScrollOffset! - leadingScrollOffset!) / (lastIndex! - firstIndex! + 1);
}
@override
int get childCount => children.length;
@override
void didAdoptChild(RenderBox child) {
assert(_currentlyUpdatingChildIndex != null);
final SliverMultiBoxAdaptorParentData childParentData = child.parentData! as SliverMultiBoxAdaptorParentData;
childParentData.index = _currentlyUpdatingChildIndex;
}
@override
void setDidUnderflow(bool value) { }
}
class TestRenderSliverFixedExtentBoxAdaptor extends RenderSliverFixedExtentBoxAdaptor {
TestRenderSliverFixedExtentBoxAdaptor({
required double itemExtent
}) : _itemExtent = itemExtent,
super(childManager: TestRenderSliverBoxChildManager(children: <RenderBox>[]));
final double _itemExtent;
@override
int getMaxChildIndexForScrollOffset(double scrollOffset, double itemExtent) {
return super.getMaxChildIndexForScrollOffset(scrollOffset, itemExtent);
}
@override
double get itemExtent => _itemExtent;
}
| flutter/packages/flutter/test/rendering/sliver_fixed_extent_layout_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/sliver_fixed_extent_layout_test.dart",
"repo_id": "flutter",
"token_count": 5887
} | 855 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'rendering_tester.dart';
void main() {
TestRenderingFlutterBinding.ensureInitialized();
test('Wrap test; toStringDeep', () {
final RenderWrap renderWrap = RenderWrap();
expect(renderWrap, hasAGoodToStringDeep);
expect(
renderWrap.toStringDeep(minLevel: DiagnosticLevel.info),
equalsIgnoringHashCodes(
'RenderWrap#00000 NEEDS-LAYOUT NEEDS-PAINT DETACHED\n'
' parentData: MISSING\n'
' constraints: MISSING\n'
' size: MISSING\n'
' direction: horizontal\n'
' alignment: start\n'
' spacing: 0.0\n'
' runAlignment: start\n'
' runSpacing: 0.0\n'
' crossAxisAlignment: 0.0\n',
),
);
});
test('Compute intrinsic height test', () {
final List<RenderBox> children = <RenderBox>[
RenderConstrainedBox(
additionalConstraints: const BoxConstraints(
minWidth: 80,
minHeight: 80,
),
),
RenderConstrainedBox(
additionalConstraints: const BoxConstraints(
minWidth: 80,
minHeight: 80,
),
),
RenderConstrainedBox(
additionalConstraints: const BoxConstraints(
minWidth: 80,
minHeight: 80,
),
),
];
final RenderWrap renderWrap = RenderWrap();
children.forEach(renderWrap.add);
renderWrap.spacing = 5;
renderWrap.runSpacing = 5;
renderWrap.direction = Axis.horizontal;
expect(renderWrap.computeMaxIntrinsicHeight(245), 165);
expect(renderWrap.computeMaxIntrinsicHeight(250), 80);
expect(renderWrap.computeMaxIntrinsicHeight(80), 250);
expect(renderWrap.computeMaxIntrinsicHeight(79), 250);
expect(renderWrap.computeMinIntrinsicHeight(245), 165);
expect(renderWrap.computeMinIntrinsicHeight(250), 80);
expect(renderWrap.computeMinIntrinsicHeight(80), 250);
expect(renderWrap.computeMinIntrinsicHeight(79), 250);
});
test('Compute intrinsic height test for width-in-height-out children', () {
const double lineHeight = 15.0;
final RenderWrap renderWrap = RenderWrap();
renderWrap.add(
RenderParagraph(
const TextSpan(
text: 'A very very very very very very very very long text',
style: TextStyle(fontSize: lineHeight),
),
textDirection: TextDirection.ltr,
),
);
renderWrap.spacing = 0;
renderWrap.runSpacing = 0;
renderWrap.direction = Axis.horizontal;
expect(renderWrap.computeMaxIntrinsicHeight(double.infinity), lineHeight);
expect(renderWrap.computeMaxIntrinsicHeight(600), 2 * lineHeight);
expect(renderWrap.computeMaxIntrinsicHeight(300), 3 * lineHeight);
});
test('Compute intrinsic width test for height-in-width-out children', () {
const double lineHeight = 15.0;
final RenderWrap renderWrap = RenderWrap();
renderWrap.add(
// Rotates a width-in-height-out render object to make it height-in-width-out.
RenderRotatedBox(
quarterTurns: 1,
child: RenderParagraph(
const TextSpan(
text: 'A very very very very very very very very long text',
style: TextStyle(fontSize: lineHeight),
),
textDirection: TextDirection.ltr,
),
),
);
renderWrap.spacing = 0;
renderWrap.runSpacing = 0;
renderWrap.direction = Axis.vertical;
expect(renderWrap.computeMaxIntrinsicWidth(double.infinity), lineHeight);
expect(renderWrap.computeMaxIntrinsicWidth(600), 2 * lineHeight);
expect(renderWrap.computeMaxIntrinsicWidth(300), 3 * lineHeight);
});
test('Compute intrinsic width test', () {
final List<RenderBox> children = <RenderBox>[
RenderConstrainedBox(
additionalConstraints: const BoxConstraints(
minWidth: 80,
minHeight: 80,
),
),
RenderConstrainedBox(
additionalConstraints: const BoxConstraints(
minWidth: 80,
minHeight: 80,
),
),
RenderConstrainedBox(
additionalConstraints: const BoxConstraints(
minWidth: 80,
minHeight: 80,
),
),
];
final RenderWrap renderWrap = RenderWrap();
children.forEach(renderWrap.add);
renderWrap.spacing = 5;
renderWrap.runSpacing = 5;
renderWrap.direction = Axis.vertical;
expect(renderWrap.computeMaxIntrinsicWidth(245), 165);
expect(renderWrap.computeMaxIntrinsicWidth(250), 80);
expect(renderWrap.computeMaxIntrinsicWidth(80), 250);
expect(renderWrap.computeMaxIntrinsicWidth(79), 250);
expect(renderWrap.computeMinIntrinsicWidth(245), 165);
expect(renderWrap.computeMinIntrinsicWidth(250), 80);
expect(renderWrap.computeMinIntrinsicWidth(80), 250);
expect(renderWrap.computeMinIntrinsicWidth(79), 250);
});
test('Compute intrinsic height for only one run', () {
final RenderBox child = RenderConstrainedBox(
additionalConstraints: const BoxConstraints(
minWidth: 80,
minHeight: 80,
),
);
final RenderWrap renderWrap = RenderWrap();
renderWrap.add(child);
renderWrap.spacing = 5;
renderWrap.runSpacing = 5;
renderWrap.direction = Axis.horizontal;
expect(renderWrap.computeMaxIntrinsicHeight(100), 80);
expect(renderWrap.computeMaxIntrinsicHeight(79), 80);
expect(renderWrap.computeMaxIntrinsicHeight(80), 80);
expect(renderWrap.computeMinIntrinsicHeight(100), 80);
expect(renderWrap.computeMinIntrinsicHeight(79), 80);
expect(renderWrap.computeMinIntrinsicHeight(80), 80);
});
test('Compute intrinsic width for only one run', () {
final RenderBox child = RenderConstrainedBox(
additionalConstraints: const BoxConstraints(
minWidth: 80,
minHeight: 80,
),
);
final RenderWrap renderWrap = RenderWrap();
renderWrap.add(child);
renderWrap.spacing = 5;
renderWrap.runSpacing = 5;
renderWrap.direction = Axis.vertical;
expect(renderWrap.computeMaxIntrinsicWidth(100), 80);
expect(renderWrap.computeMaxIntrinsicWidth(79), 80);
expect(renderWrap.computeMaxIntrinsicWidth(80), 80);
expect(renderWrap.computeMinIntrinsicWidth(100), 80);
expect(renderWrap.computeMinIntrinsicWidth(79), 80);
expect(renderWrap.computeMinIntrinsicWidth(80), 80);
});
test('Wrap respects clipBehavior', () {
const BoxConstraints viewport = BoxConstraints(maxHeight: 100.0, maxWidth: 100.0);
final TestClipPaintingContext context = TestClipPaintingContext();
for (final Clip? clip in <Clip?>[null, ...Clip.values]) {
final RenderWrap wrap;
switch (clip){
case Clip.none:
case Clip.hardEdge:
case Clip.antiAlias:
case Clip.antiAliasWithSaveLayer:
wrap = RenderWrap(textDirection: TextDirection.ltr, children: <RenderBox>[box200x200], clipBehavior: clip!);
case null:
wrap = RenderWrap(textDirection: TextDirection.ltr, children: <RenderBox>[box200x200]);
}
layout(wrap, constraints: viewport, phase: EnginePhase.composite, onErrors: expectNoFlutterErrors);
context.paintChild(wrap, Offset.zero);
// By default, clipBehavior should be Clip.none
expect(context.clipBehavior, equals(clip ?? Clip.none));
}
});
}
| flutter/packages/flutter/test/rendering/wrap_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/wrap_test.dart",
"repo_id": "flutter",
"token_count": 3092
} | 856 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
import 'package:vector_math/vector_math_64.dart';
import '../rendering/rendering_tester.dart';
const int kMaxFrameworkAccessibilityIdentifier = (1<<16) - 1;
void main() {
TestRenderingFlutterBinding.ensureInitialized();
setUp(() {
debugResetSemanticsIdCounter();
});
group('SemanticsNode', () {
const SemanticsTag tag1 = SemanticsTag('Tag One');
const SemanticsTag tag2 = SemanticsTag('Tag Two');
const SemanticsTag tag3 = SemanticsTag('Tag Three');
test('tagging', () {
final SemanticsNode node = SemanticsNode();
expect(node.isTagged(tag1), isFalse);
expect(node.isTagged(tag2), isFalse);
node.tags = <SemanticsTag>{tag1};
expect(node.isTagged(tag1), isTrue);
expect(node.isTagged(tag2), isFalse);
node.tags!.add(tag2);
expect(node.isTagged(tag1), isTrue);
expect(node.isTagged(tag2), isTrue);
});
test('getSemanticsData includes tags', () {
final Set<SemanticsTag> tags = <SemanticsTag>{tag1, tag2};
final SemanticsNode node = SemanticsNode()
..rect = const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0)
..tags = tags;
expect(node.getSemanticsData().tags, tags);
tags.add(tag3);
final SemanticsConfiguration config = SemanticsConfiguration()
..isSemanticBoundary = true
..isMergingSemanticsOfDescendants = true;
node.updateWith(
config: config,
childrenInInversePaintOrder: <SemanticsNode>[
SemanticsNode()
..rect = const Rect.fromLTRB(5.0, 5.0, 10.0, 10.0)
..tags = tags,
],
);
expect(node.getSemanticsData().tags, tags);
});
test('SemanticsConfiguration can set both string label/value/hint and attributed version', () {
final SemanticsConfiguration config = SemanticsConfiguration();
config.label = 'label1';
expect(config.label, 'label1');
expect(config.attributedLabel.string, 'label1');
expect(config.attributedLabel.attributes.isEmpty, isTrue);
expect(
(SemanticsNode()..updateWith(config: config)).toString(),
'SemanticsNode#1(STALE, owner: null, Rect.fromLTRB(0.0, 0.0, 0.0, 0.0), invisible, label: "label1")',
);
config.attributedLabel = AttributedString(
'label2',
attributes: <StringAttribute>[
SpellOutStringAttribute(range: const TextRange(start: 0, end:1)),
]
);
expect(config.label, 'label2');
expect(config.attributedLabel.string, 'label2');
expect(config.attributedLabel.attributes.length, 1);
expect(config.attributedLabel.attributes[0] is SpellOutStringAttribute, isTrue);
expect(config.attributedLabel.attributes[0].range, const TextRange(start: 0, end: 1));
expect(
(SemanticsNode()..updateWith(config: config)).toString(),
'SemanticsNode#2(STALE, owner: null, Rect.fromLTRB(0.0, 0.0, 0.0, 0.0), invisible, label: "label2" [SpellOutStringAttribute(TextRange(start: 0, end: 1))])',
);
config.label = 'label3';
expect(config.label, 'label3');
expect(config.attributedLabel.string, 'label3');
expect(config.attributedLabel.attributes.isEmpty, isTrue);
expect(
(SemanticsNode()..updateWith(config: config)).toString(),
'SemanticsNode#3(STALE, owner: null, Rect.fromLTRB(0.0, 0.0, 0.0, 0.0), invisible, label: "label3")',
);
config.value = 'value1';
expect(config.value, 'value1');
expect(config.attributedValue.string, 'value1');
expect(config.attributedValue.attributes.isEmpty, isTrue);
expect(
(SemanticsNode()..updateWith(config: config)).toString(),
'SemanticsNode#4(STALE, owner: null, Rect.fromLTRB(0.0, 0.0, 0.0, 0.0), invisible, label: "label3", value: "value1")',
);
config.attributedValue = AttributedString(
'value2',
attributes: <StringAttribute>[
SpellOutStringAttribute(range: const TextRange(start: 0, end:1)),
]
);
expect(config.value, 'value2');
expect(config.attributedValue.string, 'value2');
expect(config.attributedValue.attributes.length, 1);
expect(config.attributedValue.attributes[0] is SpellOutStringAttribute, isTrue);
expect(config.attributedValue.attributes[0].range, const TextRange(start: 0, end: 1));
expect(
(SemanticsNode()..updateWith(config: config)).toString(),
'SemanticsNode#5(STALE, owner: null, Rect.fromLTRB(0.0, 0.0, 0.0, 0.0), invisible, label: "label3", value: "value2" [SpellOutStringAttribute(TextRange(start: 0, end: 1))])',
);
config.value = 'value3';
expect(config.value, 'value3');
expect(config.attributedValue.string, 'value3');
expect(config.attributedValue.attributes.isEmpty, isTrue);
expect(
(SemanticsNode()..updateWith(config: config)).toString(),
'SemanticsNode#6(STALE, owner: null, Rect.fromLTRB(0.0, 0.0, 0.0, 0.0), invisible, label: "label3", value: "value3")',
);
config.hint = 'hint1';
expect(config.hint, 'hint1');
expect(config.attributedHint.string, 'hint1');
expect(config.attributedHint.attributes.isEmpty, isTrue);
expect(
(SemanticsNode()..updateWith(config: config)).toString(),
'SemanticsNode#7(STALE, owner: null, Rect.fromLTRB(0.0, 0.0, 0.0, 0.0), invisible, label: "label3", value: "value3", hint: "hint1")',
);
config.attributedHint = AttributedString(
'hint2',
attributes: <StringAttribute>[
SpellOutStringAttribute(range: const TextRange(start: 0, end:1)),
]
);
expect(config.hint, 'hint2');
expect(config.attributedHint.string, 'hint2');
expect(config.attributedHint.attributes.length, 1);
expect(config.attributedHint.attributes[0] is SpellOutStringAttribute, isTrue);
expect(config.attributedHint.attributes[0].range, const TextRange(start: 0, end: 1));
expect(
(SemanticsNode()..updateWith(config: config)).toString(),
'SemanticsNode#8(STALE, owner: null, Rect.fromLTRB(0.0, 0.0, 0.0, 0.0), invisible, label: "label3", value: "value3", hint: "hint2" [SpellOutStringAttribute(TextRange(start: 0, end: 1))])',
);
config.hint = 'hint3';
expect(config.hint, 'hint3');
expect(config.attributedHint.string, 'hint3');
expect(config.attributedHint.attributes.isEmpty, isTrue);
expect(
(SemanticsNode()..updateWith(config: config)).toString(),
'SemanticsNode#9(STALE, owner: null, Rect.fromLTRB(0.0, 0.0, 0.0, 0.0), invisible, label: "label3", value: "value3", hint: "hint3")',
);
});
test('provides the correct isMergedIntoParent value', () {
final SemanticsNode root = SemanticsNode()..rect = const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0);
final SemanticsNode node1 = SemanticsNode()..rect = const Rect.fromLTRB(1.0, 0.0, 10.0, 10.0);
final SemanticsNode node11 = SemanticsNode()..rect = const Rect.fromLTRB(2.0, 0.0, 10.0, 10.0);
final SemanticsNode node12 = SemanticsNode()..rect = const Rect.fromLTRB(3.0, 0.0, 10.0, 10.0);
final SemanticsConfiguration noMergeConfig = SemanticsConfiguration()
..isSemanticBoundary = true
..isMergingSemanticsOfDescendants = false;
final SemanticsConfiguration mergeConfig = SemanticsConfiguration()
..isSemanticBoundary = true
..isMergingSemanticsOfDescendants = true;
node1.updateWith(config: noMergeConfig, childrenInInversePaintOrder: <SemanticsNode>[node11, node12]);
expect(node1.isMergedIntoParent, false);
expect(node1.mergeAllDescendantsIntoThisNode, false);
expect(node11.isMergedIntoParent, false);
expect(node12.isMergedIntoParent, false);
expect(root.isMergedIntoParent, false);
root.updateWith(config: mergeConfig, childrenInInversePaintOrder: <SemanticsNode>[node1]);
expect(node1.isMergedIntoParent, true);
expect(node1.mergeAllDescendantsIntoThisNode, false);
expect(node11.isMergedIntoParent, true);
expect(node12.isMergedIntoParent, true);
expect(root.isMergedIntoParent, false);
expect(root.mergeAllDescendantsIntoThisNode, true);
// Change config
node1.updateWith(config: mergeConfig, childrenInInversePaintOrder: <SemanticsNode>[node11, node12]);
expect(node1.isMergedIntoParent, true);
expect(node1.mergeAllDescendantsIntoThisNode, true);
expect(node11.isMergedIntoParent, true);
expect(node12.isMergedIntoParent, true);
expect(root.isMergedIntoParent, false);
expect(root.mergeAllDescendantsIntoThisNode, true);
root.updateWith(config: noMergeConfig, childrenInInversePaintOrder: <SemanticsNode>[node1]);
expect(node1.isMergedIntoParent, false);
expect(node1.mergeAllDescendantsIntoThisNode, true);
expect(node11.isMergedIntoParent, true);
expect(node12.isMergedIntoParent, true);
expect(root.isMergedIntoParent, false);
expect(root.mergeAllDescendantsIntoThisNode, false);
});
test('sendSemanticsUpdate verifies no invisible nodes', () {
const Rect invisibleRect = Rect.fromLTRB(0.0, 0.0, 0.0, 10.0);
const Rect visibleRect = Rect.fromLTRB(0.0, 0.0, 10.0, 10.0);
final SemanticsOwner owner = SemanticsOwner(
onSemanticsUpdate: (SemanticsUpdate update) {},
);
final SemanticsNode root = SemanticsNode.root(owner: owner)..rect = invisibleRect;
final SemanticsNode child = SemanticsNode();
// It's ok to have an invisible root.
expect(owner.sendSemanticsUpdate, returnsNormally);
// It's ok to have an invisible child if it's merged to an ancestor.
root
..rect = visibleRect
..updateWith(
config: SemanticsConfiguration()
..isSemanticBoundary = true
..isMergingSemanticsOfDescendants = true,
childrenInInversePaintOrder: <SemanticsNode>[child..rect = invisibleRect],
);
expect(owner.sendSemanticsUpdate, returnsNormally);
// It's ok if all nodes are visible.
root
..rect = visibleRect
..updateWith(
config: SemanticsConfiguration()
..isSemanticBoundary = true
..isMergingSemanticsOfDescendants = false,
childrenInInversePaintOrder: <SemanticsNode>[child..rect = visibleRect],
);
expect(owner.sendSemanticsUpdate, returnsNormally);
// Invisible root with children bad.
root
..rect = invisibleRect
..updateWith(
config: SemanticsConfiguration()
..isSemanticBoundary = true
..isMergingSemanticsOfDescendants = true,
childrenInInversePaintOrder: <SemanticsNode>[child..rect = invisibleRect],
);
expect(owner.sendSemanticsUpdate, throwsA(isA<FlutterError>().having(
(FlutterError error) => error.message, 'message', equals(
'Invisible SemanticsNodes should not be added to the tree.\n'
'The following invisible SemanticsNodes were added to the tree:\n'
'SemanticsNode#0(dirty, merge boundary ⛔️, Rect.fromLTRB(0.0, 0.0, 0.0, 10.0), invisible)\n'
'which was added as the root SemanticsNode\n'
'An invisible SemanticsNode is one whose rect is not on screen hence not reachable for users, and its semantic information is not merged into a visible parent.\n'
'An invisible SemanticsNode makes the accessibility experience confusing, as it does not provide any visual indication when the user selects it via accessibility technologies.\n'
'Consider removing the above invisible SemanticsNodes if they were added by your RenderObject.assembleSemanticsNode implementation, or filing a bug on GitHub:\n'
' https://github.com/flutter/flutter/issues/new?template=2_bug.yml'
),
)));
// Invisible children bad.
root
..rect = visibleRect
..updateWith(
config: SemanticsConfiguration()
..isSemanticBoundary = true
..isMergingSemanticsOfDescendants = false,
childrenInInversePaintOrder: <SemanticsNode>[child..rect = invisibleRect],
);
expect(owner.sendSemanticsUpdate, throwsA(isA<FlutterError>().having(
(FlutterError error) => error.message, 'message', equals(
'Invisible SemanticsNodes should not be added to the tree.\n'
'The following invisible SemanticsNodes were added to the tree:\n'
'SemanticsNode#1(dirty, Rect.fromLTRB(0.0, 0.0, 0.0, 10.0), invisible)\n'
'which was added as a child of:\n'
' SemanticsNode#0(dirty, Rect.fromLTRB(0.0, 0.0, 10.0, 10.0))\n'
'An invisible SemanticsNode is one whose rect is not on screen hence not reachable for users, and its semantic information is not merged into a visible parent.\n'
'An invisible SemanticsNode makes the accessibility experience confusing, as it does not provide any visual indication when the user selects it via accessibility technologies.\n'
'Consider removing the above invisible SemanticsNodes if they were added by your RenderObject.assembleSemanticsNode implementation, or filing a bug on GitHub:\n'
' https://github.com/flutter/flutter/issues/new?template=2_bug.yml'
),
)));
});
test('mutate existing semantic node list errors', () {
final SemanticsNode node = SemanticsNode()
..rect = const Rect.fromLTRB(0.0, 0.0, 10.0, 10.0);
final SemanticsConfiguration config = SemanticsConfiguration()
..isSemanticBoundary = true
..isMergingSemanticsOfDescendants = true;
final List<SemanticsNode> children = <SemanticsNode>[
SemanticsNode()
..rect = const Rect.fromLTRB(5.0, 5.0, 10.0, 10.0),
];
node.updateWith(
config: config,
childrenInInversePaintOrder: children,
);
children.add(
SemanticsNode()
..rect = const Rect.fromLTRB(42.0, 42.0, 52.0, 52.0),
);
{
late FlutterError error;
try {
node.updateWith(
config: config,
childrenInInversePaintOrder: children,
);
} on FlutterError catch (e) {
error = e;
}
expect(error.toString(), equalsIgnoringHashCodes(
'Failed to replace child semantics nodes because the list of `SemanticsNode`s was mutated.\n'
'Instead of mutating the existing list, create a new list containing the desired `SemanticsNode`s.\n'
'Error details:\n'
"The list's length has changed from 1 to 2.",
));
expect(
error.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(),
'Instead of mutating the existing list, create a new list containing the desired `SemanticsNode`s.',
);
}
{
late FlutterError error;
final List<SemanticsNode> modifiedChildren = <SemanticsNode>[
SemanticsNode()
..rect = const Rect.fromLTRB(5.0, 5.0, 10.0, 10.0),
SemanticsNode()
..rect = const Rect.fromLTRB(10.0, 10.0, 20.0, 20.0),
];
node.updateWith(
config: config,
childrenInInversePaintOrder: modifiedChildren,
);
try {
modifiedChildren[0] = SemanticsNode()
..rect = const Rect.fromLTRB(0.0, 0.0, 20.0, 20.0);
modifiedChildren[1] = SemanticsNode()
..rect = const Rect.fromLTRB(40.0, 14.0, 60.0, 60.0);
node.updateWith(
config: config,
childrenInInversePaintOrder: modifiedChildren,
);
} on FlutterError catch (e) {
error = e;
}
expect(error.toStringDeep(), equalsIgnoringHashCodes(
'FlutterError\n'
' Failed to replace child semantics nodes because the list of\n'
' `SemanticsNode`s was mutated.\n'
' Instead of mutating the existing list, create a new list\n'
' containing the desired `SemanticsNode`s.\n'
' Error details:\n'
' Child node at position 0 was replaced:\n'
' Previous child: SemanticsNode#4(STALE, owner: null, merged up ⬆️, Rect.fromLTRB(5.0, 5.0, 10.0, 10.0))\n'
' New child: SemanticsNode#6(STALE, owner: null, merged up ⬆️, Rect.fromLTRB(0.0, 0.0, 20.0, 20.0))\n'
'\n'
' Child node at position 1 was replaced:\n'
' Previous child: SemanticsNode#5(STALE, owner: null, merged up ⬆️, Rect.fromLTRB(10.0, 10.0, 20.0, 20.0))\n'
' New child: SemanticsNode#7(STALE, owner: null, merged up ⬆️, Rect.fromLTRB(40.0, 14.0, 60.0, 60.0))\n',
));
expect(
error.diagnostics.singleWhere((DiagnosticsNode node) => node.level == DiagnosticLevel.hint).toString(),
'Instead of mutating the existing list, create a new list containing the desired `SemanticsNode`s.',
);
// Two previous children and two new children.
expect(error.diagnostics.where((DiagnosticsNode node) => node.value is SemanticsNode).length, 4);
}
});
test('after markNeedsSemanticsUpdate() all render objects between two semantic boundaries are asked for annotations', () {
final SemanticsHandle handle = TestRenderingFlutterBinding.instance.ensureSemantics();
addTearDown(handle.dispose);
TestRender middle;
final TestRender root = TestRender(
hasTapAction: true,
isSemanticBoundary: true,
child: TestRender(
hasLongPressAction: true,
child: middle = TestRender(
hasScrollLeftAction: true,
child: TestRender(
hasScrollRightAction: true,
child: TestRender(
hasScrollUpAction: true,
isSemanticBoundary: true,
),
),
),
),
);
layout(root);
pumpFrame(phase: EnginePhase.flushSemantics);
int expectedActions = SemanticsAction.tap.index | SemanticsAction.longPress.index | SemanticsAction.scrollLeft.index | SemanticsAction.scrollRight.index;
expect(root.debugSemantics!.getSemanticsData().actions, expectedActions);
middle
..hasScrollLeftAction = false
..hasScrollDownAction = true;
middle.markNeedsSemanticsUpdate();
pumpFrame(phase: EnginePhase.flushSemantics);
expectedActions = SemanticsAction.tap.index | SemanticsAction.longPress.index | SemanticsAction.scrollDown.index | SemanticsAction.scrollRight.index;
expect(root.debugSemantics!.getSemanticsData().actions, expectedActions);
});
});
test('toStringDeep() does not throw with transform == null', () {
final SemanticsNode child1 = SemanticsNode()
..rect = const Rect.fromLTRB(0.0, 0.0, 5.0, 5.0);
final SemanticsNode child2 = SemanticsNode()
..rect = const Rect.fromLTRB(5.0, 0.0, 10.0, 5.0);
final SemanticsNode root = SemanticsNode()
..rect = const Rect.fromLTRB(0.0, 0.0, 10.0, 5.0);
root.updateWith(
config: null,
childrenInInversePaintOrder: <SemanticsNode>[child1, child2],
);
expect(root.transform, isNull);
expect(child1.transform, isNull);
expect(child2.transform, isNull);
expect(
root.toStringDeep(),
'SemanticsNode#3\n'
' │ STALE\n'
' │ owner: null\n'
' │ Rect.fromLTRB(0.0, 0.0, 10.0, 5.0)\n'
' │\n'
' ├─SemanticsNode#1\n'
' │ STALE\n'
' │ owner: null\n'
' │ Rect.fromLTRB(0.0, 0.0, 5.0, 5.0)\n'
' │\n'
' └─SemanticsNode#2\n'
' STALE\n'
' owner: null\n'
' Rect.fromLTRB(5.0, 0.0, 10.0, 5.0)\n',
);
});
test('Incompatible OrdinalSortKey throw AssertionError when compared', () {
// Different types.
expect(() {
const OrdinalSortKey(0.0).compareTo(const CustomSortKey(0.0));
}, throwsAssertionError);
});
test('OrdinalSortKey compares correctly when names are the same', () {
const List<List<SemanticsSortKey>> tests = <List<SemanticsSortKey>>[
<SemanticsSortKey>[OrdinalSortKey(0.0), OrdinalSortKey(0.0)],
<SemanticsSortKey>[OrdinalSortKey(0.0), OrdinalSortKey(1.0)],
<SemanticsSortKey>[OrdinalSortKey(1.0), OrdinalSortKey(0.0)],
<SemanticsSortKey>[OrdinalSortKey(1.0), OrdinalSortKey(1.0)],
<SemanticsSortKey>[OrdinalSortKey(0.0, name: 'a'), OrdinalSortKey(0.0, name: 'a')],
<SemanticsSortKey>[OrdinalSortKey(0.0, name: 'a'), OrdinalSortKey(1.0, name: 'a')],
<SemanticsSortKey>[OrdinalSortKey(1.0, name: 'a'), OrdinalSortKey(0.0, name: 'a')],
<SemanticsSortKey>[OrdinalSortKey(1.0, name: 'a'), OrdinalSortKey(1.0, name: 'a')],
];
final List<int> expectedResults = <int>[0, -1, 1, 0, 0, -1, 1, 0];
assert(tests.length == expectedResults.length);
final List<int> results = <int>[
for (final List<SemanticsSortKey> tuple in tests) tuple[0].compareTo(tuple[1]),
];
expect(results, orderedEquals(expectedResults));
// Differing types should throw an assertion.
expect(() => const OrdinalSortKey(0.0).compareTo(const CustomSortKey(0.0)), throwsAssertionError);
});
test('OrdinalSortKey compares correctly when the names are different', () {
const List<List<SemanticsSortKey>> tests = <List<SemanticsSortKey>>[
<SemanticsSortKey>[OrdinalSortKey(0.0), OrdinalSortKey(0.0, name: 'bar')],
<SemanticsSortKey>[OrdinalSortKey(0.0), OrdinalSortKey(1.0, name: 'bar')],
<SemanticsSortKey>[OrdinalSortKey(1.0), OrdinalSortKey(0.0, name: 'bar')],
<SemanticsSortKey>[OrdinalSortKey(1.0), OrdinalSortKey(1.0, name: 'bar')],
<SemanticsSortKey>[OrdinalSortKey(0.0, name: 'foo'), OrdinalSortKey(0.0)],
<SemanticsSortKey>[OrdinalSortKey(0.0, name: 'foo'), OrdinalSortKey(1.0)],
<SemanticsSortKey>[OrdinalSortKey(1.0, name: 'foo'), OrdinalSortKey(0.0)],
<SemanticsSortKey>[OrdinalSortKey(1.0, name: 'foo'), OrdinalSortKey(1.0)],
<SemanticsSortKey>[OrdinalSortKey(0.0, name: 'foo'), OrdinalSortKey(0.0, name: 'bar')],
<SemanticsSortKey>[OrdinalSortKey(0.0, name: 'foo'), OrdinalSortKey(1.0, name: 'bar')],
<SemanticsSortKey>[OrdinalSortKey(1.0, name: 'foo'), OrdinalSortKey(0.0, name: 'bar')],
<SemanticsSortKey>[OrdinalSortKey(1.0, name: 'foo'), OrdinalSortKey(1.0, name: 'bar')],
<SemanticsSortKey>[OrdinalSortKey(0.0, name: 'bar'), OrdinalSortKey(0.0, name: 'foo')],
<SemanticsSortKey>[OrdinalSortKey(0.0, name: 'bar'), OrdinalSortKey(1.0, name: 'foo')],
<SemanticsSortKey>[OrdinalSortKey(1.0, name: 'bar'), OrdinalSortKey(0.0, name: 'foo')],
<SemanticsSortKey>[OrdinalSortKey(1.0, name: 'bar'), OrdinalSortKey(1.0, name: 'foo')],
];
final List<int> expectedResults = <int>[ -1, -1, -1, -1, 1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1];
assert(tests.length == expectedResults.length);
final List<int> results = <int>[
for (final List<SemanticsSortKey> tuple in tests) tuple[0].compareTo(tuple[1]),
];
expect(results, orderedEquals(expectedResults));
});
test('toStringDeep respects childOrder parameter', () {
final SemanticsNode child1 = SemanticsNode()
..rect = const Rect.fromLTRB(15.0, 0.0, 20.0, 5.0);
final SemanticsNode child2 = SemanticsNode()
..rect = const Rect.fromLTRB(10.0, 0.0, 15.0, 5.0);
final SemanticsNode root = SemanticsNode()
..rect = const Rect.fromLTRB(0.0, 0.0, 20.0, 5.0);
root.updateWith(
config: null,
childrenInInversePaintOrder: <SemanticsNode>[child1, child2],
);
expect(
root.toStringDeep(),
'SemanticsNode#3\n'
' │ STALE\n'
' │ owner: null\n'
' │ Rect.fromLTRB(0.0, 0.0, 20.0, 5.0)\n'
' │\n'
' ├─SemanticsNode#1\n'
' │ STALE\n'
' │ owner: null\n'
' │ Rect.fromLTRB(15.0, 0.0, 20.0, 5.0)\n'
' │\n'
' └─SemanticsNode#2\n'
' STALE\n'
' owner: null\n'
' Rect.fromLTRB(10.0, 0.0, 15.0, 5.0)\n',
);
expect(
root.toStringDeep(childOrder: DebugSemanticsDumpOrder.inverseHitTest),
'SemanticsNode#3\n'
' │ STALE\n'
' │ owner: null\n'
' │ Rect.fromLTRB(0.0, 0.0, 20.0, 5.0)\n'
' │\n'
' ├─SemanticsNode#1\n'
' │ STALE\n'
' │ owner: null\n'
' │ Rect.fromLTRB(15.0, 0.0, 20.0, 5.0)\n'
' │\n'
' └─SemanticsNode#2\n'
' STALE\n'
' owner: null\n'
' Rect.fromLTRB(10.0, 0.0, 15.0, 5.0)\n',
);
final SemanticsNode child3 = SemanticsNode()
..rect = const Rect.fromLTRB(0.0, 0.0, 10.0, 5.0);
child3.updateWith(
config: null,
childrenInInversePaintOrder: <SemanticsNode>[
SemanticsNode()
..rect = const Rect.fromLTRB(5.0, 0.0, 10.0, 5.0),
SemanticsNode()
..rect = const Rect.fromLTRB(0.0, 0.0, 5.0, 5.0),
],
);
final SemanticsNode rootComplex = SemanticsNode()
..rect = const Rect.fromLTRB(0.0, 0.0, 25.0, 5.0);
rootComplex.updateWith(
config: null,
childrenInInversePaintOrder: <SemanticsNode>[child1, child2, child3],
);
expect(
rootComplex.toStringDeep(),
'SemanticsNode#7\n'
' │ STALE\n'
' │ owner: null\n'
' │ Rect.fromLTRB(0.0, 0.0, 25.0, 5.0)\n'
' │\n'
' ├─SemanticsNode#1\n'
' │ STALE\n'
' │ owner: null\n'
' │ Rect.fromLTRB(15.0, 0.0, 20.0, 5.0)\n'
' │\n'
' ├─SemanticsNode#2\n'
' │ STALE\n'
' │ owner: null\n'
' │ Rect.fromLTRB(10.0, 0.0, 15.0, 5.0)\n'
' │\n'
' └─SemanticsNode#4\n'
' │ STALE\n'
' │ owner: null\n'
' │ Rect.fromLTRB(0.0, 0.0, 10.0, 5.0)\n'
' │\n'
' ├─SemanticsNode#5\n'
' │ STALE\n'
' │ owner: null\n'
' │ Rect.fromLTRB(5.0, 0.0, 10.0, 5.0)\n'
' │\n'
' └─SemanticsNode#6\n'
' STALE\n'
' owner: null\n'
' Rect.fromLTRB(0.0, 0.0, 5.0, 5.0)\n',
);
expect(
rootComplex.toStringDeep(childOrder: DebugSemanticsDumpOrder.inverseHitTest),
'SemanticsNode#7\n'
' │ STALE\n'
' │ owner: null\n'
' │ Rect.fromLTRB(0.0, 0.0, 25.0, 5.0)\n'
' │\n'
' ├─SemanticsNode#1\n'
' │ STALE\n'
' │ owner: null\n'
' │ Rect.fromLTRB(15.0, 0.0, 20.0, 5.0)\n'
' │\n'
' ├─SemanticsNode#2\n'
' │ STALE\n'
' │ owner: null\n'
' │ Rect.fromLTRB(10.0, 0.0, 15.0, 5.0)\n'
' │\n'
' └─SemanticsNode#4\n'
' │ STALE\n'
' │ owner: null\n'
' │ Rect.fromLTRB(0.0, 0.0, 10.0, 5.0)\n'
' │\n'
' ├─SemanticsNode#5\n'
' │ STALE\n'
' │ owner: null\n'
' │ Rect.fromLTRB(5.0, 0.0, 10.0, 5.0)\n'
' │\n'
' └─SemanticsNode#6\n'
' STALE\n'
' owner: null\n'
' Rect.fromLTRB(0.0, 0.0, 5.0, 5.0)\n',
);
});
test('debug properties', () {
final SemanticsNode minimalProperties = SemanticsNode();
expect(
minimalProperties.toStringDeep(),
'SemanticsNode#1\n'
' Rect.fromLTRB(0.0, 0.0, 0.0, 0.0)\n'
' invisible\n',
);
expect(
minimalProperties.toStringDeep(minLevel: DiagnosticLevel.hidden),
'SemanticsNode#1\n'
' owner: null\n'
' isMergedIntoParent: false\n'
' mergeAllDescendantsIntoThisNode: false\n'
' Rect.fromLTRB(0.0, 0.0, 0.0, 0.0)\n'
' tags: null\n'
' actions: []\n'
' customActions: []\n'
' flags: []\n'
' invisible\n'
' isHidden: false\n'
' identifier: ""\n'
' label: ""\n'
' value: ""\n'
' increasedValue: ""\n'
' decreasedValue: ""\n'
' hint: ""\n'
' tooltip: ""\n'
' textDirection: null\n'
' sortKey: null\n'
' platformViewId: null\n'
' maxValueLength: null\n'
' currentValueLength: null\n'
' scrollChildren: null\n'
' scrollIndex: null\n'
' scrollExtentMin: null\n'
' scrollPosition: null\n'
' scrollExtentMax: null\n'
' indexInParent: null\n'
' elevation: 0.0\n'
' thickness: 0.0\n',
);
final SemanticsConfiguration config = SemanticsConfiguration()
..isSemanticBoundary = true
..isMergingSemanticsOfDescendants = true
..onScrollUp = () { }
..onLongPress = () { }
..onShowOnScreen = () { }
..isChecked = false
..isSelected = true
..isButton = true
..label = 'Use all the properties'
..textDirection = TextDirection.rtl
..sortKey = const OrdinalSortKey(1.0);
final SemanticsNode allProperties = SemanticsNode()
..rect = const Rect.fromLTWH(50.0, 10.0, 20.0, 30.0)
..transform = Matrix4.translation(Vector3(10.0, 10.0, 0.0))
..updateWith(config: config);
expect(
allProperties.toStringDeep(),
equalsIgnoringHashCodes(
'SemanticsNode#2\n'
' STALE\n'
' owner: null\n'
' merge boundary ⛔️\n'
' Rect.fromLTRB(60.0, 20.0, 80.0, 50.0)\n'
' actions: longPress, scrollUp, showOnScreen\n'
' flags: hasCheckedState, isSelected, isButton\n'
' label: "Use all the properties"\n'
' textDirection: rtl\n'
' sortKey: OrdinalSortKey#19df5(order: 1.0)\n',
),
);
expect(
allProperties.getSemanticsData().toString(),
'SemanticsData(Rect.fromLTRB(50.0, 10.0, 70.0, 40.0), [1.0,0.0,0.0,10.0; 0.0,1.0,0.0,10.0; 0.0,0.0,1.0,0.0; 0.0,0.0,0.0,1.0], actions: [longPress, scrollUp, showOnScreen], flags: [hasCheckedState, isSelected, isButton], label: "Use all the properties", textDirection: rtl)',
);
final SemanticsNode scaled = SemanticsNode()
..rect = const Rect.fromLTWH(50.0, 10.0, 20.0, 30.0)
..transform = Matrix4.diagonal3(Vector3(10.0, 10.0, 1.0));
expect(
scaled.toStringDeep(),
'SemanticsNode#3\n'
' STALE\n'
' owner: null\n'
' Rect.fromLTRB(50.0, 10.0, 70.0, 40.0) scaled by 10.0x\n',
);
expect(
scaled.getSemanticsData().toString(),
'SemanticsData(Rect.fromLTRB(50.0, 10.0, 70.0, 40.0), [10.0,0.0,0.0,0.0; 0.0,10.0,0.0,0.0; 0.0,0.0,1.0,0.0; 0.0,0.0,0.0,1.0])',
);
});
test('blocked actions debug properties', () {
final SemanticsConfiguration config = SemanticsConfiguration()
..isBlockingUserActions = true
..onScrollUp = () { }
..onLongPress = () { }
..onShowOnScreen = () { }
..onDidGainAccessibilityFocus = () { };
final SemanticsNode blocked = SemanticsNode()
..rect = const Rect.fromLTWH(50.0, 10.0, 20.0, 30.0)
..transform = Matrix4.translation(Vector3(10.0, 10.0, 0.0))
..updateWith(config: config);
expect(
blocked.toStringDeep(),
equalsIgnoringHashCodes(
'SemanticsNode#1\n'
' STALE\n'
' owner: null\n'
' Rect.fromLTRB(60.0, 20.0, 80.0, 50.0)\n'
' actions: didGainAccessibilityFocus, longPress🚫️, scrollUp🚫️,\n'
' showOnScreen🚫️\n',
),
);
});
test('Custom actions debug properties', () {
final SemanticsConfiguration configuration = SemanticsConfiguration();
const CustomSemanticsAction action1 = CustomSemanticsAction(label: 'action1');
const CustomSemanticsAction action2 = CustomSemanticsAction(label: 'action2');
const CustomSemanticsAction action3 = CustomSemanticsAction(label: 'action3');
configuration.customSemanticsActions = <CustomSemanticsAction, VoidCallback>{
action1: () { },
action2: () { },
action3: () { },
};
final SemanticsNode actionNode = SemanticsNode();
actionNode.updateWith(config: configuration);
expect(
actionNode.toStringDeep(minLevel: DiagnosticLevel.hidden),
'SemanticsNode#1\n'
' STALE\n'
' owner: null\n'
' isMergedIntoParent: false\n'
' mergeAllDescendantsIntoThisNode: false\n'
' Rect.fromLTRB(0.0, 0.0, 0.0, 0.0)\n'
' tags: null\n'
' actions: customAction\n'
' customActions: action1, action2, action3\n'
' flags: []\n'
' invisible\n'
' isHidden: false\n'
' identifier: ""\n'
' label: ""\n'
' value: ""\n'
' increasedValue: ""\n'
' decreasedValue: ""\n'
' hint: ""\n'
' tooltip: ""\n'
' textDirection: null\n'
' sortKey: null\n'
' platformViewId: null\n'
' maxValueLength: null\n'
' currentValueLength: null\n'
' scrollChildren: null\n'
' scrollIndex: null\n'
' scrollExtentMin: null\n'
' scrollPosition: null\n'
' scrollExtentMax: null\n'
' indexInParent: null\n'
' elevation: 0.0\n'
' thickness: 0.0\n',
);
});
test('Attributed String can concat', () {
final AttributedString string1 = AttributedString(
'string1',
attributes: <StringAttribute>[
SpellOutStringAttribute(range: const TextRange(start:0, end:4)),
]
);
final AttributedString string2 = AttributedString(
'string2',
attributes: <StringAttribute>[
LocaleStringAttribute(locale: const Locale('es', 'MX'), range: const TextRange(start:0, end:4)),
]
);
final AttributedString result = string1 + string2;
expect(result.string, 'string1string2');
expect(result.attributes.length, 2);
expect(result.attributes[0].range, const TextRange(start:0, end:4));
expect(result.attributes[0] is SpellOutStringAttribute, isTrue);
expect(result.toString(), "AttributedString('string1string2', attributes: [SpellOutStringAttribute(TextRange(start: 0, end: 4)), LocaleStringAttribute(TextRange(start: 7, end: 11), es-MX)])");
});
test('Semantics id does not repeat', () {
final SemanticsOwner owner = SemanticsOwner(
onSemanticsUpdate: (SemanticsUpdate update) {},
);
const int expectId = 1400;
SemanticsNode? nodeToRemove;
for (int i = 0; i < kMaxFrameworkAccessibilityIdentifier; i++) {
final SemanticsNode node = SemanticsNode();
node.attach(owner);
if (node.id == expectId) {
nodeToRemove = node;
}
}
nodeToRemove!.detach();
final SemanticsNode newNode = SemanticsNode();
newNode.attach(owner);
// Id is reused.
expect(newNode.id, expectId);
});
test('Tags show up in debug properties', () {
final SemanticsNode actionNode = SemanticsNode()
..tags = <SemanticsTag>{RenderViewport.useTwoPaneSemantics};
expect(
actionNode.toStringDeep(),
contains('\n tags: RenderViewport.twoPane\n'),
);
});
test('SemanticsConfiguration getter/setter', () {
final SemanticsConfiguration config = SemanticsConfiguration();
const CustomSemanticsAction customAction = CustomSemanticsAction(label: 'test');
expect(config.isSemanticBoundary, isFalse);
expect(config.isButton, isFalse);
expect(config.isLink, isFalse);
expect(config.isMergingSemanticsOfDescendants, isFalse);
expect(config.isEnabled, null);
expect(config.isChecked, null);
expect(config.isSelected, isFalse);
expect(config.isBlockingSemanticsOfPreviouslyPaintedNodes, isFalse);
expect(config.isFocused, isFalse);
expect(config.isTextField, isFalse);
expect(config.onShowOnScreen, isNull);
expect(config.onScrollDown, isNull);
expect(config.onScrollUp, isNull);
expect(config.onScrollLeft, isNull);
expect(config.onScrollRight, isNull);
expect(config.onLongPress, isNull);
expect(config.onDecrease, isNull);
expect(config.onIncrease, isNull);
expect(config.onMoveCursorForwardByCharacter, isNull);
expect(config.onMoveCursorBackwardByCharacter, isNull);
expect(config.onTap, isNull);
expect(config.customSemanticsActions[customAction], isNull);
config.isSemanticBoundary = true;
config.isButton = true;
config.isLink = true;
config.isMergingSemanticsOfDescendants = true;
config.isEnabled = true;
config.isChecked = true;
config.isSelected = true;
config.isBlockingSemanticsOfPreviouslyPaintedNodes = true;
config.isFocused = true;
config.isTextField = true;
void onShowOnScreen() { }
void onScrollDown() { }
void onScrollUp() { }
void onScrollLeft() { }
void onScrollRight() { }
void onLongPress() { }
void onDecrease() { }
void onIncrease() { }
void onMoveCursorForwardByCharacter(bool _) { }
void onMoveCursorBackwardByCharacter(bool _) { }
void onTap() { }
void onCustomAction() { }
config.onShowOnScreen = onShowOnScreen;
config.onScrollDown = onScrollDown;
config.onScrollUp = onScrollUp;
config.onScrollLeft = onScrollLeft;
config.onScrollRight = onScrollRight;
config.onLongPress = onLongPress;
config.onDecrease = onDecrease;
config.onIncrease = onIncrease;
config.onMoveCursorForwardByCharacter = onMoveCursorForwardByCharacter;
config.onMoveCursorBackwardByCharacter = onMoveCursorBackwardByCharacter;
config.onTap = onTap;
config.customSemanticsActions[customAction] = onCustomAction;
expect(config.isSemanticBoundary, isTrue);
expect(config.isButton, isTrue);
expect(config.isLink, isTrue);
expect(config.isMergingSemanticsOfDescendants, isTrue);
expect(config.isEnabled, isTrue);
expect(config.isChecked, isTrue);
expect(config.isSelected, isTrue);
expect(config.isBlockingSemanticsOfPreviouslyPaintedNodes, isTrue);
expect(config.isFocused, isTrue);
expect(config.isTextField, isTrue);
expect(config.onShowOnScreen, same(onShowOnScreen));
expect(config.onScrollDown, same(onScrollDown));
expect(config.onScrollUp, same(onScrollUp));
expect(config.onScrollLeft, same(onScrollLeft));
expect(config.onScrollRight, same(onScrollRight));
expect(config.onLongPress, same(onLongPress));
expect(config.onDecrease, same(onDecrease));
expect(config.onIncrease, same(onIncrease));
expect(config.onMoveCursorForwardByCharacter, same(onMoveCursorForwardByCharacter));
expect(config.onMoveCursorBackwardByCharacter, same(onMoveCursorBackwardByCharacter));
expect(config.onTap, same(onTap));
expect(config.customSemanticsActions[customAction], same(onCustomAction));
});
test('SemanticsOwner dispatches memory events', () async {
await expectLater(
await memoryEvents(() => SemanticsOwner(
onSemanticsUpdate: (SemanticsUpdate update) {},
).dispose(), SemanticsOwner),
areCreateAndDispose,
);
});
test('SemanticsNode.indexInParent appears in string output', () async {
final SemanticsNode node = SemanticsNode()..indexInParent = 10;
expect(node.toString(), contains('indexInParent: 10'));
});
}
class TestRender extends RenderProxyBox {
TestRender({
this.hasTapAction = false,
this.hasLongPressAction = false,
this.hasScrollLeftAction = false,
this.hasScrollRightAction = false,
this.hasScrollUpAction = false,
this.hasScrollDownAction = false,
this.isSemanticBoundary = false,
RenderBox? child,
}) : super(child);
bool hasTapAction;
bool hasLongPressAction;
bool hasScrollLeftAction;
bool hasScrollRightAction;
bool hasScrollUpAction;
bool hasScrollDownAction;
bool isSemanticBoundary;
@override
void describeSemanticsConfiguration(SemanticsConfiguration config) {
super.describeSemanticsConfiguration(config);
config.isSemanticBoundary = isSemanticBoundary;
if (hasTapAction) {
config.onTap = () { };
}
if (hasLongPressAction) {
config.onLongPress = () { };
}
if (hasScrollLeftAction) {
config.onScrollLeft = () { };
}
if (hasScrollRightAction) {
config.onScrollRight = () { };
}
if (hasScrollUpAction) {
config.onScrollUp = () { };
}
if (hasScrollDownAction) {
config.onScrollDown = () { };
}
}
}
class CustomSortKey extends OrdinalSortKey {
const CustomSortKey(super.order, {super.name});
}
| flutter/packages/flutter/test/semantics/semantics_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/semantics/semantics_test.dart",
"repo_id": "flutter",
"token_count": 17427
} | 857 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('Haptic feedback control test', () async {
final List<MethodCall> log = <MethodCall>[];
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async {
log.add(methodCall);
return null;
});
await HapticFeedback.vibrate();
expect(log, hasLength(1));
expect(log.single, isMethodCall('HapticFeedback.vibrate', arguments: null));
});
test('Haptic feedback variation tests', () async {
Future<void> callAndVerifyHapticFunction(Future<void> Function() hapticFunction, String platformMethodArgument) async {
final List<MethodCall> log = <MethodCall>[];
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, (MethodCall methodCall) async {
log.add(methodCall);
return null;
});
await hapticFunction();
expect(log, hasLength(1));
expect(
log.last,
isMethodCall('HapticFeedback.vibrate', arguments: platformMethodArgument),
);
}
await callAndVerifyHapticFunction(HapticFeedback.lightImpact, 'HapticFeedbackType.lightImpact');
await callAndVerifyHapticFunction(HapticFeedback.mediumImpact, 'HapticFeedbackType.mediumImpact');
await callAndVerifyHapticFunction(HapticFeedback.heavyImpact, 'HapticFeedbackType.heavyImpact');
await callAndVerifyHapticFunction(HapticFeedback.selectionClick, 'HapticFeedbackType.selectionClick');
});
}
| flutter/packages/flutter/test/services/haptic_feedback_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/services/haptic_feedback_test.dart",
"repo_id": "flutter",
"token_count": 614
} | 858 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
import 'restoration.dart';
void main() {
testWidgets('$RestorationManager dispatches memory events', (WidgetTester tester) async {
await expectLater(
await memoryEvents(() => RestorationManager().dispose(), RestorationManager),
areCreateAndDispose,
);
});
group('RestorationManager', () {
testWidgets('root bucket retrieval', (WidgetTester tester) async {
final List<MethodCall> callsToEngine = <MethodCall>[];
final Completer<Map<dynamic, dynamic>> result = Completer<Map<dynamic, dynamic>>();
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, (MethodCall call) {
callsToEngine.add(call);
return result.future;
});
final RestorationManager manager = RestorationManager();
addTearDown(manager.dispose);
final Future<RestorationBucket?> rootBucketFuture = manager.rootBucket;
RestorationBucket? rootBucket;
rootBucketFuture.then((RestorationBucket? bucket) {
rootBucket = bucket;
});
expect(rootBucketFuture, isNotNull);
expect(rootBucket, isNull);
// Accessing rootBucket again gives same future.
expect(manager.rootBucket, same(rootBucketFuture));
// Engine has only been contacted once.
expect(callsToEngine, hasLength(1));
expect(callsToEngine.single.method, 'get');
// Complete the engine request.
result.complete(_createEncodedRestorationData1());
await tester.pump();
// Root bucket future completed.
expect(rootBucket, isNotNull);
// Root bucket contains the expected data.
expect(rootBucket!.read<int>('value1'), 10);
expect(rootBucket!.read<String>('value2'), 'Hello');
final RestorationBucket child = rootBucket!.claimChild('child1', debugOwner: null);
addTearDown(child.dispose);
expect(child.read<int>('another value'), 22);
// Accessing the root bucket again completes synchronously with same bucket.
RestorationBucket? synchronousBucket;
manager.rootBucket.then((RestorationBucket? bucket) {
synchronousBucket = bucket;
});
expect(synchronousBucket, isNotNull);
expect(synchronousBucket, same(rootBucket));
});
testWidgets('root bucket received from engine before retrieval', (WidgetTester tester) async {
SystemChannels.restoration.setMethodCallHandler(null);
final List<MethodCall> callsToEngine = <MethodCall>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, (MethodCall call) async {
callsToEngine.add(call);
return null;
});
final RestorationManager manager = RestorationManager();
addTearDown(manager.dispose);
await _pushDataFromEngine(_createEncodedRestorationData1());
RestorationBucket? rootBucket;
manager.rootBucket.then((RestorationBucket? bucket) => rootBucket = bucket);
// Root bucket is available synchronously.
expect(rootBucket, isNotNull);
// Engine was never asked.
expect(callsToEngine, isEmpty);
});
testWidgets('root bucket received while engine retrieval is pending', (WidgetTester tester) async {
SystemChannels.restoration.setMethodCallHandler(null);
final List<MethodCall> callsToEngine = <MethodCall>[];
final Completer<Map<dynamic, dynamic>> result = Completer<Map<dynamic, dynamic>>();
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, (MethodCall call) {
callsToEngine.add(call);
return result.future;
});
final RestorationManager manager = RestorationManager();
addTearDown(manager.dispose);
RestorationBucket? rootBucket;
manager.rootBucket.then((RestorationBucket? bucket) => rootBucket = bucket);
expect(rootBucket, isNull);
expect(callsToEngine.single.method, 'get');
await _pushDataFromEngine(_createEncodedRestorationData1());
expect(rootBucket, isNotNull);
expect(rootBucket!.read<int>('value1'), 10);
result.complete(_createEncodedRestorationData2());
await tester.pump();
RestorationBucket? rootBucket2;
manager.rootBucket.then((RestorationBucket? bucket) => rootBucket2 = bucket);
expect(rootBucket2, isNotNull);
expect(rootBucket2, same(rootBucket));
expect(rootBucket2!.read<int>('value1'), 10);
expect(rootBucket2!.contains('foo'), isFalse);
});
testWidgets('root bucket is properly replaced when new data is available', (WidgetTester tester) async {
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, (MethodCall call) async {
return _createEncodedRestorationData1();
});
final RestorationManager manager = RestorationManager();
addTearDown(manager.dispose);
RestorationBucket? rootBucket;
manager.rootBucket.then((RestorationBucket? bucket) {
rootBucket = bucket;
});
await tester.pump();
expect(rootBucket, isNotNull);
expect(rootBucket!.read<int>('value1'), 10);
final RestorationBucket child = rootBucket!.claimChild('child1', debugOwner: null);
expect(child.read<int>('another value'), 22);
bool rootReplaced = false;
RestorationBucket? newRoot;
manager.addListener(() {
rootReplaced = true;
manager.rootBucket.then((RestorationBucket? bucket) {
newRoot = bucket;
});
// The new bucket is available synchronously.
expect(newRoot, isNotNull);
});
// Send new Data.
await _pushDataFromEngine(_createEncodedRestorationData2());
expect(rootReplaced, isTrue);
expect(newRoot, isNot(same(rootBucket)));
child.dispose();
expect(newRoot!.read<int>('foo'), 33);
expect(newRoot!.read<int>('value1'), null);
final RestorationBucket newChild = newRoot!.claimChild('childFoo', debugOwner: null);
addTearDown(newChild.dispose);
expect(newChild.read<String>('bar'), 'Hello');
});
testWidgets('returns null as root bucket when restoration is disabled', (WidgetTester tester) async {
final List<MethodCall> callsToEngine = <MethodCall>[];
final Completer<Map<dynamic, dynamic>> result = Completer<Map<dynamic, dynamic>>();
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, (MethodCall call) {
callsToEngine.add(call);
return result.future;
});
int listenerCount = 0;
final RestorationManager manager = RestorationManager()..addListener(() {
listenerCount++;
});
addTearDown(manager.dispose);
RestorationBucket? rootBucket;
bool rootBucketResolved = false;
manager.rootBucket.then((RestorationBucket? bucket) {
rootBucketResolved = true;
rootBucket = bucket;
});
await tester.pump();
expect(rootBucketResolved, isFalse);
expect(listenerCount, 0);
result.complete(_packageRestorationData(enabled: false));
await tester.pump();
expect(rootBucketResolved, isTrue);
expect(rootBucket, isNull);
// Switch to non-null.
await _pushDataFromEngine(_createEncodedRestorationData1());
expect(listenerCount, 1);
manager.rootBucket.then((RestorationBucket? bucket) {
rootBucket = bucket;
});
expect(rootBucket, isNotNull);
// Switch to null again.
await _pushDataFromEngine(_packageRestorationData(enabled: false));
expect(listenerCount, 2);
manager.rootBucket.then((RestorationBucket? bucket) {
rootBucket = bucket;
});
expect(rootBucket, isNull);
});
testWidgets('flushData', (WidgetTester tester) async {
final List<MethodCall> callsToEngine = <MethodCall>[];
final Completer<Map<dynamic, dynamic>> result = Completer<Map<dynamic, dynamic>>();
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, (MethodCall call) {
callsToEngine.add(call);
return result.future;
});
final RestorationManager manager = RestorationManager();
addTearDown(manager.dispose);
final Future<RestorationBucket?> rootBucketFuture = manager.rootBucket;
RestorationBucket? rootBucket;
rootBucketFuture.then((RestorationBucket? bucket) {
rootBucket = bucket;
});
result.complete(_createEncodedRestorationData1());
await tester.pump();
expect(rootBucket, isNotNull);
callsToEngine.clear();
// Schedule a frame.
SchedulerBinding.instance.ensureVisualUpdate();
rootBucket!.write('foo', 1);
// flushData is no-op because frame is scheduled.
manager.flushData();
expect(callsToEngine, isEmpty);
// Data is flushed at the end of the frame.
await tester.pump();
expect(callsToEngine, hasLength(1));
callsToEngine.clear();
// flushData without frame sends data directly.
rootBucket!.write('foo', 2);
manager.flushData();
expect(callsToEngine, hasLength(1));
});
testWidgets('isReplacing', (WidgetTester tester) async {
final Completer<Map<dynamic, dynamic>> result = Completer<Map<dynamic, dynamic>>();
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.restoration, (MethodCall call) {
return result.future;
});
final TestRestorationManager manager = TestRestorationManager();
addTearDown(manager.dispose);
expect(manager.isReplacing, isFalse);
RestorationBucket? rootBucket;
manager.rootBucket.then((RestorationBucket? bucket) {
rootBucket = bucket;
});
result.complete(_createEncodedRestorationData1());
await tester.idle();
expect(rootBucket, isNotNull);
expect(rootBucket!.isReplacing, isFalse);
expect(manager.isReplacing, isFalse);
tester.binding.scheduleFrame();
await tester.pump();
expect(manager.isReplacing, isFalse);
expect(rootBucket!.isReplacing, isFalse);
manager.receiveDataFromEngine(enabled: true, data: null);
RestorationBucket? rootBucket2;
manager.rootBucket.then((RestorationBucket? bucket) {
rootBucket2 = bucket;
});
expect(rootBucket2, isNotNull);
expect(rootBucket2, isNot(same(rootBucket)));
expect(manager.isReplacing, isTrue);
expect(rootBucket2!.isReplacing, isTrue);
await tester.idle();
expect(manager.isReplacing, isTrue);
expect(rootBucket2!.isReplacing, isTrue);
tester.binding.scheduleFrame();
await tester.pump();
expect(manager.isReplacing, isFalse);
expect(rootBucket2!.isReplacing, isFalse);
manager.receiveDataFromEngine(enabled: false, data: null);
RestorationBucket? rootBucket3;
manager.rootBucket.then((RestorationBucket? bucket) {
rootBucket3 = bucket;
});
expect(rootBucket3, isNull);
expect(manager.isReplacing, isFalse);
await tester.idle();
expect(manager.isReplacing, isFalse);
tester.binding.scheduleFrame();
await tester.pump();
expect(manager.isReplacing, isFalse);
});
});
test('debugIsSerializableForRestoration', () {
expect(debugIsSerializableForRestoration(Object()), isFalse);
expect(debugIsSerializableForRestoration(Container()), isFalse);
expect(debugIsSerializableForRestoration(null), isTrue);
expect(debugIsSerializableForRestoration(147823), isTrue);
expect(debugIsSerializableForRestoration(12.43), isTrue);
expect(debugIsSerializableForRestoration('Hello World'), isTrue);
expect(debugIsSerializableForRestoration(<int>[12, 13, 14]), isTrue);
expect(debugIsSerializableForRestoration(<String, int>{'v1' : 10, 'v2' : 23}), isTrue);
expect(debugIsSerializableForRestoration(<String, dynamic>{
'hello': <int>[12, 12, 12],
'world': <int, bool>{
1: true,
2: false,
4: true,
},
}), isTrue);
});
}
Future<void> _pushDataFromEngine(Map<dynamic, dynamic> data) async {
await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage(
'flutter/restoration',
const StandardMethodCodec().encodeMethodCall(MethodCall('push', data)),
(_) { },
);
}
Map<dynamic, dynamic> _createEncodedRestorationData1() {
final Map<String, dynamic> data = <String, dynamic>{
valuesMapKey: <String, dynamic>{
'value1' : 10,
'value2' : 'Hello',
},
childrenMapKey: <String, dynamic>{
'child1' : <String, dynamic>{
valuesMapKey : <String, dynamic>{
'another value': 22,
},
},
},
};
return _packageRestorationData(data: data);
}
Map<dynamic, dynamic> _createEncodedRestorationData2() {
final Map<String, dynamic> data = <String, dynamic>{
valuesMapKey: <String, dynamic>{
'foo' : 33,
},
childrenMapKey: <String, dynamic>{
'childFoo' : <String, dynamic>{
valuesMapKey : <String, dynamic>{
'bar': 'Hello',
},
},
},
};
return _packageRestorationData(data: data);
}
Map<dynamic, dynamic> _packageRestorationData({bool enabled = true, Map<dynamic, dynamic>? data}) {
final ByteData? encoded = const StandardMessageCodec().encodeMessage(data);
return <dynamic, dynamic>{
'enabled': enabled,
'data': encoded?.buffer.asUint8List(encoded.offsetInBytes, encoded.lengthInBytes),
};
}
class TestRestorationManager extends RestorationManager {
void receiveDataFromEngine({required bool enabled, required Uint8List? data}) {
handleRestorationUpdateFromEngine(enabled: enabled, data: data);
}
}
| flutter/packages/flutter/test/services/restoration_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/services/restoration_test.dart",
"repo_id": "flutter",
"token_count": 5270
} | 859 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('AnimatedContainer.debugFillProperties', (WidgetTester tester) async {
final AnimatedContainer container = AnimatedContainer(
constraints: const BoxConstraints.tightFor(width: 17.0, height: 23.0),
decoration: const BoxDecoration(color: Color(0xFF00FF00)),
foregroundDecoration: const BoxDecoration(color: Color(0x7F0000FF)),
margin: const EdgeInsets.all(10.0),
padding: const EdgeInsets.all(7.0),
transform: Matrix4.translationValues(4.0, 3.0, 0.0),
width: 50.0,
height: 75.0,
curve: Curves.ease,
duration: const Duration(milliseconds: 200),
);
expect(container, hasOneLineDescription);
});
testWidgets('AnimatedContainer control test', (WidgetTester tester) async {
final GlobalKey key = GlobalKey();
const BoxDecoration decorationA = BoxDecoration(
color: Color(0xFF00FF00),
);
const BoxDecoration decorationB = BoxDecoration(
color: Color(0xFF0000FF),
);
BoxDecoration actualDecoration;
await tester.pumpWidget(
AnimatedContainer(
key: key,
duration: const Duration(milliseconds: 200),
decoration: decorationA,
),
);
final RenderDecoratedBox box = key.currentContext!.findRenderObject()! as RenderDecoratedBox;
actualDecoration = box.decoration as BoxDecoration;
expect(actualDecoration.color, equals(decorationA.color));
await tester.pumpWidget(
AnimatedContainer(
key: key,
duration: const Duration(milliseconds: 200),
decoration: decorationB,
),
);
expect(key.currentContext!.findRenderObject(), equals(box));
actualDecoration = box.decoration as BoxDecoration;
expect(actualDecoration.color, equals(decorationA.color));
await tester.pump(const Duration(seconds: 1));
actualDecoration = box.decoration as BoxDecoration;
expect(actualDecoration.color, equals(decorationB.color));
expect(box, hasAGoodToStringDeep);
expect(
box.toStringDeep(minLevel: DiagnosticLevel.info),
equalsIgnoringHashCodes(
'RenderDecoratedBox#00000\n'
' │ parentData: <none>\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ size: Size(800.0, 600.0)\n'
' │ decoration: BoxDecoration:\n'
' │ color: Color(0xff0000ff)\n'
' │ configuration: ImageConfiguration(bundle:\n'
' │ PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n'
' │ android)\n'
' │\n'
' └─child: RenderPadding#00000\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ size: Size(800.0, 600.0)\n'
' │ padding: EdgeInsets.zero\n'
' │\n'
' └─child: RenderLimitedBox#00000\n'
' │ parentData: offset=Offset(0.0, 0.0) (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, h=600.0)\n'
' │ size: Size(800.0, 600.0)\n'
' │ maxWidth: 0.0\n'
' │ maxHeight: 0.0\n'
' │\n'
' └─child: RenderConstrainedBox#00000\n'
' parentData: <none> (can use size)\n'
' constraints: BoxConstraints(w=800.0, h=600.0)\n'
' size: Size(800.0, 600.0)\n'
' additionalConstraints: BoxConstraints(biggest)\n',
),
);
});
testWidgets('AnimatedContainer overanimate test', (WidgetTester tester) async {
await tester.pumpWidget(
AnimatedContainer(
duration: const Duration(milliseconds: 200),
color: const Color(0xFF00FF00),
),
);
expect(tester.binding.transientCallbackCount, 0);
await tester.pump(const Duration(seconds: 1));
expect(tester.binding.transientCallbackCount, 0);
await tester.pumpWidget(
AnimatedContainer(
duration: const Duration(milliseconds: 200),
color: const Color(0xFF00FF00),
),
);
expect(tester.binding.transientCallbackCount, 0);
await tester.pump(const Duration(seconds: 1));
expect(tester.binding.transientCallbackCount, 0);
await tester.pumpWidget(
AnimatedContainer(
duration: const Duration(milliseconds: 200),
color: const Color(0xFF0000FF),
),
);
expect(tester.binding.transientCallbackCount, 1); // this is the only time an animation should have started!
await tester.pump(const Duration(seconds: 1));
expect(tester.binding.transientCallbackCount, 0);
await tester.pumpWidget(
AnimatedContainer(
duration: const Duration(milliseconds: 200),
color: const Color(0xFF0000FF),
),
);
expect(tester.binding.transientCallbackCount, 0);
});
testWidgets('AnimatedContainer padding visual-to-directional animation', (WidgetTester tester) async {
final Key target = UniqueKey();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
padding: const EdgeInsets.only(right: 50.0),
child: SizedBox.expand(key: target),
),
),
);
expect(tester.getSize(find.byKey(target)), const Size(750.0, 600.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(750.0, 0.0));
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
padding: const EdgeInsetsDirectional.only(start: 100.0),
child: SizedBox.expand(key: target),
),
),
);
expect(tester.getSize(find.byKey(target)), const Size(750.0, 600.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(750.0, 0.0));
await tester.pump(const Duration(milliseconds: 100));
expect(tester.getSize(find.byKey(target)), const Size(725.0, 600.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(725.0, 0.0));
await tester.pump(const Duration(milliseconds: 500));
expect(tester.getSize(find.byKey(target)), const Size(700.0, 600.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(700.0, 0.0));
});
testWidgets('AnimatedContainer alignment visual-to-directional animation', (WidgetTester tester) async {
final Key target = UniqueKey();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
alignment: Alignment.topRight,
child: SizedBox(key: target, width: 100.0, height: 200.0),
),
),
);
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(800.0, 0.0));
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
alignment: AlignmentDirectional.bottomStart,
child: SizedBox(key: target, width: 100.0, height: 200.0),
),
),
);
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(800.0, 0.0));
await tester.pump(const Duration(milliseconds: 100));
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(800.0, 200.0));
await tester.pump(const Duration(milliseconds: 500));
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(800.0, 400.0));
});
testWidgets('Animation rerun', (WidgetTester tester) async {
await tester.pumpWidget(
Center(
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
width: 100.0,
height: 100.0,
child: const Text('X', textDirection: TextDirection.ltr),
),
),
);
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
RenderBox text = tester.renderObject(find.text('X'));
expect(text.size.width, equals(100.0));
expect(text.size.height, equals(100.0));
await tester.pump(const Duration(milliseconds: 1000));
await tester.pumpWidget(
Center(
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
width: 200.0,
height: 200.0,
child: const Text('X', textDirection: TextDirection.ltr),
),
),
);
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
text = tester.renderObject(find.text('X'));
expect(text.size.width, greaterThan(110.0));
expect(text.size.width, lessThan(190.0));
expect(text.size.height, greaterThan(110.0));
expect(text.size.height, lessThan(190.0));
await tester.pump(const Duration(milliseconds: 1000));
expect(text.size.width, equals(200.0));
expect(text.size.height, equals(200.0));
await tester.pumpWidget(
Center(
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
width: 200.0,
height: 100.0,
child: const Text('X', textDirection: TextDirection.ltr),
),
),
);
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
expect(text.size.width, equals(200.0));
expect(text.size.height, greaterThan(110.0));
expect(text.size.height, lessThan(190.0));
await tester.pump(const Duration(milliseconds: 1000));
expect(text.size.width, equals(200.0));
expect(text.size.height, equals(100.0));
});
testWidgets('AnimatedContainer sets transformAlignment', (WidgetTester tester) async {
final Key target = UniqueKey();
await tester.pumpWidget(
Center(
child: Directionality(
textDirection: TextDirection.ltr,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
transform: Matrix4.diagonal3Values(0.5, 0.5, 1),
transformAlignment: Alignment.topLeft,
child: SizedBox(key: target, width: 100.0, height: 200.0),
),
),
),
);
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopLeft(find.byKey(target)), const Offset(350.0, 200.0));
await tester.pumpWidget(
Center(
child: Directionality(
textDirection: TextDirection.ltr,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
transform: Matrix4.diagonal3Values(0.5, 0.5, 1),
transformAlignment: Alignment.bottomRight,
child: SizedBox(key: target, width: 100.0, height: 200.0),
),
),
),
);
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopLeft(find.byKey(target)), const Offset(350.0, 200.0));
await tester.pump(const Duration(milliseconds: 100));
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopLeft(find.byKey(target)), const Offset(375.0, 250.0));
await tester.pump(const Duration(milliseconds: 500));
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopLeft(find.byKey(target)), const Offset(400.0, 300.0));
});
testWidgets('AnimatedContainer sets clipBehavior', (WidgetTester tester) async {
await tester.pumpWidget(
AnimatedContainer(
decoration: const BoxDecoration(
color: Color(0xFFED1D7F),
),
duration: const Duration(milliseconds: 200),
),
);
expect(tester.firstWidget<Container>(find.byType(Container)).clipBehavior, Clip.none);
await tester.pumpWidget(
AnimatedContainer(
decoration: const BoxDecoration(
color: Color(0xFFED1D7F),
),
duration: const Duration(milliseconds: 200),
clipBehavior: Clip.antiAlias,
),
);
expect(tester.firstWidget<Container>(find.byType(Container)).clipBehavior, Clip.antiAlias);
});
}
| flutter/packages/flutter/test/widgets/animated_container_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/animated_container_test.dart",
"repo_id": "flutter",
"token_count": 5238
} | 860 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
Future<Size> _getSize(WidgetTester tester, BoxConstraints constraints, double aspectRatio) async {
final Key childKey = UniqueKey();
await tester.pumpWidget(
Center(
child: ConstrainedBox(
constraints: constraints,
child: AspectRatio(
aspectRatio: aspectRatio,
child: Container(
key: childKey,
),
),
),
),
);
final RenderBox box = tester.renderObject(find.byKey(childKey));
return box.size;
}
void main() {
testWidgets('Aspect ratio control test', (WidgetTester tester) async {
expect(await _getSize(tester, BoxConstraints.loose(const Size(500.0, 500.0)), 2.0), equals(const Size(500.0, 250.0)));
expect(await _getSize(tester, BoxConstraints.loose(const Size(500.0, 500.0)), 0.5), equals(const Size(250.0, 500.0)));
});
testWidgets('Aspect ratio infinite width', (WidgetTester tester) async {
final Key childKey = UniqueKey();
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: AspectRatio(
aspectRatio: 2.0,
child: Container(
key: childKey,
),
),
),
),
));
final RenderBox box = tester.renderObject(find.byKey(childKey));
expect(box.size, equals(const Size(1200.0, 600.0)));
});
}
| flutter/packages/flutter/test/widgets/aspect_ratio_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/aspect_ratio_test.dart",
"repo_id": "flutter",
"token_count": 698
} | 861 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
// This file is for tests for WidgetsBinding that require a `LiveTestWidgetsFlutterBinding`.
void main() {
LiveTestWidgetsFlutterBinding();
testWidgets('ReportTiming callback records the sendFramesToEngine when it was scheduled', (WidgetTester tester) async {
// Addresses https://github.com/flutter/flutter/issues/144261
// This test needs LiveTestWidgetsFlutterBinding for multiple reasons.
//
// First, this was the environment that this bug was discovered.
//
// Second, unlike `AutomatedTestWidgetsFlutterBinding`, which overrides
// `scheduleWarmUpFrame` to execute the handlers synchronously,
// `LiveTestWidgetsFlutterBinding` still calls them asynchronously. This
// allows `runApp`, which also schedules a warm-up frame, to bind a widget
// without rendering a frame, which is needed to for `deferFirstFrame` to
// take effect.
// Before `testWidgets` executes the test body, it pumps a frame with a
// fixed dummy widget, then calls `resetFirstFrameSent`. The pumped frame
// schedules a reportTiming call that has yet to arrive.
//
// This puts the test in an inconsistent state: a reportTiming callback is
// supposed to happen only after a frame is rendered, but due to
// `resetFirstFrameSent`, the framework thinks no frames have been rendered.
expect(tester.binding.sendFramesToEngine, true);
// Push the widget with `runApp` instead of `tester.pump`, avoiding
// rendering a frame, which is needed for `deferFirstFrame` later to work.
runApp(const DummyWidget());
// Verify that no widget tree is built and nothing is rendered.
expect(find.text('First frame'), findsNothing);
// Defer the first frame, making `sendFramesToEngine` false, so that widget
// tree will be built but not sent to the engine.
tester.binding.deferFirstFrame();
expect(tester.binding.sendFramesToEngine, false);
// Pump a frame, letting the reportTiming callback to run. If the
// reportTiming callback were to assume that `sendFramesToEngine` is true,
// the callback would crash.
await tester.pump(const Duration(milliseconds: 1));
await tester.binding.waitUntilFirstFrameRasterized;
expect(find.text('First frame'), findsOne);
}, skip: kIsWeb); // [intended] Web doesn't use LiveTestWidgetsFlutterBinding
}
class DummyWidget extends StatelessWidget {
const DummyWidget({super.key});
@override
Widget build(BuildContext context) {
return const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Text('First frame'),
),
);
}
}
| flutter/packages/flutter/test/widgets/binding_live_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/binding_live_test.dart",
"repo_id": "flutter",
"token_count": 896
} | 862 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
import 'clipboard_utils.dart';
import 'editable_text_utils.dart';
void main() {
final MockClipboard mockClipboard = MockClipboard();
TestWidgetsFlutterBinding.ensureInitialized()
.defaultBinaryMessenger.setMockMethodCallHandler(SystemChannels.platform, mockClipboard.handleMethodCall);
setUp(() async {
// Fill the clipboard so that the Paste option is available in the text
// selection menu.
await Clipboard.setData(const ClipboardData(text: 'Clipboard data'));
});
testWidgets('Hides and shows only a single menu', (WidgetTester tester) async {
final GlobalKey key1 = GlobalKey();
final GlobalKey key2 = GlobalKey();
late final BuildContext context;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext localContext) {
context = localContext;
return const SizedBox.shrink();
},
),
),
),
);
expect(find.byKey(key1), findsNothing);
expect(find.byKey(key2), findsNothing);
final ContextMenuController controller1 = ContextMenuController();
await tester.pump();
expect(find.byKey(key1), findsNothing);
expect(find.byKey(key2), findsNothing);
controller1.show(
context: context,
contextMenuBuilder: (BuildContext context) {
return Placeholder(key: key1);
},
);
await tester.pump();
expect(find.byKey(key1), findsOneWidget);
expect(find.byKey(key2), findsNothing);
// Showing the same thing again does nothing and is not an error.
controller1.show(
context: context,
contextMenuBuilder: (BuildContext context) {
return Placeholder(key: key1);
},
);
await tester.pump();
expect(tester.takeException(), null);
expect(find.byKey(key1), findsOneWidget);
expect(find.byKey(key2), findsNothing);
// Showing a new menu hides the first.
final ContextMenuController controller2 = ContextMenuController();
controller2.show(
context: context,
contextMenuBuilder: (BuildContext context) {
return Placeholder(key: key2);
},
);
await tester.pump();
expect(find.byKey(key1), findsNothing);
expect(find.byKey(key2), findsOneWidget);
controller2.remove();
await tester.pump();
expect(find.byKey(key1), findsNothing);
expect(find.byKey(key2), findsNothing);
});
testWidgets('A menu can be hidden and then reshown',
// TODO(polina-c): clean up leaks, https://github.com/flutter/flutter/issues/134787 [leaks-to-clean]
experimentalLeakTesting: LeakTesting.settings.withIgnoredAll(),
(WidgetTester tester) async {
final GlobalKey key1 = GlobalKey();
late final BuildContext context;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext localContext) {
context = localContext;
return const SizedBox.shrink();
},
),
),
),
);
expect(find.byKey(key1), findsNothing);
final ContextMenuController controller = ContextMenuController();
// Instantiating the controller does not shown it.
await tester.pump();
expect(find.byKey(key1), findsNothing);
controller.show(
context: context,
contextMenuBuilder: (BuildContext context) {
return Placeholder(key: key1);
},
);
await tester.pump();
expect(find.byKey(key1), findsOneWidget);
controller.remove();
await tester.pump();
expect(find.byKey(key1), findsNothing);
controller.show(
context: context,
contextMenuBuilder: (BuildContext context) {
return Placeholder(key: key1);
},
);
await tester.pump();
expect(find.byKey(key1), findsOneWidget);
});
testWidgets('markNeedsBuild causes the builder to update', (WidgetTester tester) async {
int buildCount = 0;
late final BuildContext context;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext localContext) {
context = localContext;
return const SizedBox.shrink();
},
),
),
),
);
final ContextMenuController controller = ContextMenuController();
controller.show(
context: context,
contextMenuBuilder: (BuildContext context) {
buildCount++;
return const Placeholder();
},
);
expect(buildCount, 0);
await tester.pump();
expect(buildCount, 1);
controller.markNeedsBuild();
expect(buildCount, 1);
await tester.pump();
expect(buildCount, 2);
controller.remove();
});
testWidgets('Calling show when a built-in widget is already showing its context menu hides the built-in menu',
// TODO(polina-c): clean up leaks, https://github.com/flutter/flutter/issues/134787 [leaks-to-clean]
experimentalLeakTesting: LeakTesting.settings.withIgnoredAll(),
(WidgetTester tester) async {
final GlobalKey builtInKey = GlobalKey();
final GlobalKey directKey = GlobalKey();
late final BuildContext context;
final TextEditingController textEditingController = TextEditingController();
addTearDown(textEditingController.dispose);
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Builder(
builder: (BuildContext localContext) {
context = localContext;
return EditableText(
controller: textEditingController,
backgroundCursorColor: Colors.grey,
focusNode: focusNode,
style: const TextStyle(),
cursorColor: Colors.red,
selectionControls: materialTextSelectionHandleControls,
contextMenuBuilder: (
BuildContext context,
EditableTextState editableTextState,
) {
return Placeholder(key: builtInKey);
},
);
},
),
),
),
);
expect(find.byKey(builtInKey), findsNothing);
expect(find.byKey(directKey), findsNothing);
final EditableTextState state = tester.state<EditableTextState>(find.byType(EditableText));
await tester.tapAt(textOffsetToPosition(tester, 0));
await tester.pump();
expect(state.showToolbar(), true);
await tester.pump();
expect(find.byKey(builtInKey), findsOneWidget);
expect(find.byKey(directKey), findsNothing);
final ContextMenuController controller = ContextMenuController();
controller.show(
context: context,
contextMenuBuilder: (BuildContext context) {
return Placeholder(key: directKey);
},
);
await tester.pump();
expect(find.byKey(builtInKey), findsNothing);
expect(find.byKey(directKey), findsOneWidget);
expect(controller.isShown, isTrue);
// And showing the built-in menu hides the directly shown menu.
expect(state.showToolbar(), isTrue);
await tester.pump();
expect(find.byKey(builtInKey), findsOneWidget);
expect(find.byKey(directKey), findsNothing);
expect(controller.isShown, isFalse);
// Calling remove on the hidden ContextMenuController does not hide the
// built-in menu.
controller.remove();
await tester.pump();
expect(find.byKey(builtInKey), findsOneWidget);
expect(find.byKey(directKey), findsNothing);
expect(controller.isShown, isFalse);
state.hideToolbar();
await tester.pump();
expect(find.byKey(builtInKey), findsNothing);
expect(find.byKey(directKey), findsNothing);
expect(controller.isShown, isFalse);
},
skip: isContextMenuProvidedByPlatform, // [intended] no Flutter-drawn text selection toolbar on web.
);
}
| flutter/packages/flutter/test/widgets/context_menu_controller_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/context_menu_controller_test.dart",
"repo_id": "flutter",
"token_count": 3213
} | 863 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
group('DisplayFeatureSubScreen', () {
testWidgets('without Directionality or anchor', (WidgetTester tester) async {
const Key childKey = Key('childKey');
final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith(
displayFeatures: <DisplayFeature>[
const DisplayFeature(
bounds: Rect.fromLTRB(390, 0, 410, 600),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
]
);
await tester.pumpWidget(
MediaQuery(
data: mediaQuery,
child: const DisplayFeatureSubScreen(
child: SizedBox.expand(
key: childKey,
),
),
),
);
// With no Directionality or anchorpoint, the widget throws
final String message = tester.takeException().toString();
expect(message, contains('Directionality'));
});
testWidgets('with anchorPoint', (WidgetTester tester) async {
const Key childKey = Key('childKey');
final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith(
displayFeatures: <DisplayFeature>[
const DisplayFeature(
bounds: Rect.fromLTRB(390, 0, 410, 600),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
]
);
await tester.pumpWidget(
MediaQuery(
data: mediaQuery,
child: const DisplayFeatureSubScreen(
anchorPoint: Offset(600, 300),
child: SizedBox.expand(
key: childKey,
),
),
),
);
// anchorPoint is in the middle of the right screen
final RenderBox renderBox = tester.renderObject(find.byKey(childKey));
expect(renderBox.size.width, equals(390.0));
expect(renderBox.size.height, equals(600.0));
expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(410,0)));
});
testWidgets('with infinity anchorpoint', (WidgetTester tester) async {
const Key childKey = Key('childKey');
final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith(
displayFeatures: <DisplayFeature>[
const DisplayFeature(
bounds: Rect.fromLTRB(390, 0, 410, 600),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
]
);
await tester.pumpWidget(
MediaQuery(
data: mediaQuery,
child: const DisplayFeatureSubScreen(
anchorPoint: Offset.infinite,
child: SizedBox.expand(
key: childKey,
),
),
),
);
// anchorPoint is infinite, so the bottom-most & right-most screen is chosen
final RenderBox renderBox = tester.renderObject(find.byKey(childKey));
expect(renderBox.size.width, equals(390.0));
expect(renderBox.size.height, equals(600.0));
expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(410,0)));
});
testWidgets('with horizontal hinge and anchorPoint', (WidgetTester tester) async {
const Key childKey = Key('childKey');
final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith(
displayFeatures: <DisplayFeature>[
const DisplayFeature(
bounds: Rect.fromLTRB(0, 290, 800, 310),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
]
);
await tester.pumpWidget(
MediaQuery(
data: mediaQuery,
child: const DisplayFeatureSubScreen(
anchorPoint: Offset(1000, 1000),
child: SizedBox.expand(
key: childKey,
),
),
),
);
final RenderBox renderBox = tester.renderObject(find.byKey(childKey));
expect(renderBox.size.width, equals(800.0));
expect(renderBox.size.height, equals(290.0));
expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(0,310)));
});
testWidgets('with multiple display features and anchorPoint', (WidgetTester tester) async {
const Key childKey = Key('childKey');
final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith(
displayFeatures: <DisplayFeature>[
const DisplayFeature(
bounds: Rect.fromLTRB(0, 290, 800, 310),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
const DisplayFeature(
bounds: Rect.fromLTRB(390, 0, 410, 600),
type: DisplayFeatureType.hinge,
state: DisplayFeatureState.unknown,
),
]
);
await tester.pumpWidget(
MediaQuery(
data: mediaQuery,
child: const DisplayFeatureSubScreen(
anchorPoint: Offset(1000, 1000),
child: SizedBox.expand(
key: childKey,
),
),
),
);
final RenderBox renderBox = tester.renderObject(find.byKey(childKey));
expect(renderBox.size.width, equals(390.0));
expect(renderBox.size.height, equals(290.0));
expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(410,310)));
});
testWidgets('with non-splitting display features and anchorPoint', (WidgetTester tester) async {
const Key childKey = Key('childKey');
final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith(
displayFeatures: <DisplayFeature>[
// Top notch
const DisplayFeature(
bounds: Rect.fromLTRB(100, 0, 700, 100),
type: DisplayFeatureType.cutout,
state: DisplayFeatureState.unknown,
),
// Bottom notch
const DisplayFeature(
bounds: Rect.fromLTRB(100, 500, 700, 600),
type: DisplayFeatureType.cutout,
state: DisplayFeatureState.unknown,
),
const DisplayFeature(
bounds: Rect.fromLTRB(0, 300, 800, 300),
type: DisplayFeatureType.fold,
state: DisplayFeatureState.postureFlat,
),
]
);
await tester.pumpWidget(
MediaQuery(
data: mediaQuery,
child: const Directionality(
textDirection: TextDirection.ltr,
child: DisplayFeatureSubScreen(
child: SizedBox.expand(
key: childKey,
),
),
),
),
);
// The display features provided are not wide enough to produce sub-screens
final RenderBox renderBox = tester.renderObject(find.byKey(childKey));
expect(renderBox.size.width, equals(800.0));
expect(renderBox.size.height, equals(600.0));
expect(renderBox.localToGlobal(Offset.zero), equals(Offset.zero));
});
testWidgets('with size 0 display feature in half-opened posture and anchorPoint', (WidgetTester tester) async {
const Key childKey = Key('childKey');
final MediaQueryData mediaQuery = MediaQueryData.fromView(tester.view).copyWith(
displayFeatures: <DisplayFeature>[
const DisplayFeature(
bounds: Rect.fromLTRB(0, 300, 800, 300),
type: DisplayFeatureType.fold,
state: DisplayFeatureState.postureHalfOpened,
),
]
);
await tester.pumpWidget(
MediaQuery(
data: mediaQuery,
child: const DisplayFeatureSubScreen(
anchorPoint: Offset(1000, 1000),
child: SizedBox.expand(
key: childKey,
),
),
),
);
final RenderBox renderBox = tester.renderObject(find.byKey(childKey));
expect(renderBox.size.width, equals(800.0));
expect(renderBox.size.height, equals(300.0));
expect(renderBox.localToGlobal(Offset.zero), equals(const Offset(0,300)));
});
});
}
| flutter/packages/flutter/test/widgets/display_feature_sub_screen_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/display_feature_sub_screen_test.dart",
"repo_id": "flutter",
"token_count": 3792
} | 864 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('FadeTransition', (WidgetTester tester) async {
final DebugPrintCallback oldPrint = debugPrint;
final List<String> log = <String>[];
debugPrint = (String? message, { int? wrapWidth }) {
log.add(message!);
};
debugPrintBuildScope = true;
final AnimationController controller = AnimationController(
vsync: const TestVSync(),
duration: const Duration(seconds: 2),
);
addTearDown(controller.dispose);
await tester.pumpWidget(FadeTransition(
opacity: controller,
child: const Placeholder(),
));
expect(log, hasLength(2));
expect(log.last, 'buildScope finished');
await tester.pump();
expect(log, hasLength(2));
controller.forward();
await tester.pumpAndSettle();
expect(log, hasLength(2));
debugPrint = oldPrint;
debugPrintBuildScope = false;
});
}
| flutter/packages/flutter/test/widgets/fade_transition_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/fade_transition_test.dart",
"repo_id": "flutter",
"token_count": 408
} | 865 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('GridPaper control test', (WidgetTester tester) async {
await tester.pumpWidget(const GridPaper());
final List<Layer> layers1 = tester.layers;
await tester.pumpWidget(const GridPaper());
final List<Layer> layers2 = tester.layers;
expect(layers1, equals(layers2));
});
}
| flutter/packages/flutter/test/widgets/grid_paper_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/grid_paper_test.dart",
"repo_id": "flutter",
"token_count": 204
} | 866 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui show Image;
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
class TestImageProvider extends ImageProvider<TestImageProvider> {
const TestImageProvider(this.image);
final ui.Image image;
@override
Future<TestImageProvider> obtainKey(ImageConfiguration configuration) {
return SynchronousFuture<TestImageProvider>(this);
}
@override
ImageStreamCompleter loadImage(TestImageProvider key, ImageDecoderCallback decode) {
return OneFrameImageStreamCompleter(
SynchronousFuture<ImageInfo>(ImageInfo(image: image)),
);
}
}
void main() {
late ui.Image testImage;
setUpAll(() async {
testImage = await createTestImage(width: 16, height: 9);
});
tearDownAll(() {
testImage.dispose();
});
testWidgets('DecorationImage RTL with alignment topEnd and match', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: Center(
child: Container(
width: 100.0,
height: 50.0,
decoration: BoxDecoration(
image: DecorationImage(
image: TestImageProvider(testImage),
alignment: AlignmentDirectional.topEnd,
repeat: ImageRepeat.repeatX,
matchTextDirection: true,
),
),
),
),
),
duration: Duration.zero,
phase: EnginePhase.layout, // so that we don't try to paint the fake images
);
expect(find.byType(Container), paints
..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0))
..translate(x: 50.0, y: 0.0)
..scale(x: -1.0, y: 1.0)
..translate(x: -50.0, y: 0.0)
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(-12.0, 0.0, 4.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(4.0, 0.0, 20.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(20.0, 0.0, 36.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(36.0, 0.0, 52.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(52.0, 0.0, 68.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(68.0, 0.0, 84.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 0.0, 100.0, 9.0))
..restore(),
);
expect(find.byType(Container), isNot(paints..scale()..scale()));
});
testWidgets('DecorationImage LTR with alignment topEnd (and pointless match)', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Container(
width: 100.0,
height: 50.0,
decoration: BoxDecoration(
image: DecorationImage(
image: TestImageProvider(testImage),
alignment: AlignmentDirectional.topEnd,
repeat: ImageRepeat.repeatX,
matchTextDirection: true,
),
),
),
),
),
duration: Duration.zero,
phase: EnginePhase.layout, // so that we don't try to paint the fake images
);
expect(find.byType(Container), paints
..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(-12.0, 0.0, 4.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(4.0, 0.0, 20.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(20.0, 0.0, 36.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(36.0, 0.0, 52.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(52.0, 0.0, 68.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(68.0, 0.0, 84.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 0.0, 100.0, 9.0))
..restore(),
);
expect(find.byType(Container), isNot(paints..scale()));
});
testWidgets('DecorationImage RTL with alignment topEnd', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: Center(
child: Container(
width: 100.0,
height: 50.0,
decoration: BoxDecoration(
image: DecorationImage(
image: TestImageProvider(testImage),
alignment: AlignmentDirectional.topEnd,
repeat: ImageRepeat.repeatX,
),
),
),
),
),
duration: Duration.zero,
phase: EnginePhase.layout, // so that we don't try to paint the fake images
);
expect(find.byType(Container), paints
..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(16.0, 0.0, 32.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(32.0, 0.0, 48.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(48.0, 0.0, 64.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(64.0, 0.0, 80.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(80.0, 0.0, 96.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(96.0, 0.0, 112.0, 9.0))
..restore(),
);
expect(find.byType(Container), isNot(paints..scale()));
});
testWidgets('DecorationImage LTR with alignment topEnd', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Container(
width: 100.0,
height: 50.0,
decoration: BoxDecoration(
image: DecorationImage(
image: TestImageProvider(testImage),
alignment: AlignmentDirectional.topEnd,
repeat: ImageRepeat.repeatX,
),
),
),
),
),
duration: Duration.zero,
phase: EnginePhase.layout, // so that we don't try to paint the fake images
);
expect(find.byType(Container), paints
..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(-12.0, 0.0, 4.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(4.0, 0.0, 20.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(20.0, 0.0, 36.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(36.0, 0.0, 52.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(52.0, 0.0, 68.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(68.0, 0.0, 84.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 0.0, 100.0, 9.0))
..restore(),
);
expect(find.byType(Container), isNot(paints..scale()));
});
testWidgets('DecorationImage RTL with alignment center-right and match', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: Center(
child: Container(
width: 100.0,
height: 50.0,
decoration: BoxDecoration(
image: DecorationImage(
image: TestImageProvider(testImage),
alignment: Alignment.centerRight,
matchTextDirection: true,
),
),
),
),
),
duration: Duration.zero,
phase: EnginePhase.layout, // so that we don't try to paint the fake images
);
expect(find.byType(Container), paints
..translate(x: 50.0, y: 0.0)
..scale(x: -1.0, y: 1.0)
..translate(x: -50.0, y: 0.0)
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(0.0, 20.5, 16.0, 29.5))
..restore(),
);
expect(find.byType(Container), isNot(paints..scale()..scale()));
expect(find.byType(Container), isNot(paints..drawImageRect()..drawImageRect()));
});
testWidgets('DecorationImage RTL with alignment center-right and no match', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: Center(
child: Container(
width: 100.0,
height: 50.0,
decoration: BoxDecoration(
image: DecorationImage(
image: TestImageProvider(testImage),
alignment: Alignment.centerRight,
),
),
),
),
),
duration: Duration.zero,
phase: EnginePhase.layout, // so that we don't try to paint the fake images
);
expect(find.byType(Container), paints
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 20.5, 100.0, 29.5)),
);
expect(find.byType(Container), isNot(paints..scale()));
expect(find.byType(Container), isNot(paints..drawImageRect()..drawImageRect()));
});
testWidgets('DecorationImage LTR with alignment center-right and match', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Container(
width: 100.0,
height: 50.0,
decoration: BoxDecoration(
image: DecorationImage(
image: TestImageProvider(testImage),
alignment: Alignment.centerRight,
matchTextDirection: true,
),
),
),
),
),
duration: Duration.zero,
phase: EnginePhase.layout, // so that we don't try to paint the fake images
);
expect(find.byType(Container), paints
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 20.5, 100.0, 29.5)),
);
expect(find.byType(Container), isNot(paints..scale()));
expect(find.byType(Container), isNot(paints..drawImageRect()..drawImageRect()));
});
testWidgets('DecorationImage LTR with alignment center-right and no match', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Container(
width: 100.0,
height: 50.0,
decoration: BoxDecoration(
image: DecorationImage(
image: TestImageProvider(testImage),
alignment: Alignment.centerRight,
matchTextDirection: true,
),
),
),
),
),
duration: Duration.zero,
phase: EnginePhase.layout, // so that we don't try to paint the fake images
);
expect(find.byType(Container), paints
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 20.5, 100.0, 29.5)),
);
expect(find.byType(Container), isNot(paints..scale()));
expect(find.byType(Container), isNot(paints..drawImageRect()..drawImageRect()));
});
testWidgets('Image RTL with alignment topEnd and match', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: Center(
child: SizedBox(
width: 100.0,
height: 50.0,
child: Image(
image: TestImageProvider(testImage),
alignment: AlignmentDirectional.topEnd,
repeat: ImageRepeat.repeatX,
matchTextDirection: true,
),
),
),
),
duration: Duration.zero,
phase: EnginePhase.layout, // so that we don't try to paint the fake images
);
expect(find.byType(SizedBox), paints
..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0))
..translate(x: 50.0, y: 0.0)
..scale(x: -1.0, y: 1.0)
..translate(x: -50.0, y: 0.0)
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(-12.0, 0.0, 4.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(4.0, 0.0, 20.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(20.0, 0.0, 36.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(36.0, 0.0, 52.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(52.0, 0.0, 68.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(68.0, 0.0, 84.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 0.0, 100.0, 9.0))
..restore(),
);
expect(find.byType(SizedBox), isNot(paints..scale()..scale()));
});
testWidgets('Image LTR with alignment topEnd (and pointless match)', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100.0,
height: 50.0,
child: Image(
image: TestImageProvider(testImage),
alignment: AlignmentDirectional.topEnd,
repeat: ImageRepeat.repeatX,
matchTextDirection: true,
),
),
),
),
duration: Duration.zero,
phase: EnginePhase.layout, // so that we don't try to paint the fake images
);
expect(find.byType(SizedBox), paints
..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(-12.0, 0.0, 4.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(4.0, 0.0, 20.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(20.0, 0.0, 36.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(36.0, 0.0, 52.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(52.0, 0.0, 68.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(68.0, 0.0, 84.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 0.0, 100.0, 9.0))
..restore(),
);
expect(find.byType(SizedBox), isNot(paints..scale()));
});
testWidgets('Image RTL with alignment topEnd', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: Center(
child: SizedBox(
width: 100.0,
height: 50.0,
child: Image(
image: TestImageProvider(testImage),
alignment: AlignmentDirectional.topEnd,
repeat: ImageRepeat.repeatX,
),
),
),
),
duration: Duration.zero,
phase: EnginePhase.layout, // so that we don't try to paint the fake images
);
expect(find.byType(SizedBox), paints
..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(16.0, 0.0, 32.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(32.0, 0.0, 48.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(48.0, 0.0, 64.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(64.0, 0.0, 80.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(80.0, 0.0, 96.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(96.0, 0.0, 112.0, 9.0))
..restore(),
);
expect(find.byType(SizedBox), isNot(paints..scale()));
});
testWidgets('Image LTR with alignment topEnd', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100.0,
height: 50.0,
child: Image(
image: TestImageProvider(testImage),
alignment: AlignmentDirectional.topEnd,
repeat: ImageRepeat.repeatX,
),
),
),
),
duration: Duration.zero,
phase: EnginePhase.layout, // so that we don't try to paint the fake images
);
expect(find.byType(SizedBox), paints
..clipRect(rect: const Rect.fromLTRB(0.0, 0.0, 100.0, 50.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(-12.0, 0.0, 4.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(4.0, 0.0, 20.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(20.0, 0.0, 36.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(36.0, 0.0, 52.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(52.0, 0.0, 68.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(68.0, 0.0, 84.0, 9.0))
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 0.0, 100.0, 9.0))
..restore(),
);
expect(find.byType(SizedBox), isNot(paints..scale()));
});
testWidgets('Image RTL with alignment center-right and match', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: Center(
child: SizedBox(
width: 100.0,
height: 50.0,
child: Image(
image: TestImageProvider(testImage),
alignment: Alignment.centerRight,
matchTextDirection: true,
),
),
),
),
);
expect(find.byType(SizedBox), paints
..translate(x: 50.0, y: 0.0)
..scale(x: -1.0, y: 1.0)
..translate(x: -50.0, y: 0.0)
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(0.0, 20.5, 16.0, 29.5))
..restore(),
);
expect(find.byType(SizedBox), isNot(paints..scale()..scale()));
expect(find.byType(SizedBox), isNot(paints..drawImageRect()..drawImageRect()));
});
testWidgets('Image RTL with alignment center-right and no match', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: Center(
child: SizedBox(
width: 100.0,
height: 50.0,
child: Image(
image: TestImageProvider(testImage),
alignment: Alignment.centerRight,
),
),
),
),
duration: Duration.zero,
phase: EnginePhase.layout, // so that we don't try to paint the fake images
);
expect(find.byType(SizedBox), paints
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 20.5, 100.0, 29.5)),
);
expect(find.byType(SizedBox), isNot(paints..scale()));
expect(find.byType(SizedBox), isNot(paints..drawImageRect()..drawImageRect()));
});
testWidgets('Image LTR with alignment center-right and match', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100.0,
height: 50.0,
child: Image(
image: TestImageProvider(testImage),
alignment: Alignment.centerRight,
matchTextDirection: true,
),
),
),
),
duration: Duration.zero,
phase: EnginePhase.layout, // so that we don't try to paint the fake images
);
expect(find.byType(SizedBox), paints
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 20.5, 100.0, 29.5)),
);
expect(find.byType(SizedBox), isNot(paints..scale()));
expect(find.byType(SizedBox), isNot(paints..drawImageRect()..drawImageRect()));
});
testWidgets('Image LTR with alignment center-right and no match', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100.0,
height: 50.0,
child: Image(
image: TestImageProvider(testImage),
alignment: Alignment.centerRight,
matchTextDirection: true,
),
),
),
),
duration: Duration.zero,
phase: EnginePhase.layout, // so that we don't try to paint the fake images
);
expect(find.byType(SizedBox), paints
..drawImageRect(source: const Rect.fromLTRB(0.0, 0.0, 16.0, 9.0), destination: const Rect.fromLTRB(84.0, 20.5, 100.0, 29.5)),
);
expect(find.byType(SizedBox), isNot(paints..scale()));
expect(find.byType(SizedBox), isNot(paints..drawImageRect()..drawImageRect()));
});
testWidgets('Image - Switch needing direction', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Image(
image: TestImageProvider(testImage),
alignment: Alignment.centerRight,
),
),
duration: Duration.zero,
phase: EnginePhase.layout, // so that we don't try to paint the fake images
);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Image(
image: TestImageProvider(testImage),
alignment: AlignmentDirectional.centerEnd,
matchTextDirection: true,
),
),
duration: Duration.zero,
phase: EnginePhase.layout, // so that we don't try to paint the fake images
);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Image(
image: TestImageProvider(testImage),
alignment: Alignment.centerRight,
),
),
duration: Duration.zero,
phase: EnginePhase.layout, // so that we don't try to paint the fake images
);
});
}
| flutter/packages/flutter/test/widgets/image_rtl_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/image_rtl_test.dart",
"repo_id": "flutter",
"token_count": 11578
} | 867 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
Future<void> sendKeyCombination(
WidgetTester tester,
SingleActivator activator,
) async {
final List<LogicalKeyboardKey> modifiers = <LogicalKeyboardKey>[
if (activator.control) LogicalKeyboardKey.control,
if (activator.shift) LogicalKeyboardKey.shift,
if (activator.alt) LogicalKeyboardKey.alt,
if (activator.meta) LogicalKeyboardKey.meta,
];
for (final LogicalKeyboardKey modifier in modifiers) {
await tester.sendKeyDownEvent(modifier);
}
await tester.sendKeyDownEvent(activator.trigger);
await tester.sendKeyUpEvent(activator.trigger);
await tester.pump();
for (final LogicalKeyboardKey modifier in modifiers.reversed) {
await tester.sendKeyUpEvent(modifier);
}
}
| flutter/packages/flutter/test/widgets/keyboard_utils.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/keyboard_utils.dart",
"repo_id": "flutter",
"token_count": 333
} | 868 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
const List<int> items = <int>[0, 1, 2, 3, 4, 5];
Widget buildFrame() {
return Directionality(
textDirection: TextDirection.ltr,
child: ListView(
itemExtent: 290.0,
children: items.map<Widget>((int item) {
return Text('$item');
}).toList(),
),
);
}
void main() {
testWidgets('Drag vertically', (WidgetTester tester) async {
await tester.pumpWidget(buildFrame());
await tester.pump();
await tester.drag(find.text('1'), const Offset(0.0, -300.0));
await tester.pump();
// screen is 600px high, and has the following items:
// -10..280 = 1
// 280..570 = 2
// 570..860 = 3
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
await tester.pump();
await tester.drag(find.text('2'), const Offset(0.0, -290.0));
await tester.pump();
// screen is 600px high, and has the following items:
// -10..280 = 2
// 280..570 = 3
// 570..860 = 4
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsNothing);
await tester.pump();
await tester.drag(find.text('3'), const Offset(-300.0, 0.0));
await tester.pump();
// nothing should have changed
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsNothing);
});
testWidgets('Drag vertically', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
itemExtent: 290.0,
padding: const EdgeInsets.only(top: 250.0),
children: items.map<Widget>((int item) {
return Text('$item');
}).toList(),
),
),
);
await tester.pump();
// screen is 600px high, and has the following items:
// 250..540 = 0
// 540..830 = 1
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
await tester.drag(find.text('0'), const Offset(0.0, -300.0));
await tester.pump();
// screen is 600px high, and has the following items:
// -50..240 = 0
// 240..530 = 1
// 530..820 = 2
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
});
}
| flutter/packages/flutter/test/widgets/list_view_vertical_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/list_view_vertical_test.dart",
"repo_id": "flutter",
"token_count": 1326
} | 869 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'multi_view_testing.dart';
void main() {
testWidgets('Hot reload does not crash if ViewAnchor is used between ParentDataWidget and the render object it is applied to', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/142480.
Widget buildTest(String string) {
return Directionality(
textDirection: TextDirection.ltr,
child: Stack(
children: <Widget>[
Positioned( // ParentDataWidget
right: 0,
bottom: 0,
child: ViewAnchor(
view: View(
view: FakeView(tester.view),
child: const Text('Side-view'),
),
child: Text(string), // Text's RenderObject is the target for the ParentDataWidget above.
),
),
],
),
);
}
await tester.pumpWidget(buildTest('bottom-right'));
expect(tester.getBottomRight(find.text('bottom-right')), const Offset(800, 600));
// Rebuild with a slightly different string to simulate a hot reload.
await tester.pumpWidget(buildTest('bottom-right-again'));
expect(find.text('bottom-right'), findsNothing);
expect(tester.getBottomRight(find.text('bottom-right-again')), const Offset(800, 600));
});
}
| flutter/packages/flutter/test/widgets/multi_view_parent_data_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/multi_view_parent_data_test.dart",
"repo_id": "flutter",
"token_count": 653
} | 870 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('OverflowBar documented defaults', (WidgetTester tester) async {
const OverflowBar bar = OverflowBar();
expect(bar.spacing, 0);
expect(bar.alignment, null);
expect(bar.overflowSpacing, 0);
expect(bar.overflowDirection, VerticalDirection.down);
expect(bar.textDirection, null);
expect(bar.children, const <Widget>[]);
});
testWidgets('Empty OverflowBar', (WidgetTester tester) async {
const Size size = Size(16, 24);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: ConstrainedBox(
constraints: BoxConstraints.tight(size),
child: const OverflowBar(),
),
),
),
);
expect(tester.getSize(find.byType(OverflowBar)), size);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: OverflowBar(),
),
),
);
expect(tester.getSize(find.byType(OverflowBar)), Size.zero);
});
testWidgets('OverflowBar horizontal layout', (WidgetTester tester) async {
final Key child1Key = UniqueKey();
final Key child2Key = UniqueKey();
final Key child3Key = UniqueKey();
Widget buildFrame({ required double spacing, required TextDirection textDirection }) {
return Directionality(
textDirection: textDirection,
child: Align(
alignment: Alignment.topLeft,
child: OverflowBar(
spacing: spacing,
children: <Widget>[
SizedBox(width: 48, height: 48, key: child1Key),
SizedBox(width: 64, height: 64, key: child2Key),
SizedBox(width: 32, height: 32, key: child3Key),
],
),
),
);
}
// Children are vertically centered, start at x=0
await tester.pumpWidget(buildFrame(spacing: 0, textDirection: TextDirection.ltr));
expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(0, 8, 48, 56));
expect(tester.getRect(find.byKey(child2Key)), const Rect.fromLTRB(48, 0, 112, 64));
expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(112, 16, 144, 48));
// Children are vertically centered, start at x=0
await tester.pumpWidget(buildFrame(spacing: 10, textDirection: TextDirection.ltr));
expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(0, 8, 48, 56));
expect(tester.getRect(find.byKey(child2Key)), const Rect.fromLTRB(10.0 + 48, 0, 10.0 + 112, 64));
expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(10.0 + 112 + 10.0, 16, 10.0 + 10.0 + 144, 48));
// Children appear in reverse order for RTL
await tester.pumpWidget(buildFrame(spacing: 0, textDirection: TextDirection.rtl));
expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(0, 16, 32, 48));
expect(tester.getRect(find.byKey(child2Key)), const Rect.fromLTRB(32, 0, 96, 64));
expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(96, 8, 144, 56));
// Children appear in reverse order for RTL
await tester.pumpWidget(buildFrame(spacing: 10, textDirection: TextDirection.rtl));
expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(0, 16, 32, 48));
expect(tester.getRect(find.byKey(child2Key)), const Rect.fromLTRB(10.0 + 32, 0, 10.0 + 96, 64));
expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(10.0 + 96 + 10.0, 8, 10.0 + 10.0 + 144, 56));
});
testWidgets('OverflowBar vertical layout', (WidgetTester tester) async {
final Key child1Key = UniqueKey();
final Key child2Key = UniqueKey();
final Key child3Key = UniqueKey();
Widget buildFrame({
double overflowSpacing = 0,
VerticalDirection overflowDirection = VerticalDirection.down,
OverflowBarAlignment overflowAlignment = OverflowBarAlignment.start,
TextDirection textDirection = TextDirection.ltr,
}) {
return Directionality(
textDirection: textDirection,
child: Align(
alignment: Alignment.topLeft,
child: ConstrainedBox(
constraints: BoxConstraints.loose(const Size(100, double.infinity)),
child: OverflowBar(
overflowSpacing: overflowSpacing,
overflowAlignment: overflowAlignment,
overflowDirection: overflowDirection,
children: <Widget>[
SizedBox(width: 48, height: 48, key: child1Key),
SizedBox(width: 64, height: 64, key: child2Key),
SizedBox(width: 32, height: 32, key: child3Key),
],
),
),
),
);
}
// Children are left aligned
await tester.pumpWidget(buildFrame());
expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(0, 0, 48, 48));
expect(tester.getRect(find.byKey(child2Key)), const Rect.fromLTRB(0, 48, 64, 112));
expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(0, 112, 32, 144));
// Children are left aligned
await tester.pumpWidget(buildFrame(overflowAlignment: OverflowBarAlignment.end, textDirection: TextDirection.rtl));
expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(0, 0, 48, 48));
expect(tester.getRect(find.byKey(child2Key)), const Rect.fromLTRB(0, 48, 64, 112));
expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(0, 112, 32, 144));
// Spaced children are left aligned
await tester.pumpWidget(buildFrame(overflowSpacing: 10));
expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(0, 0, 48, 48));
expect(tester.getRect(find.byKey(child2Key)), const Rect.fromLTRB(0, 10.0 + 48, 64, 10.0 + 112));
expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(0, 10.0 + 112 + 10.0, 32, 10.0 + 10.0 + 144));
// Left-aligned children appear in reverse order for VerticalDirection.up
await tester.pumpWidget(buildFrame(overflowDirection: VerticalDirection.up));
expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(0, 0, 32, 32));
expect(tester.getRect(find.byKey(child2Key)), const Rect.fromLTRB(0, 32, 64, 96));
expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(0, 96, 48, 144));
// Left-aligned spaced children appear in reverse order for VerticalDirection.up
await tester.pumpWidget(buildFrame(overflowSpacing: 10, overflowDirection: VerticalDirection.up));
expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(0, 0, 32, 32));
expect(tester.getRect(find.byKey(child2Key)), const Rect.fromLTRB(0, 10.0 + 32, 64, 10.0 + 96));
expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(0, 10.0 + 10.0 + 96, 48, 10.0 + 10.0 + 144));
// Children are right aligned
await tester.pumpWidget(buildFrame(overflowAlignment: OverflowBarAlignment.end));
expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(100.0 - 48, 0, 100, 48));
expect(tester.getRect(find.byKey(child2Key)), const Rect.fromLTRB(100.0 - 64, 48, 100, 112));
expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(100.0 - 32, 112, 100, 144));
// Children are right aligned
await tester.pumpWidget(buildFrame(textDirection: TextDirection.rtl));
expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(100.0 - 48, 0, 100, 48));
expect(tester.getRect(find.byKey(child2Key)), const Rect.fromLTRB(100.0 - 64, 48, 100, 112));
expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(100.0 - 32, 112, 100, 144));
// Children are centered
await tester.pumpWidget(buildFrame(overflowAlignment: OverflowBarAlignment.center));
expect(tester.getRect(find.byKey(child1Key)), const Rect.fromLTRB(100.0/2.0 - 48/2, 0, 100.0/2.0 + 48/2, 48));
expect(tester.getRect(find.byKey(child2Key)), const Rect.fromLTRB(100.0/2.0 - 64/2, 48, 100.0/2.0 + 64/2, 112));
expect(tester.getRect(find.byKey(child3Key)), const Rect.fromLTRB(100.0/2.0 - 32/2, 112, 100.0/2.0 + 32/2, 144));
});
testWidgets('OverflowBar intrinsic width', (WidgetTester tester) async {
Widget buildFrame({ required double width }) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Container(
width: width,
alignment: Alignment.topLeft,
child: const IntrinsicWidth(
child: OverflowBar(
spacing: 4,
overflowSpacing: 8,
children: <Widget>[
SizedBox(width: 48, height: 50),
SizedBox(width: 64, height: 25),
SizedBox(width: 32, height: 75),
],
),
),
),
),
);
}
await tester.pumpWidget(buildFrame(width: 800));
expect(tester.getSize(find.byType(OverflowBar)).width, 152); // 152 = 48 + 4 + 64 + 4 + 32
await tester.pumpWidget(buildFrame(width: 150));
expect(tester.getSize(find.byType(OverflowBar)).width, 150);
});
testWidgets('OverflowBar intrinsic height', (WidgetTester tester) async {
Widget buildFrame({ required double maxWidth }) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Container(
width: maxWidth,
alignment: Alignment.topLeft,
child: const IntrinsicHeight(
child: OverflowBar(
spacing: 4,
overflowSpacing: 8,
children: <Widget>[
SizedBox(width: 48, height: 50),
SizedBox(width: 64, height: 25),
SizedBox(width: 32, height: 75),
],
),
),
),
),
);
}
await tester.pumpWidget(buildFrame(maxWidth: 800));
expect(tester.getSize(find.byType(OverflowBar)).height, 75); // 75 = max(50, 25, 75)
await tester.pumpWidget(buildFrame(maxWidth: 150));
expect(tester.getSize(find.byType(OverflowBar)).height, 166); // 166 = 50 + 8 + 25 + 8 + 75
});
testWidgets('OverflowBar is wider that its intrinsic width', (WidgetTester tester) async {
final Key key0 = UniqueKey();
final Key key1 = UniqueKey();
final Key key2 = UniqueKey();
Widget buildFrame(TextDirection textDirection) {
return Directionality(
textDirection: textDirection,
child: SizedBox(
width: 800,
// intrinsic width = 50 + 10 + 60 + 10 + 70 = 200
child: OverflowBar(
spacing: 10,
children: <Widget>[
SizedBox(key: key0, width: 50, height: 50),
SizedBox(key: key1, width: 60, height: 50),
SizedBox(key: key2, width: 70, height: 50),
],
),
),
);
}
await tester.pumpWidget(buildFrame(TextDirection.ltr));
expect(tester.getSize(find.byType(OverflowBar)), const Size(800.0, 600.0));
expect(tester.getTopLeft(find.byKey(key0)).dx, 0);
expect(tester.getTopLeft(find.byKey(key1)).dx, 60);
expect(tester.getTopLeft(find.byKey(key2)).dx, 130);
await tester.pumpWidget(buildFrame(TextDirection.rtl));
expect(tester.getSize(find.byType(OverflowBar)), const Size(800.0, 600.0));
expect(tester.getTopLeft(find.byKey(key0)).dx, 750);
expect(tester.getTopLeft(find.byKey(key1)).dx, 680);
expect(tester.getTopLeft(find.byKey(key2)).dx, 600);
});
testWidgets('OverflowBar with alignment should match Row with mainAxisAlignment', (WidgetTester tester) async {
final Key key0 = UniqueKey();
final Key key1 = UniqueKey();
final Key key2 = UniqueKey();
// This list of children appears in a Row and an OverflowBar, so each
// find.byKey() for key0, key1, key2 returns two widgets.
final List<Widget> children = <Widget>[
SizedBox(key: key0, width: 50, height: 50),
SizedBox(key: key1, width: 70, height: 50),
SizedBox(key: key2, width: 80, height: 50),
];
const List<MainAxisAlignment> allAlignments = <MainAxisAlignment>[
MainAxisAlignment.start,
MainAxisAlignment.center,
MainAxisAlignment.end,
MainAxisAlignment.spaceBetween,
MainAxisAlignment.spaceAround,
MainAxisAlignment.spaceEvenly,
];
const List<TextDirection> allTextDirections = <TextDirection>[
TextDirection.ltr,
TextDirection.rtl,
];
Widget buildFrame(MainAxisAlignment alignment, TextDirection textDirection) {
return Directionality(
textDirection: textDirection,
child: Column(
children: <Widget>[
OverflowBar(
alignment: alignment,
children: children,
),
Row(
mainAxisAlignment: alignment,
children: children,
),
],
),
);
}
// Each key from key0, key1, key2 maps to one child in the OverflowBar
// and a matching child in the Row. We expect the children to be the
// same size and for their left and right edges to align.
void testLayout() {
expect(tester.getSize(find.byType(OverflowBar)), const Size(800, 50));
for (final Key key in <Key>[key0, key1, key2]) {
final Finder matchingChildren = find.byKey(key);
expect(matchingChildren.evaluate().length, 2);
final Rect rect0 = tester.getRect(matchingChildren.first);
final Rect rect1 = tester.getRect(matchingChildren.last);
expect(rect0.size, rect1.size);
expect(rect0.left, rect1.left);
expect(rect0.right, rect1.right);
}
}
for (final MainAxisAlignment alignment in allAlignments) {
for (final TextDirection textDirection in allTextDirections) {
await tester.pumpWidget(buildFrame(alignment, textDirection));
testLayout();
}
}
});
}
| flutter/packages/flutter/test/widgets/overflow_bar_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/overflow_bar_test.dart",
"repo_id": "flutter",
"token_count": 6006
} | 871 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/src/foundation/diagnostics.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
late FakeMenuChannel fakeMenuChannel;
late PlatformMenuDelegate originalDelegate;
late DefaultPlatformMenuDelegate delegate;
final List<String> selected = <String>[];
final List<String> opened = <String>[];
final List<String> closed = <String>[];
void onSelected(String item) {
selected.add(item);
}
void onOpen(String item) {
opened.add(item);
}
void onClose(String item) {
closed.add(item);
}
setUp(() {
fakeMenuChannel = FakeMenuChannel((MethodCall call) async {});
delegate = DefaultPlatformMenuDelegate(channel: fakeMenuChannel);
originalDelegate = WidgetsBinding.instance.platformMenuDelegate;
WidgetsBinding.instance.platformMenuDelegate = delegate;
selected.clear();
opened.clear();
closed.clear();
});
tearDown(() {
WidgetsBinding.instance.platformMenuDelegate = originalDelegate;
});
group('PlatformMenuBar', () {
group('basic menu structure is transmitted to platform', () {
testWidgets('using onSelected', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: PlatformMenuBar(
menus: createTestMenus(
onSelected: onSelected,
onOpen: onOpen,
onClose: onClose,
shortcuts: <String, MenuSerializableShortcut>{
subSubMenu10[0]: const SingleActivator(LogicalKeyboardKey.keyA, control: true),
subSubMenu10[1]: const SingleActivator(LogicalKeyboardKey.keyB, shift: true),
subSubMenu10[2]: const SingleActivator(LogicalKeyboardKey.keyC, alt: true),
subSubMenu10[3]: const SingleActivator(LogicalKeyboardKey.keyD, meta: true),
},
),
child: const Center(child: Text('Body')),
),
),
),
);
expect(
fakeMenuChannel.outgoingCalls.last.method,
equals('Menu.setMenus'),
);
expect(
fakeMenuChannel.outgoingCalls.last.arguments,
equals(expectedStructure),
);
});
testWidgets('using onSelectedIntent', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: PlatformMenuBar(
menus: createTestMenus(
onSelectedIntent: const DoNothingIntent(),
onOpen: onOpen,
onClose: onClose,
shortcuts: <String, MenuSerializableShortcut>{
subSubMenu10[0]: const SingleActivator(LogicalKeyboardKey.keyA, control: true),
subSubMenu10[1]: const SingleActivator(LogicalKeyboardKey.keyB, shift: true),
subSubMenu10[2]: const SingleActivator(LogicalKeyboardKey.keyC, alt: true),
subSubMenu10[3]: const SingleActivator(LogicalKeyboardKey.keyD, meta: true),
},
),
child: const Center(child: Text('Body')),
),
),
),
);
expect(
fakeMenuChannel.outgoingCalls.last.method,
equals('Menu.setMenus'),
);
expect(
fakeMenuChannel.outgoingCalls.last.arguments,
equals(expectedStructure),
);
});
});
testWidgets('asserts when more than one has locked the delegate', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Material(
child: PlatformMenuBar(
menus: <PlatformMenuItem>[],
child: PlatformMenuBar(
menus: <PlatformMenuItem>[],
child: SizedBox(),
),
),
),
),
);
expect(tester.takeException(), isA<AssertionError>());
});
testWidgets('diagnostics', (WidgetTester tester) async {
const PlatformMenuItem item = PlatformMenuItem(
label: 'label2',
shortcut: SingleActivator(LogicalKeyboardKey.keyA),
);
const PlatformMenuBar menuBar = PlatformMenuBar(
menus: <PlatformMenuItem>[item],
child: SizedBox(),
);
await tester.pumpWidget(
const MaterialApp(
home: Material(
child: menuBar,
),
),
);
await tester.pump();
expect(
menuBar.toStringDeep(),
equalsIgnoringHashCodes(
'PlatformMenuBar#00000\n'
' └─PlatformMenuItem#00000(label2)\n'
' label: "label2"\n'
' shortcut: SingleActivator#00000(keys: Key A)\n'
' DISABLED\n',
),
);
});
});
group('MenuBarItem', () {
testWidgets('diagnostics', (WidgetTester tester) async {
const PlatformMenuItem childItem = PlatformMenuItem(
label: 'label',
);
const PlatformMenu item = PlatformMenu(
label: 'label',
menus: <PlatformMenuItem>[childItem],
);
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
item.debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(description, <String>[
'label: "label"',
]);
});
});
group('ShortcutSerialization', () {
testWidgets('character constructor', (WidgetTester tester) async {
final ShortcutSerialization serialization = ShortcutSerialization.character('?');
expect(serialization.toChannelRepresentation(), equals(<String, Object?>{
'shortcutCharacter': '?',
'shortcutModifiers': 0,
}));
final ShortcutSerialization serializationWithModifiers = ShortcutSerialization.character('?', alt: true, control: true, meta: true);
expect(serializationWithModifiers.toChannelRepresentation(), equals(<String, Object?>{
'shortcutCharacter': '?',
'shortcutModifiers': 13,
}));
});
testWidgets('modifier constructor', (WidgetTester tester) async {
final ShortcutSerialization serialization = ShortcutSerialization.modifier(LogicalKeyboardKey.home);
expect(serialization.toChannelRepresentation(), equals(<String, Object?>{
'shortcutTrigger': LogicalKeyboardKey.home.keyId,
'shortcutModifiers': 0,
}));
final ShortcutSerialization serializationWithModifiers = ShortcutSerialization.modifier(LogicalKeyboardKey.home, alt: true, control: true, meta: true, shift: true);
expect(serializationWithModifiers.toChannelRepresentation(), equals(<String, Object?>{
'shortcutTrigger': LogicalKeyboardKey.home.keyId,
'shortcutModifiers': 15,
}));
});
});
}
const List<String> mainMenu = <String>[
'Menu 0',
'Menu 1',
'Menu 2',
'Menu 3',
];
const List<String> subMenu0 = <String>[
'Sub Menu 00',
];
const List<String> subMenu1 = <String>[
'Sub Menu 10',
'Sub Menu 11',
'Sub Menu 12',
];
const List<String> subSubMenu10 = <String>[
'Sub Sub Menu 110',
'Sub Sub Menu 111',
'Sub Sub Menu 112',
'Sub Sub Menu 113',
];
const List<String> subMenu2 = <String>[
'Sub Menu 20',
];
List<PlatformMenuItem> createTestMenus({
void Function(String)? onSelected,
Intent? onSelectedIntent,
void Function(String)? onOpen,
void Function(String)? onClose,
Map<String, MenuSerializableShortcut> shortcuts = const <String, MenuSerializableShortcut>{},
bool includeStandard = false,
}) {
final List<PlatformMenuItem> result = <PlatformMenuItem>[
PlatformMenu(
label: mainMenu[0],
onOpen: onOpen != null ? () => onOpen(mainMenu[0]) : null,
onClose: onClose != null ? () => onClose(mainMenu[0]) : null,
menus: <PlatformMenuItem>[
PlatformMenuItem(
label: subMenu0[0],
onSelected: onSelected != null ? () => onSelected(subMenu0[0]) : null,
onSelectedIntent: onSelectedIntent,
shortcut: shortcuts[subMenu0[0]],
),
],
),
PlatformMenu(
label: mainMenu[1],
onOpen: onOpen != null ? () => onOpen(mainMenu[1]) : null,
onClose: onClose != null ? () => onClose(mainMenu[1]) : null,
menus: <PlatformMenuItem>[
PlatformMenuItemGroup(
members: <PlatformMenuItem>[
PlatformMenuItem(
label: subMenu1[0],
onSelected: onSelected != null ? () => onSelected(subMenu0[0]) : null,
onSelectedIntent: onSelectedIntent,
shortcut: shortcuts[subMenu1[0]],
),
],
),
PlatformMenu(
label: subMenu1[1],
onOpen: onOpen != null ? () => onOpen(subMenu1[1]) : null,
onClose: onClose != null ? () => onClose(subMenu1[1]) : null,
menus: <PlatformMenuItem>[
PlatformMenuItemGroup(
members: <PlatformMenuItem>[
PlatformMenuItem(
label: subSubMenu10[0],
onSelected: onSelected != null ? () => onSelected(subSubMenu10[0]) : null,
onSelectedIntent: onSelectedIntent,
shortcut: shortcuts[subSubMenu10[0]],
),
],
),
PlatformMenuItemGroup(
members: <PlatformMenuItem>[
PlatformMenuItem(
label: subSubMenu10[1],
onSelected: onSelected != null ? () => onSelected(subSubMenu10[1]) : null,
onSelectedIntent: onSelectedIntent,
shortcut: shortcuts[subSubMenu10[1]],
),
],
),
PlatformMenuItem(
label: subSubMenu10[2],
onSelected: onSelected != null ? () => onSelected(subSubMenu10[2]) : null,
onSelectedIntent: onSelectedIntent,
shortcut: shortcuts[subSubMenu10[2]],
),
PlatformMenuItemGroup(
members: <PlatformMenuItem>[
PlatformMenuItem(
label: subSubMenu10[3],
onSelected: onSelected != null ? () => onSelected(subSubMenu10[3]) : null,
onSelectedIntent: onSelectedIntent,
shortcut: shortcuts[subSubMenu10[3]],
),
],
),
],
),
PlatformMenuItem(
label: subMenu1[2],
onSelected: onSelected != null ? () => onSelected(subMenu1[2]) : null,
onSelectedIntent: onSelectedIntent,
shortcut: shortcuts[subMenu1[2]],
),
],
),
PlatformMenu(
label: mainMenu[2],
onOpen: onOpen != null ? () => onOpen(mainMenu[2]) : null,
onClose: onClose != null ? () => onClose(mainMenu[2]) : null,
menus: <PlatformMenuItem>[
PlatformMenuItem(
// Always disabled.
label: subMenu2[0],
shortcut: shortcuts[subMenu2[0]],
),
],
),
// Disabled menu
PlatformMenu(
label: mainMenu[3],
onOpen: onOpen != null ? () => onOpen(mainMenu[2]) : null,
onClose: onClose != null ? () => onClose(mainMenu[2]) : null,
menus: <PlatformMenuItem>[],
),
];
return result;
}
const Map<String, Object?> expectedStructure = <String, Object?>{
'0': <Map<String, Object?>>[
<String, Object?>{
'id': 2,
'label': 'Menu 0',
'enabled': true,
'children': <Map<String, Object?>>[
<String, Object?>{
'id': 1,
'label': 'Sub Menu 00',
'enabled': true,
},
],
},
<String, Object?>{
'id': 18,
'label': 'Menu 1',
'enabled': true,
'children': <Map<String, Object?>>[
<String, Object?>{
'id': 4,
'label': 'Sub Menu 10',
'enabled': true,
},
<String, Object?>{'id': 5, 'isDivider': true},
<String, Object?>{
'id': 16,
'label': 'Sub Menu 11',
'enabled': true,
'children': <Map<String, Object?>>[
<String, Object?>{
'id': 7,
'label': 'Sub Sub Menu 110',
'enabled': true,
'shortcutTrigger': 97,
'shortcutModifiers': 8,
},
<String, Object?>{'id': 8, 'isDivider': true},
<String, Object?>{
'id': 10,
'label': 'Sub Sub Menu 111',
'enabled': true,
'shortcutTrigger': 98,
'shortcutModifiers': 2,
},
<String, Object?>{'id': 11, 'isDivider': true},
<String, Object?>{
'id': 12,
'label': 'Sub Sub Menu 112',
'enabled': true,
'shortcutTrigger': 99,
'shortcutModifiers': 4,
},
<String, Object?>{'id': 13, 'isDivider': true},
<String, Object?>{
'id': 14,
'label': 'Sub Sub Menu 113',
'enabled': true,
'shortcutTrigger': 100,
'shortcutModifiers': 1,
},
],
},
<String, Object?>{
'id': 17,
'label': 'Sub Menu 12',
'enabled': true,
},
],
},
<String, Object?>{
'id': 20,
'label': 'Menu 2',
'enabled': true,
'children': <Map<String, Object?>>[
<String, Object?>{
'id': 19,
'label': 'Sub Menu 20',
'enabled': false,
},
],
},
<String, Object?>{'id': 21, 'label': 'Menu 3', 'enabled': false, 'children': <Map<String, Object?>>[]},
],
};
class FakeMenuChannel implements MethodChannel {
FakeMenuChannel(this.outgoing);
Future<dynamic> Function(MethodCall) outgoing;
Future<void> Function(MethodCall)? incoming;
List<MethodCall> outgoingCalls = <MethodCall>[];
@override
BinaryMessenger get binaryMessenger => throw UnimplementedError();
@override
MethodCodec get codec => const StandardMethodCodec();
@override
Future<List<T>> invokeListMethod<T>(String method, [dynamic arguments]) => throw UnimplementedError();
@override
Future<Map<K, V>> invokeMapMethod<K, V>(String method, [dynamic arguments]) => throw UnimplementedError();
@override
Future<T> invokeMethod<T>(String method, [dynamic arguments]) async {
final MethodCall call = MethodCall(method, arguments);
outgoingCalls.add(call);
return await outgoing(call) as T;
}
@override
String get name => 'flutter/menu';
@override
void setMethodCallHandler(Future<void> Function(MethodCall call)? handler) => incoming = handler;
}
| flutter/packages/flutter/test/widgets/platform_menu_bar_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/platform_menu_bar_test.dart",
"repo_id": "flutter",
"token_count": 7013
} | 872 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'restoration.dart';
void main() {
testWidgets('claims bucket', (WidgetTester tester) async {
const String id = 'hello world 1234';
final MockRestorationManager manager = MockRestorationManager();
addTearDown(manager.dispose);
final Map<String, dynamic> rawData = <String, dynamic>{};
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData);
addTearDown(root.dispose);
expect(rawData, isEmpty);
await tester.pumpWidget(
UnmanagedRestorationScope(
bucket: root,
child: const _TestRestorableWidget(
restorationId: id,
),
),
);
manager.doSerialization();
final _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget));
expect(state.bucket?.restorationId, id);
expect((rawData[childrenMapKey] as Map<Object?, Object?>).containsKey(id), isTrue);
expect(state.property.value, 10);
expect((((rawData[childrenMapKey] as Map<Object?, Object?>)[id]! as Map<String, dynamic>)[valuesMapKey] as Map<Object?, Object?>)['foo'], 10);
expect(state.property.log, <String>['createDefaultValue', 'initWithValue', 'toPrimitives']);
expect(state.toggleBucketLog, isEmpty);
expect(state.restoreStateLog.single, isNull);
});
testWidgets('claimed bucket with data', (WidgetTester tester) async {
final MockRestorationManager manager = MockRestorationManager();
addTearDown(manager.dispose);
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: _createRawDataSet());
addTearDown(root.dispose);
await tester.pumpWidget(
UnmanagedRestorationScope(
bucket: root,
child: const _TestRestorableWidget(
restorationId: 'child1',
),
),
);
manager.doSerialization();
final _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget));
expect(state.bucket!.restorationId, 'child1');
expect(state.property.value, 22);
expect(state.property.log, <String>['fromPrimitives', 'initWithValue']);
expect(state.toggleBucketLog, isEmpty);
expect(state.restoreStateLog.single, isNull);
});
testWidgets('renames existing bucket when new ID is provided via widget', (WidgetTester tester) async {
final MockRestorationManager manager = MockRestorationManager();
addTearDown(manager.dispose);
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: _createRawDataSet());
addTearDown(root.dispose);
await tester.pumpWidget(
UnmanagedRestorationScope(
bucket: root,
child: const _TestRestorableWidget(
restorationId: 'child1',
),
),
);
manager.doSerialization();
// Claimed existing bucket with data.
final _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget));
expect(state.bucket!.restorationId, 'child1');
expect(state.bucket!.read<int>('foo'), 22);
final RestorationBucket bucket = state.bucket!;
state.property.log.clear();
state.restoreStateLog.clear();
// Rename the existing bucket.
await tester.pumpWidget(
UnmanagedRestorationScope(
bucket: root,
child: const _TestRestorableWidget(
restorationId: 'something else',
),
),
);
manager.doSerialization();
expect(state.bucket!.restorationId, 'something else');
expect(state.bucket!.read<int>('foo'), 22);
expect(state.bucket, same(bucket));
expect(state.property.log, isEmpty);
expect(state.restoreStateLog, isEmpty);
expect(state.toggleBucketLog, isEmpty);
});
testWidgets('renames existing bucket when didUpdateRestorationId is called', (WidgetTester tester) async {
final MockRestorationManager manager = MockRestorationManager();
addTearDown(manager.dispose);
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: _createRawDataSet());
addTearDown(root.dispose);
await tester.pumpWidget(
UnmanagedRestorationScope(
bucket: root,
child: const _TestRestorableWidget(
restorationId: 'child1',
),
),
);
manager.doSerialization();
// Claimed existing bucket with data.
final _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget));
expect(state.bucket!.restorationId, 'child1');
expect(state.bucket!.read<int>('foo'), 22);
final RestorationBucket bucket = state.bucket!;
state.property.log.clear();
state.restoreStateLog.clear();
// Rename the existing bucket.
state.injectId('newnewnew');
manager.doSerialization();
expect(state.bucket!.restorationId, 'newnewnew');
expect(state.bucket!.read<int>('foo'), 22);
expect(state.bucket, same(bucket));
expect(state.property.log, isEmpty);
expect(state.restoreStateLog, isEmpty);
expect(state.toggleBucketLog, isEmpty);
});
testWidgets('Disposing widget removes its data', (WidgetTester tester) async {
final MockRestorationManager manager = MockRestorationManager();
addTearDown(manager.dispose);
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData);
addTearDown(root.dispose);
expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child1'), isTrue);
await tester.pumpWidget(
UnmanagedRestorationScope(
bucket: root,
child: const _TestRestorableWidget(
restorationId: 'child1',
),
),
);
manager.doSerialization();
expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child1'), isTrue);
await tester.pumpWidget(
UnmanagedRestorationScope(
bucket: root,
child: Container(),
),
);
manager.doSerialization();
expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child1'), isFalse);
});
testWidgets('toggling id between null and non-null', (WidgetTester tester) async {
final MockRestorationManager manager = MockRestorationManager();
addTearDown(manager.dispose);
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData);
addTearDown(root.dispose);
await tester.pumpWidget(
UnmanagedRestorationScope(
bucket: root,
child: const _TestRestorableWidget(),
),
);
final _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget));
expect(state.bucket, isNull);
expect(state.property.value, 10); // Initialized to default.
expect((((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<String, dynamic>)['foo'], 22);
expect(state.property.log, <String>['createDefaultValue', 'initWithValue']);
state.property.log.clear();
expect(state.restoreStateLog.single, isNull);
expect(state.toggleBucketLog, isEmpty);
state.restoreStateLog.clear();
state.toggleBucketLog.clear();
// Change id to non-null.
await tester.pumpWidget(
UnmanagedRestorationScope(
bucket: root,
child: const _TestRestorableWidget(
restorationId: 'child1',
),
),
);
manager.doSerialization();
expect(state.bucket, isNotNull);
expect(state.bucket!.restorationId, 'child1');
expect(state.property.value, 10);
expect((((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<String, dynamic>)['foo'], 10);
expect(state.property.log, <String>['toPrimitives']);
state.property.log.clear();
expect(state.restoreStateLog, isEmpty);
expect(state.toggleBucketLog.single, isNull);
state.restoreStateLog.clear();
state.toggleBucketLog.clear();
final RestorationBucket bucket = state.bucket!;
// Change id back to null.
await tester.pumpWidget(
UnmanagedRestorationScope(
bucket: root,
child: const _TestRestorableWidget(),
),
);
manager.doSerialization();
expect(state.bucket, isNull);
expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child1'), isFalse);
expect(state.property.log, isEmpty);
expect(state.restoreStateLog, isEmpty);
expect(state.toggleBucketLog.single, same(bucket));
});
testWidgets('move in and out of scope', (WidgetTester tester) async {
final Key key = GlobalKey();
final MockRestorationManager manager = MockRestorationManager();
addTearDown(manager.dispose);
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData);
addTearDown(root.dispose);
await tester.pumpWidget(
_TestRestorableWidget(
key: key,
restorationId: 'child1',
),
);
final _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget));
expect(state.bucket, isNull);
expect(state.property.value, 10); // Initialized to default.
expect((((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<String, dynamic>)['foo'], 22);
expect(state.property.log, <String>['createDefaultValue', 'initWithValue']);
state.property.log.clear();
expect(state.restoreStateLog.single, isNull);
expect(state.toggleBucketLog, isEmpty);
state.restoreStateLog.clear();
state.toggleBucketLog.clear();
// Move it under a valid scope.
await tester.pumpWidget(
UnmanagedRestorationScope(
bucket: root,
child: _TestRestorableWidget(
key: key,
restorationId: 'child1',
),
),
);
manager.doSerialization();
expect(state.bucket, isNotNull);
expect(state.bucket!.restorationId, 'child1');
expect(state.property.value, 10);
expect((((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<String, dynamic>)['foo'], 10);
expect(state.property.log, <String>['toPrimitives']);
state.property.log.clear();
expect(state.restoreStateLog, isEmpty);
expect(state.toggleBucketLog.single, isNull);
state.restoreStateLog.clear();
state.toggleBucketLog.clear();
final RestorationBucket bucket = state.bucket!;
// Move out of scope again.
await tester.pumpWidget(
_TestRestorableWidget(
key: key,
restorationId: 'child1',
),
);
manager.doSerialization();
expect(state.bucket, isNull);
expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child1'), isFalse);
expect(state.property.log, isEmpty);
expect(state.restoreStateLog, isEmpty);
expect(state.toggleBucketLog.single, same(bucket));
});
testWidgets('moving scope moves its data', (WidgetTester tester) async {
final MockRestorationManager manager = MockRestorationManager();
addTearDown(manager.dispose);
final Map<String, dynamic> rawData = <String, dynamic>{};
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData);
addTearDown(root.dispose);
final Key key = GlobalKey();
await tester.pumpWidget(
UnmanagedRestorationScope(
bucket: root,
child: Row(
textDirection: TextDirection.ltr,
children: <Widget>[
RestorationScope(
restorationId: 'fixed',
child: _TestRestorableWidget(
key: key,
restorationId: 'moving-child',
),
),
],
),
),
);
manager.doSerialization();
final _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget));
expect(state.bucket!.restorationId, 'moving-child');
expect((((rawData[childrenMapKey] as Map<Object?, Object?>)['fixed']! as Map<String, dynamic>)[childrenMapKey] as Map<Object?, Object?>).containsKey('moving-child'), isTrue);
final RestorationBucket bucket = state.bucket!;
state.property.log.clear();
state.restoreStateLog.clear();
state.bucket!.write('value', 11);
manager.doSerialization();
// Move widget.
await tester.pumpWidget(
UnmanagedRestorationScope(
bucket: root,
child: Row(
textDirection: TextDirection.ltr,
children: <Widget>[
RestorationScope(
restorationId: 'fixed',
child: Container(),
),
_TestRestorableWidget(
key: key,
restorationId: 'moving-child',
),
],
),
),
);
manager.doSerialization();
expect(state.bucket!.restorationId, 'moving-child');
expect(state.bucket, same(bucket));
expect(state.bucket!.read<int>('value'), 11);
expect(state.property.log, isEmpty);
expect(state.toggleBucketLog, isEmpty);
expect(state.restoreStateLog, isEmpty);
expect((rawData[childrenMapKey] as Map<Object?, Object?>)['fixed'], isEmpty);
expect((rawData[childrenMapKey] as Map<Object?, Object?>).containsKey('moving-child'), isTrue);
});
testWidgets('restartAndRestore', (WidgetTester tester) async {
await tester.pumpWidget(
const RootRestorationScope(
restorationId: 'root-child',
child: _TestRestorableWidget(
restorationId: 'widget',
),
),
);
_TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget));
expect(state.bucket, isNotNull);
expect(state.property.value, 10); // default
expect(state.property.log, <String>['createDefaultValue', 'initWithValue', 'toPrimitives']);
expect(state.restoreStateLog.single, isNull);
expect(state.toggleBucketLog, isEmpty);
_clearLogs(state);
state.setProperties(() {
state.property.value = 20;
});
await tester.pump();
expect(state.property.value, 20);
expect(state.property.log, <String>['toPrimitives']);
expect(state.restoreStateLog, isEmpty);
expect(state.toggleBucketLog, isEmpty);
_clearLogs(state);
final _TestRestorableWidgetState oldState = state;
await tester.restartAndRestore();
state = tester.state(find.byType(_TestRestorableWidget));
expect(state, isNot(same(oldState)));
expect(state.property.value, 20);
expect(state.property.log, <String>['fromPrimitives', 'initWithValue']);
expect(state.restoreStateLog.single, isNull);
expect(state.toggleBucketLog, isEmpty);
});
testWidgets('restore while running', (WidgetTester tester) async {
await tester.pumpWidget(
const RootRestorationScope(
restorationId: 'root-child',
child: _TestRestorableWidget(
restorationId: 'widget',
),
),
);
_TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget));
state.setProperties(() {
state.property.value = 20;
});
await tester.pump();
expect(state.property.value, 20);
final TestRestorationData data = await tester.getRestorationData();
state.setProperties(() {
state.property.value = 30;
});
await tester.pump();
expect(state.property.value, 30);
_clearLogs(state);
final _TestRestorableWidgetState oldState = state;
final RestorationBucket oldBucket = oldState.bucket!;
await tester.restoreFrom(data);
state = tester.state(find.byType(_TestRestorableWidget));
expect(state, same(oldState));
expect(state.property.value, 20);
expect(state.property.log, <String>['fromPrimitives', 'initWithValue']);
expect(state.restoreStateLog.single, oldBucket);
expect(state.toggleBucketLog, isEmpty);
});
testWidgets('can register additional property outside of restoreState', (WidgetTester tester) async {
await tester.pumpWidget(
const RootRestorationScope(
restorationId: 'root-child',
child: _TestRestorableWidget(
restorationId: 'widget',
),
),
);
final _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget));
state.registerAdditionalProperty();
expect(state.additionalProperty!.value, 11);
expect(state.additionalProperty!.log, <String>['createDefaultValue', 'initWithValue', 'toPrimitives']);
state.setProperties(() {
state.additionalProperty!.value = 33;
});
await tester.pump();
expect(state.additionalProperty!.value, 33);
final TestRestorationData data = await tester.getRestorationData();
state.setProperties(() {
state.additionalProperty!.value = 44;
});
await tester.pump();
expect(state.additionalProperty!.value, 44);
_clearLogs(state);
await tester.restoreFrom(data);
expect(state, same(tester.state(find.byType(_TestRestorableWidget))));
expect(state.additionalProperty!.value, 33);
expect(state.property.log, <String>['fromPrimitives', 'initWithValue']);
});
testWidgets('cannot register same property twice', (WidgetTester tester) async {
await tester.pumpWidget(
const RootRestorationScope(
restorationId: 'root-child',
child: _TestRestorableWidget(
restorationId: 'widget',
),
),
);
final _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget));
state.registerAdditionalProperty();
await tester.pump();
expect(() => state.registerAdditionalProperty(), throwsAssertionError);
});
testWidgets('cannot register under ID that is already in use', (WidgetTester tester) async {
await tester.pumpWidget(
const RootRestorationScope(
restorationId: 'root-child',
child: _TestRestorableWidget(
restorationId: 'widget',
),
),
);
final _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget));
expect(() => state.registerPropertyUnderSameId(), throwsAssertionError);
});
testWidgets('data of disabled property is not stored', (WidgetTester tester) async {
await tester.pumpWidget(
const RootRestorationScope(
restorationId: 'root-child',
child: _TestRestorableWidget(
restorationId: 'widget',
),
),
);
_TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget));
state.setProperties(() {
state.property.value = 30;
});
await tester.pump();
expect(state.property.value, 30);
expect(state.bucket!.read<int>('foo'), 30);
_clearLogs(state);
state.setProperties(() {
state.property.enabled = false;
});
await tester.pump();
expect(state.property.value, 30);
expect(state.bucket!.contains('foo'), isFalse);
expect(state.property.log, isEmpty);
state.setProperties(() {
state.property.value = 40;
});
await tester.pump();
expect(state.bucket!.contains('foo'), isFalse);
expect(state.property.log, isEmpty);
await tester.restartAndRestore();
state = tester.state(find.byType(_TestRestorableWidget));
expect(state.property.log, <String>['createDefaultValue', 'initWithValue', 'toPrimitives']);
expect(state.property.value, 10); // Initialized to default value.
});
testWidgets('Enabling property stores its data again', (WidgetTester tester) async {
await tester.pumpWidget(
const RootRestorationScope(
restorationId: 'root-child',
child: _TestRestorableWidget(
restorationId: 'widget',
),
),
);
_TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget));
_clearLogs(state);
state.setProperties(() {
state.property.enabled = false;
});
await tester.pump();
expect(state.bucket!.contains('foo'), isFalse);
state.setProperties(() {
state.property.value = 40;
});
await tester.pump();
expect(state.property.value, 40);
expect(state.bucket!.contains('foo'), isFalse);
expect(state.property.log, isEmpty);
state.setProperties(() {
state.property.enabled = true;
});
await tester.pump();
expect(state.bucket!.read<int>('foo'), 40);
expect(state.property.log, <String>['toPrimitives']);
await tester.restartAndRestore();
state = tester.state(find.byType(_TestRestorableWidget));
expect(state.property.log, <String>['fromPrimitives', 'initWithValue']);
expect(state.property.value, 40);
});
testWidgets('Unregistering a property removes its data', (WidgetTester tester) async {
await tester.pumpWidget(
const RootRestorationScope(
restorationId: 'root-child',
child: _TestRestorableWidget(
restorationId: 'widget',
),
),
);
final _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget));
state.registerAdditionalProperty();
await tester.pump();
expect(state.additionalProperty!.value, 11);
expect(state.bucket!.read<int>('additional'), 11);
state.unregisterAdditionalProperty();
await tester.pump();
expect(state.bucket!.contains('additional'), isFalse);
expect(() => state.additionalProperty!.value, throwsAssertionError); // No longer registered.
// Can register the same property again.
state.registerAdditionalProperty();
await tester.pump();
expect(state.additionalProperty!.value, 11);
expect(state.bucket!.read<int>('additional'), 11);
});
testWidgets('Disposing a property unregisters it, but keeps data', (WidgetTester tester) async {
await tester.pumpWidget(
const RootRestorationScope(
restorationId: 'root-child',
child: _TestRestorableWidget(
restorationId: 'widget',
),
),
);
final _TestRestorableWidgetState state = tester.state(find.byType(_TestRestorableWidget));
state.registerAdditionalProperty();
await tester.pump();
expect(state.additionalProperty!.value, 11);
expect(state.bucket!.read<int>('additional'), 11);
state.additionalProperty!.dispose();
await tester.pump();
expect(state.bucket!.read<int>('additional'), 11);
// Can register property under same id again.
state.additionalProperty = _TestRestorableProperty(22);
state.registerAdditionalProperty();
await tester.pump();
expect(state.additionalProperty!.value, 11); // Old value restored.
expect(state.bucket!.read<int>('additional'), 11);
});
test('RestorableProperty throws after disposed', () {
final RestorableProperty<Object?> property = _TestRestorableProperty(10);
property.dispose();
expect(() => property.dispose(), throwsFlutterError);
});
}
void _clearLogs(_TestRestorableWidgetState state) {
state.property.log.clear();
state.additionalProperty?.log.clear();
state.restoreStateLog.clear();
state.toggleBucketLog.clear();
}
class _TestRestorableWidget extends StatefulWidget {
const _TestRestorableWidget({super.key, this.restorationId});
final String? restorationId;
@override
State<_TestRestorableWidget> createState() => _TestRestorableWidgetState();
}
class _TestRestorableWidgetState extends State<_TestRestorableWidget> with RestorationMixin {
final _TestRestorableProperty property = _TestRestorableProperty(10);
_TestRestorableProperty? additionalProperty;
bool _reregisterAdditionalProperty = false;
final List<RestorationBucket?> restoreStateLog = <RestorationBucket?>[];
final List<RestorationBucket?> toggleBucketLog = <RestorationBucket?>[];
@override
void restoreState(RestorationBucket? oldBucket, bool initialRestore) {
restoreStateLog.add(oldBucket);
registerForRestoration(property, 'foo');
if (_reregisterAdditionalProperty && additionalProperty != null) {
registerForRestoration(additionalProperty!, 'additional');
}
}
@override
void didToggleBucket(RestorationBucket? oldBucket) {
toggleBucketLog.add(oldBucket);
super.didToggleBucket(oldBucket);
}
@override
void dispose() {
super.dispose();
property.dispose();
additionalProperty?.dispose();
}
@override
Widget build(BuildContext context) {
return Container();
}
void setProperties(VoidCallback fn) => setState(fn);
String? _injectedId;
void injectId(String id) {
_injectedId = id;
didUpdateRestorationId();
}
void registerAdditionalProperty({bool reregister = true}) {
additionalProperty ??= _TestRestorableProperty(11);
registerForRestoration(additionalProperty!, 'additional');
_reregisterAdditionalProperty = reregister;
}
void unregisterAdditionalProperty() {
unregisterFromRestoration(additionalProperty!);
}
void registerPropertyUnderSameId() {
registerForRestoration(_TestRestorableProperty(11), 'foo');
}
@override
String? get restorationId => _injectedId ?? widget.restorationId;
}
Map<String, dynamic> _createRawDataSet() {
return <String, dynamic>{
valuesMapKey: <String, dynamic>{
'value1' : 10,
'value2' : 'Hello',
},
childrenMapKey: <String, dynamic>{
'child1' : <String, dynamic>{
valuesMapKey : <String, dynamic>{
'foo': 22,
},
},
'child2' : <String, dynamic>{
valuesMapKey : <String, dynamic>{
'bar': 33,
},
},
},
};
}
class _TestRestorableProperty extends RestorableProperty<Object?> {
_TestRestorableProperty(this._value);
List<String> log = <String>[];
@override
bool get enabled => _enabled;
bool _enabled = true;
set enabled(bool value) {
_enabled = value;
notifyListeners();
}
@override
Object? createDefaultValue() {
log.add('createDefaultValue');
return _value;
}
@override
Object? fromPrimitives(Object? data) {
log.add('fromPrimitives');
return data;
}
Object? get value {
assert(isRegistered);
return _value;
}
Object? _value;
set value(Object? value) {
_value = value;
notifyListeners();
}
@override
void initWithValue(Object? v) {
log.add('initWithValue');
_value = v;
}
@override
Object? toPrimitives() {
log.add('toPrimitives');
return _value;
}
}
| flutter/packages/flutter/test/widgets/restoration_mixin_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/restoration_mixin_test.dart",
"repo_id": "flutter",
"token_count": 9730
} | 873 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui show Image;
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
import '../painting/image_test_utils.dart';
void main() {
late ui.Image testImage;
ui.Image cloneImage() {
final ui.Image clone = testImage.clone();
addTearDown(clone.dispose);
return clone;
}
setUpAll(() async {
testImage = await createTestImage(width: 10, height: 10);
});
tearDownAll(() {
testImage.dispose();
});
tearDown(() {
imageCache.clear();
});
T findPhysics<T extends ScrollPhysics>(WidgetTester tester) {
return Scrollable.of(find.byType(TestWidget).evaluate().first).position.physics as T;
}
ScrollMetrics findMetrics(WidgetTester tester) {
return Scrollable.of(find.byType(TestWidget).evaluate().first).position;
}
testWidgets('ScrollAwareImageProvider does not delay if widget is not in scrollable', (WidgetTester tester) async {
final GlobalKey<TestWidgetState> key = GlobalKey<TestWidgetState>();
await tester.pumpWidget(TestWidget(key));
final DisposableBuildContext context = DisposableBuildContext(key.currentState!);
addTearDown(context.dispose);
final TestImageProvider testImageProvider = TestImageProvider(testImage.clone());
final ScrollAwareImageProvider<TestImageProvider> imageProvider = ScrollAwareImageProvider<TestImageProvider>(
context: context,
imageProvider: testImageProvider,
);
expect(testImageProvider.configuration, null);
expect(imageCache.containsKey(testImageProvider), false);
final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty);
expect(testImageProvider.configuration, ImageConfiguration.empty);
expect(stream.completer, isNotNull);
expect(stream.completer!.hasListeners, true);
expect(imageCache.containsKey(testImageProvider), true);
expect(imageCache.currentSize, 0);
testImageProvider.complete();
expect(imageCache.currentSize, 1);
});
testWidgets('ScrollAwareImageProvider does not delay if in scrollable that is not scrolling', (WidgetTester tester) async {
final GlobalKey<TestWidgetState> key = GlobalKey<TestWidgetState>();
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: ListView(
physics: RecordingPhysics(),
children: <Widget>[
TestWidget(key),
],
),
));
final DisposableBuildContext context = DisposableBuildContext(key.currentState!);
addTearDown(context.dispose);
final TestImageProvider testImageProvider = TestImageProvider(testImage.clone());
final ScrollAwareImageProvider<TestImageProvider> imageProvider = ScrollAwareImageProvider<TestImageProvider>(
context: context,
imageProvider: testImageProvider,
);
expect(testImageProvider.configuration, null);
expect(imageCache.containsKey(testImageProvider), false);
final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty);
expect(testImageProvider.configuration, ImageConfiguration.empty);
expect(stream.completer, isNotNull);
expect(stream.completer!.hasListeners, true);
expect(imageCache.containsKey(testImageProvider), true);
expect(imageCache.currentSize, 0);
testImageProvider.complete();
expect(imageCache.currentSize, 1);
expect(findPhysics<RecordingPhysics>(tester).velocities, <double>[0]);
});
testWidgets('ScrollAwareImageProvider does not delay if in scrollable that is scrolling slowly', (WidgetTester tester) async {
final List<GlobalKey<TestWidgetState>> keys = <GlobalKey<TestWidgetState>>[];
final ScrollController scrollController = ScrollController();
addTearDown(scrollController.dispose);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: ListView.builder(
physics: RecordingPhysics(),
controller: scrollController,
itemBuilder: (BuildContext context, int index) {
keys.add(GlobalKey<TestWidgetState>());
return TestWidget(keys.last);
},
itemCount: 50,
),
));
final DisposableBuildContext context = DisposableBuildContext(keys.last.currentState!);
addTearDown(context.dispose);
final TestImageProvider testImageProvider = TestImageProvider(testImage.clone());
final ScrollAwareImageProvider<TestImageProvider> imageProvider = ScrollAwareImageProvider<TestImageProvider>(
context: context,
imageProvider: testImageProvider,
);
expect(testImageProvider.configuration, null);
expect(imageCache.containsKey(testImageProvider), false);
scrollController.animateTo(
100,
duration: const Duration(seconds: 2),
curve: Curves.fastLinearToSlowEaseIn,
);
await tester.pump();
final RecordingPhysics physics = findPhysics<RecordingPhysics>(tester);
expect(physics.velocities.length, 0);
final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty);
expect(physics.velocities.length, 1);
expect(
const ScrollPhysics().recommendDeferredLoading(
physics.velocities.first,
findMetrics(tester),
find.byType(TestWidget).evaluate().first,
),
false,
);
expect(testImageProvider.configuration, ImageConfiguration.empty);
expect(stream.completer, isNotNull);
expect(stream.completer!.hasListeners, true);
expect(imageCache.containsKey(testImageProvider), true);
expect(imageCache.currentSize, 0);
testImageProvider.complete();
expect(imageCache.currentSize, 1);
});
testWidgets('ScrollAwareImageProvider delays if in scrollable that is scrolling fast', (WidgetTester tester) async {
final List<GlobalKey<TestWidgetState>> keys = <GlobalKey<TestWidgetState>>[];
final ScrollController scrollController = ScrollController();
addTearDown(scrollController.dispose);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: ListView.builder(
physics: RecordingPhysics(),
controller: scrollController,
itemBuilder: (BuildContext context, int index) {
keys.add(GlobalKey<TestWidgetState>());
return TestWidget(keys.last);
},
itemCount: 50,
),
));
final DisposableBuildContext context = DisposableBuildContext(keys.last.currentState!);
addTearDown(context.dispose);
final TestImageProvider testImageProvider = TestImageProvider(testImage.clone());
final ScrollAwareImageProvider<TestImageProvider> imageProvider = ScrollAwareImageProvider<TestImageProvider>(
context: context,
imageProvider: testImageProvider,
);
expect(testImageProvider.configuration, null);
expect(imageCache.containsKey(testImageProvider), false);
scrollController.animateTo(
3000,
duration: const Duration(seconds: 2),
curve: Curves.fastLinearToSlowEaseIn,
);
await tester.pump();
final RecordingPhysics physics = findPhysics<RecordingPhysics>(tester);
expect(physics.velocities.length, 0);
final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty);
expect(physics.velocities.length, 1);
expect(
const ScrollPhysics().recommendDeferredLoading(
physics.velocities.first,
findMetrics(tester),
find.byType(TestWidget).evaluate().first,
),
true,
);
expect(testImageProvider.configuration, null);
expect(stream.completer, null);
expect(imageCache.containsKey(testImageProvider), false);
expect(imageCache.currentSize, 0);
await tester.pump(const Duration(seconds: 1));
expect(physics.velocities.last, 0);
expect(testImageProvider.configuration, ImageConfiguration.empty);
expect(stream.completer, isNotNull);
expect(stream.completer!.hasListeners, true);
expect(imageCache.containsKey(testImageProvider), true);
expect(imageCache.currentSize, 0);
testImageProvider.complete();
expect(imageCache.currentSize, 1);
});
testWidgets('ScrollAwareImageProvider delays if in scrollable that is scrolling fast and fizzles if disposed', (WidgetTester tester) async {
final List<GlobalKey<TestWidgetState>> keys = <GlobalKey<TestWidgetState>>[];
final ScrollController scrollController = ScrollController();
addTearDown(scrollController.dispose);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: ListView.builder(
physics: RecordingPhysics(),
controller: scrollController,
itemBuilder: (BuildContext context, int index) {
keys.add(GlobalKey<TestWidgetState>());
return TestWidget(keys.last);
},
itemCount: 50,
),
));
final DisposableBuildContext context = DisposableBuildContext(keys.last.currentState!);
addTearDown(context.dispose);
final TestImageProvider testImageProvider = TestImageProvider(cloneImage());
final ScrollAwareImageProvider<TestImageProvider> imageProvider = ScrollAwareImageProvider<TestImageProvider>(
context: context,
imageProvider: testImageProvider,
);
expect(testImageProvider.configuration, null);
expect(imageCache.containsKey(testImageProvider), false);
scrollController.animateTo(
3000,
duration: const Duration(seconds: 2),
curve: Curves.fastLinearToSlowEaseIn,
);
await tester.pump();
final RecordingPhysics physics = findPhysics<RecordingPhysics>(tester);
expect(physics.velocities.length, 0);
final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty);
expect(physics.velocities.length, 1);
expect(
const ScrollPhysics().recommendDeferredLoading(
physics.velocities.first,
findMetrics(tester),
find.byType(TestWidget).evaluate().first,
),
true,
);
expect(testImageProvider.configuration, null);
expect(stream.completer, null);
expect(imageCache.containsKey(testImageProvider), false);
expect(imageCache.currentSize, 0);
// as if we had picked a context that scrolled out of the tree.
context.dispose();
await tester.pump(const Duration(seconds: 1));
expect(physics.velocities.length, 1);
expect(testImageProvider.configuration, null);
expect(stream.completer, null);
expect(imageCache.containsKey(testImageProvider), false);
expect(imageCache.currentSize, 0);
testImageProvider.complete();
expect(imageCache.currentSize, 0);
});
testWidgets('ScrollAwareImageProvider resolves from ImageCache and does not set completer twice', (WidgetTester tester) async {
final GlobalKey<TestWidgetState> key = GlobalKey<TestWidgetState>();
final ScrollController scrollController = ScrollController();
addTearDown(scrollController.dispose);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: SingleChildScrollView(
physics: ControllablePhysics(),
controller: scrollController,
child: TestWidget(key),
),
));
final DisposableBuildContext context = DisposableBuildContext(key.currentState!);
addTearDown(context.dispose);
final TestImageProvider testImageProvider = TestImageProvider(cloneImage());
final ScrollAwareImageProvider<TestImageProvider> imageProvider = ScrollAwareImageProvider<TestImageProvider>(
context: context,
imageProvider: testImageProvider,
);
expect(testImageProvider.configuration, null);
expect(imageCache.containsKey(testImageProvider), false);
final ControllablePhysics physics = findPhysics<ControllablePhysics>(tester);
physics.recommendDeferredLoadingValue = true;
final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty);
expect(testImageProvider.configuration, null);
expect(stream.completer, null);
expect(imageCache.containsKey(testImageProvider), false);
expect(imageCache.currentSize, 0);
// Simulate a case where someone else has managed to complete this stream -
// so it can land in the cache right before we stop scrolling fast.
// If we miss the early return, we will fail.
testImageProvider.complete();
imageCache.putIfAbsent(testImageProvider, () => testImageProvider.loadImage(testImageProvider, PaintingBinding.instance.instantiateImageCodecWithSize));
// We've stopped scrolling fast.
physics.recommendDeferredLoadingValue = false;
await tester.idle();
expect(imageCache.containsKey(testImageProvider), true);
expect(imageCache.currentSize, 1);
expect(testImageProvider.loadCallCount, 1);
expect(stream.completer, null);
});
testWidgets('ScrollAwareImageProvider does not block LRU updates to image cache',
experimentalLeakTesting: LeakTesting.settings.withIgnoredAll(),
(WidgetTester tester) async {
final int oldSize = imageCache.maximumSize;
imageCache.maximumSize = 1;
final GlobalKey<TestWidgetState> key = GlobalKey<TestWidgetState>();
final ScrollController scrollController = ScrollController();
addTearDown(scrollController.dispose);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: SingleChildScrollView(
physics: ControllablePhysics(),
controller: scrollController,
child: TestWidget(key),
),
));
final DisposableBuildContext context = DisposableBuildContext(key.currentState!);
addTearDown(context.dispose);
final TestImageProvider testImageProvider = TestImageProvider(testImage.clone());
final ScrollAwareImageProvider<TestImageProvider> imageProvider = ScrollAwareImageProvider<TestImageProvider>(
context: context,
imageProvider: testImageProvider,
);
expect(testImageProvider.configuration, null);
expect(imageCache.containsKey(testImageProvider), false);
final ControllablePhysics physics = findPhysics<ControllablePhysics>(tester);
physics.recommendDeferredLoadingValue = true;
final ImageStream stream = imageProvider.resolve(ImageConfiguration.empty);
expect(testImageProvider.configuration, null);
expect(stream.completer, null);
expect(imageCache.currentSize, 0);
// Occupy the only slot in the cache with another image.
final TestImageProvider testImageProvider2 = TestImageProvider(testImage.clone());
testImageProvider2.complete();
await precacheImage(testImageProvider2, context.context!);
expect(imageCache.containsKey(testImageProvider), false);
expect(imageCache.containsKey(testImageProvider2), true);
expect(imageCache.currentSize, 1);
// Complete the original image while we're still scrolling fast.
testImageProvider.complete();
stream.setCompleter(testImageProvider.loadImage(testImageProvider, PaintingBinding.instance.instantiateImageCodecWithSize));
// Verify that this hasn't changed the cache state yet
expect(imageCache.containsKey(testImageProvider), false);
expect(imageCache.containsKey(testImageProvider2), true);
expect(imageCache.currentSize, 1);
expect(testImageProvider.loadCallCount, 1);
await tester.pump();
// After pumping a frame, the original image should be in the cache because
// it took the LRU slot.
expect(imageCache.containsKey(testImageProvider), true);
expect(imageCache.containsKey(testImageProvider2), false);
expect(imageCache.currentSize, 1);
expect(testImageProvider.loadCallCount, 1);
imageCache.maximumSize = oldSize;
});
}
class TestWidget extends StatefulWidget {
const TestWidget(Key? key) : super(key: key);
@override
State<TestWidget> createState() => TestWidgetState();
}
class TestWidgetState extends State<TestWidget> {
@override
Widget build(BuildContext context) => const SizedBox(height: 50);
}
class RecordingPhysics extends ScrollPhysics {
RecordingPhysics({ super.parent });
final List<double> velocities = <double>[];
@override
RecordingPhysics applyTo(ScrollPhysics? ancestor) {
return RecordingPhysics(parent: buildParent(ancestor));
}
@override
bool recommendDeferredLoading(double velocity, ScrollMetrics metrics, BuildContext context) {
velocities.add(velocity);
return super.recommendDeferredLoading(velocity, metrics, context);
}
}
// Ignore this so that we can mutate whether we defer loading or not at specific
// times without worrying about actual scrolling mechanics.
// ignore: must_be_immutable
class ControllablePhysics extends ScrollPhysics {
ControllablePhysics({ super.parent });
bool recommendDeferredLoadingValue = false;
@override
ControllablePhysics applyTo(ScrollPhysics? ancestor) {
return ControllablePhysics(parent: buildParent(ancestor));
}
@override
bool recommendDeferredLoading(double velocity, ScrollMetrics metrics, BuildContext context) {
return recommendDeferredLoadingValue;
}
}
| flutter/packages/flutter/test/widgets/scroll_aware_image_provider_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/scroll_aware_image_provider_test.dart",
"repo_id": "flutter",
"token_count": 5594
} | 874 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart' show DragStartBehavior;
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
const List<int> items = <int>[0, 1, 2, 3, 4, 5];
void main() {
testWidgets('Tap item after scroll - horizontal', (WidgetTester tester) async {
final List<int> tapped = <int>[];
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 50.0,
child: ListView(
dragStartBehavior: DragStartBehavior.down,
itemExtent: 290.0,
scrollDirection: Axis.horizontal,
children: items.map<Widget>((int item) {
return GestureDetector(
onTap: () { tapped.add(item); },
dragStartBehavior: DragStartBehavior.down,
child: Text('$item'),
);
}).toList(),
),
),
),
),
);
await tester.drag(find.text('2'), const Offset(-280.0, 0.0));
await tester.pump(const Duration(seconds: 1));
// screen is 800px wide, and has the following items:
// -280..10 = 0
// 10..300 = 1
// 300..590 = 2
// 590..880 = 3
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
expect(tapped, equals(<int>[]));
await tester.tap(find.text('2'));
expect(tapped, equals(<int>[2]));
});
testWidgets('Tap item after scroll - vertical', (WidgetTester tester) async {
final List<int> tapped = <int>[];
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 50.0,
child: ListView(
dragStartBehavior: DragStartBehavior.down,
itemExtent: 290.0,
children: items.map<Widget>((int item) {
return GestureDetector(
onTap: () { tapped.add(item); },
dragStartBehavior: DragStartBehavior.down,
child: Text('$item'),
);
}).toList(),
),
),
),
),
);
await tester.drag(find.text('1'), const Offset(0.0, -280.0));
await tester.pump(const Duration(seconds: 1));
// screen is 600px tall, and has the following items:
// -280..10 = 0
// 10..300 = 1
// 300..590 = 2
// 590..880 = 3
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
expect(tapped, equals(<int>[]));
await tester.tap(find.text('1'));
expect(tapped, equals(<int>[1]));
await tester.tap(find.text('3'), warnIfMissed: false);
expect(tapped, equals(<int>[1])); // the center of the third item is off-screen so it shouldn't get hit
});
testWidgets('Padding scroll anchor start', (WidgetTester tester) async {
final List<int> tapped = <int>[];
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
itemExtent: 290.0,
padding: const EdgeInsets.fromLTRB(5.0, 20.0, 15.0, 10.0),
children: items.map<Widget>((int item) {
return GestureDetector(
onTap: () { tapped.add(item); },
child: Text('$item'),
);
}).toList(),
),
),
);
await tester.tapAt(const Offset(200.0, 19.0));
expect(tapped, equals(<int>[]));
await tester.tapAt(const Offset(200.0, 21.0));
expect(tapped, equals(<int>[0]));
await tester.tapAt(const Offset(4.0, 400.0));
expect(tapped, equals(<int>[0]));
await tester.tapAt(const Offset(6.0, 400.0));
expect(tapped, equals(<int>[0, 1]));
await tester.tapAt(const Offset(800.0 - 14.0, 400.0));
expect(tapped, equals(<int>[0, 1]));
await tester.tapAt(const Offset(800.0 - 16.0, 400.0));
expect(tapped, equals(<int>[0, 1, 1]));
});
testWidgets('Padding scroll anchor end', (WidgetTester tester) async {
final List<int> tapped = <int>[];
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
itemExtent: 290.0,
reverse: true,
padding: const EdgeInsets.fromLTRB(5.0, 20.0, 15.0, 10.0),
children: items.map<Widget>((int item) {
return GestureDetector(
onTap: () { tapped.add(item); },
child: Text('$item'),
);
}).toList(),
),
),
);
await tester.tapAt(const Offset(200.0, 600.0 - 9.0));
expect(tapped, equals(<int>[]));
await tester.tapAt(const Offset(200.0, 600.0 - 11.0));
expect(tapped, equals(<int>[0]));
await tester.tapAt(const Offset(4.0, 200.0));
expect(tapped, equals(<int>[0]));
await tester.tapAt(const Offset(6.0, 200.0));
expect(tapped, equals(<int>[0, 1]));
await tester.tapAt(const Offset(800.0 - 14.0, 200.0));
expect(tapped, equals(<int>[0, 1]));
await tester.tapAt(const Offset(800.0 - 16.0, 200.0));
expect(tapped, equals(<int>[0, 1, 1]));
});
testWidgets('Tap immediately following clamped overscroll', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/5709
final List<int> tapped = <int>[];
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
itemExtent: 200.0,
children: items.map<Widget>((int item) {
return GestureDetector(
onTap: () { tapped.add(item); },
child: Text('$item'),
);
}).toList(),
),
),
);
await tester.fling(find.text('0'), const Offset(0.0, 400.0), 1000.0);
final ScrollableState scrollable = tester.state(find.byType(Scrollable));
expect(scrollable.position.pixels, equals(0.0));
await tester.tapAt(const Offset(200.0, 100.0));
expect(tapped, equals(<int>[0]));
});
}
| flutter/packages/flutter/test/widgets/scrollable_list_hit_testing_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/scrollable_list_hit_testing_test.dart",
"repo_id": "flutter",
"token_count": 3035
} | 875 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
void main() {
testWidgets('Semantics 3', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
// implicit annotators
await tester.pumpWidget(
Semantics(
container: true,
child: Semantics(
label: 'test',
textDirection: TextDirection.ltr,
child: Semantics(
checked: true,
),
),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index,
label: 'test',
rect: TestSemantics.fullScreen,
),
],
),
));
// remove one
await tester.pumpWidget(
Semantics(
container: true,
child: Semantics(
checked: true,
),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index,
rect: TestSemantics.fullScreen,
),
],
),
));
// change what it says
await tester.pumpWidget(
Semantics(
container: true,
child: Semantics(
label: 'test',
textDirection: TextDirection.ltr,
),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
label: 'test',
textDirection: TextDirection.ltr,
rect: TestSemantics.fullScreen,
),
],
),
));
// add a node
await tester.pumpWidget(
Semantics(
container: true,
child: Semantics(
checked: true,
child: Semantics(
label: 'test',
textDirection: TextDirection.ltr,
),
),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
flags: SemanticsFlag.hasCheckedState.index | SemanticsFlag.isChecked.index,
label: 'test',
rect: TestSemantics.fullScreen,
),
],
),
));
int changeCount = 0;
tester.binding.pipelineOwner.semanticsOwner!.addListener(() {
changeCount += 1;
});
// make no changes
await tester.pumpWidget(
Semantics(
container: true,
child: Semantics(
checked: true,
child: Semantics(
label: 'test',
textDirection: TextDirection.ltr,
),
),
),
);
expect(changeCount, 0);
semantics.dispose();
});
}
| flutter/packages/flutter/test/widgets/semantics_3_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/semantics_3_test.dart",
"repo_id": "flutter",
"token_count": 1566
} | 876 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
void main() {
testWidgets('Semantics tester visits last child', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
const TextStyle textStyle = TextStyle();
final TapGestureRecognizer recognizer = TapGestureRecognizer();
addTearDown(recognizer.dispose);
await tester.pumpWidget(
Text.rich(
TextSpan(
children: <TextSpan>[
const TextSpan(text: 'hello'),
TextSpan(text: 'world', recognizer: recognizer..onTap = () { }),
],
style: textStyle,
),
textDirection: TextDirection.ltr,
maxLines: 1,
),
);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
children: <TestSemantics>[
TestSemantics(
label: 'hello',
textDirection: TextDirection.ltr,
),
TestSemantics(),
],
),
],
);
expect(semantics, isNot(hasSemantics(expectedSemantics, ignoreTransform: true, ignoreId: true, ignoreRect: true)));
semantics.dispose();
});
}
| flutter/packages/flutter/test/widgets/semantics_tester_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/semantics_tester_test.dart",
"repo_id": "flutter",
"token_count": 622
} | 877 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('SizeChangedLayoutNotification test', (WidgetTester tester) async {
bool notified = false;
await tester.pumpWidget(
Center(
child: NotificationListener<LayoutChangedNotification>(
onNotification: (LayoutChangedNotification notification) {
throw Exception('Should not reach this point.');
},
child: const SizeChangedLayoutNotifier(
child: SizedBox(
width: 100.0,
height: 100.0,
),
),
),
),
);
await tester.pumpWidget(
Center(
child: NotificationListener<LayoutChangedNotification>(
onNotification: (LayoutChangedNotification notification) {
expect(notification, isA<SizeChangedLayoutNotification>());
notified = true;
return true;
},
child: const SizeChangedLayoutNotifier(
child: SizedBox(
width: 200.0,
height: 100.0,
),
),
),
),
);
expect(notified, isTrue);
});
}
| flutter/packages/flutter/test/widgets/size_changed_layout_notification_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/size_changed_layout_notification_test.dart",
"repo_id": "flutter",
"token_count": 595
} | 878 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void verifyPaintPosition(GlobalKey key, Offset ideal, bool visible) {
final RenderSliver target = key.currentContext!.findRenderObject()! as RenderSliver;
expect(target.parent, isA<RenderViewport>());
final SliverPhysicalParentData parentData = target.parentData! as SliverPhysicalParentData;
final Offset actual = parentData.paintOffset;
expect(actual, ideal);
final SliverGeometry geometry = target.geometry!;
expect(geometry.visible, visible);
}
void verifyActualBoxPosition(WidgetTester tester, Finder finder, int index, Rect ideal) {
final RenderBox box = tester.renderObjectList<RenderBox>(finder).elementAt(index);
final Rect rect = Rect.fromPoints(box.localToGlobal(Offset.zero), box.localToGlobal(box.size.bottomRight(Offset.zero)));
expect(rect, equals(ideal));
}
void main() {
testWidgets('Sliver appbars - pinned', (WidgetTester tester) async {
const double bigHeight = 550.0;
GlobalKey key1, key2, key3, key4, key5;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
slivers: <Widget>[
BigSliver(key: key1 = GlobalKey(), height: bigHeight),
SliverPersistentHeader(key: key2 = GlobalKey(), delegate: TestDelegate(), pinned: true),
SliverPersistentHeader(key: key3 = GlobalKey(), delegate: TestDelegate(), pinned: true),
BigSliver(key: key4 = GlobalKey(), height: bigHeight),
BigSliver(key: key5 = GlobalKey(), height: bigHeight),
],
),
),
);
final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position;
final double max = bigHeight * 3.0 + TestDelegate().maxExtent * 2.0 - 600.0; // 600 is the height of the test viewport
assert(max < 10000.0);
expect(max, 1450.0);
expect(position.pixels, 0.0);
expect(position.minScrollExtent, 0.0);
expect(position.maxScrollExtent, max);
position.animateTo(10000.0, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 10));
expect(position.pixels, max);
expect(position.minScrollExtent, 0.0);
expect(position.maxScrollExtent, max);
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, true);
verifyPaintPosition(key3, const Offset(0.0, 100.0), true);
verifyPaintPosition(key4, Offset.zero, true);
verifyPaintPosition(key5, const Offset(0.0, 50.0), true);
});
testWidgets('Sliver appbars - toStringDeep of maxExtent that throws', (WidgetTester tester) async {
final TestDelegateThatCanThrow delegateThatCanThrow = TestDelegateThatCanThrow();
GlobalKey key;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
slivers: <Widget>[
SliverPersistentHeader(key: key = GlobalKey(), delegate: delegateThatCanThrow, pinned: true),
],
),
),
);
await tester.pumpAndSettle(const Duration(milliseconds: 10));
final RenderObject renderObject = key.currentContext!.findRenderObject()!;
// The delegate must only start throwing immediately before calling
// toStringDeep to avoid triggering spurious exceptions.
// If the _RenderSliverPinnedPersistentHeaderForWidgets class was not
// private it would make more sense to create an instance of it directly.
delegateThatCanThrow.shouldThrow = true;
expect(renderObject, hasAGoodToStringDeep);
expect(
renderObject.toStringDeep(minLevel: DiagnosticLevel.info),
equalsIgnoringHashCodes(
'_RenderSliverPinnedPersistentHeaderForWidgets#00000 relayoutBoundary=up1\n'
' │ parentData: paintOffset=Offset(0.0, 0.0) (can use size)\n'
' │ constraints: SliverConstraints(AxisDirection.down,\n'
' │ GrowthDirection.forward, ScrollDirection.idle, scrollOffset:\n'
' │ 0.0, precedingScrollExtent: 0.0, remainingPaintExtent: 600.0,\n'
' │ crossAxisExtent: 800.0, crossAxisDirection:\n'
' │ AxisDirection.right, viewportMainAxisExtent: 600.0,\n'
' │ remainingCacheExtent: 850.0, cacheOrigin: 0.0)\n'
' │ geometry: SliverGeometry(scrollExtent: 200.0, paintExtent: 200.0,\n'
' │ maxPaintExtent: 200.0, hasVisualOverflow: true, cacheExtent:\n'
' │ 200.0)\n'
' │ maxExtent: EXCEPTION (FlutterError)\n'
' │ child position: 0.0\n'
' │\n'
' └─child: RenderConstrainedBox#00000 relayoutBoundary=up2\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, 0.0<=h<=200.0)\n'
' │ size: Size(800.0, 200.0)\n'
' │ additionalConstraints: BoxConstraints(0.0<=w<=Infinity,\n'
' │ 100.0<=h<=200.0)\n'
' │\n'
' └─child: RenderLimitedBox#00000 relayoutBoundary=up3\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=800.0, 100.0<=h<=200.0)\n'
' │ size: Size(800.0, 200.0)\n'
' │ maxWidth: 0.0\n'
' │ maxHeight: 0.0\n'
' │\n'
' └─child: RenderConstrainedBox#00000 relayoutBoundary=up4\n'
' parentData: <none> (can use size)\n'
' constraints: BoxConstraints(w=800.0, 100.0<=h<=200.0)\n'
' size: Size(800.0, 200.0)\n'
' additionalConstraints: BoxConstraints(biggest)\n',
),
);
});
testWidgets('Sliver appbars - pinned with slow scroll', (WidgetTester tester) async {
const double bigHeight = 550.0;
GlobalKey key1, key2, key3, key4, key5;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
slivers: <Widget>[
BigSliver(key: key1 = GlobalKey(), height: bigHeight),
SliverPersistentHeader(key: key2 = GlobalKey(), delegate: TestDelegate(), pinned: true),
SliverPersistentHeader(key: key3 = GlobalKey(), delegate: TestDelegate(), pinned: true),
BigSliver(key: key4 = GlobalKey(), height: bigHeight),
BigSliver(key: key5 = GlobalKey(), height: bigHeight),
],
),
),
);
final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position;
verifyPaintPosition(key1, Offset.zero, true);
verifyPaintPosition(key2, const Offset(0.0, 550.0), true);
verifyPaintPosition(key3, const Offset(0.0, 750.0), false);
verifyPaintPosition(key4, const Offset(0.0, 950.0), false);
verifyPaintPosition(key5, const Offset(0.0, 1500.0), false);
position.animateTo(550.0, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle();
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, true);
verifyPaintPosition(key3, const Offset(0.0, 200.0), true);
verifyPaintPosition(key4, const Offset(0.0, 400.0), true);
verifyPaintPosition(key5, const Offset(0.0, 950.0), false);
position.animateTo(600.0, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 200));
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, true);
verifyPaintPosition(key3, const Offset(0.0, 150.0), true);
verifyPaintPosition(key4, const Offset(0.0, 350.0), true);
verifyPaintPosition(key5, const Offset(0.0, 900.0), false);
position.animateTo(650.0, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 300));
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, true);
verifyPaintPosition(key3, const Offset(0.0, 100.0), true);
verifyActualBoxPosition(tester, find.byType(Container), 1, const Rect.fromLTWH(0.0, 100.0, 800.0, 200.0));
verifyPaintPosition(key4, const Offset(0.0, 300.0), true);
verifyPaintPosition(key5, const Offset(0.0, 850.0), false);
position.animateTo(700.0, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 400));
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, true);
verifyPaintPosition(key3, const Offset(0.0, 100.0), true);
verifyActualBoxPosition(tester, find.byType(Container), 1, const Rect.fromLTWH(0.0, 100.0, 800.0, 200.0));
verifyPaintPosition(key4, const Offset(0.0, 250.0), true);
verifyPaintPosition(key5, const Offset(0.0, 800.0), false);
position.animateTo(750.0, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 500));
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, true);
verifyPaintPosition(key3, const Offset(0.0, 100.0), true);
verifyActualBoxPosition(tester, find.byType(Container), 1, const Rect.fromLTWH(0.0, 100.0, 800.0, 200.0));
verifyPaintPosition(key4, const Offset(0.0, 200.0), true);
verifyPaintPosition(key5, const Offset(0.0, 750.0), false);
position.animateTo(800.0, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 60));
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, true);
verifyPaintPosition(key3, const Offset(0.0, 100.0), true);
verifyPaintPosition(key4, const Offset(0.0, 150.0), true);
verifyPaintPosition(key5, const Offset(0.0, 700.0), false);
position.animateTo(850.0, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 70));
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, true);
verifyPaintPosition(key3, const Offset(0.0, 100.0), true);
verifyPaintPosition(key4, const Offset(0.0, 100.0), true);
verifyPaintPosition(key5, const Offset(0.0, 650.0), false);
position.animateTo(900.0, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 80));
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, true);
verifyPaintPosition(key3, const Offset(0.0, 100.0), true);
verifyPaintPosition(key4, const Offset(0.0, 50.0), true);
verifyPaintPosition(key5, const Offset(0.0, 600.0), false);
position.animateTo(950.0, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 90));
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, true);
verifyPaintPosition(key3, const Offset(0.0, 100.0), true);
verifyActualBoxPosition(tester, find.byType(Container), 1, const Rect.fromLTWH(0.0, 100.0, 800.0, 100.0));
verifyPaintPosition(key4, Offset.zero, true);
verifyPaintPosition(key5, const Offset(0.0, 550.0), true);
});
testWidgets('Sliver appbars - pinned with less overlap', (WidgetTester tester) async {
const double bigHeight = 650.0;
GlobalKey key1, key2, key3, key4, key5;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
slivers: <Widget>[
BigSliver(key: key1 = GlobalKey(), height: bigHeight),
SliverPersistentHeader(key: key2 = GlobalKey(), delegate: TestDelegate(), pinned: true),
SliverPersistentHeader(key: key3 = GlobalKey(), delegate: TestDelegate(), pinned: true),
BigSliver(key: key4 = GlobalKey(), height: bigHeight),
BigSliver(key: key5 = GlobalKey(), height: bigHeight),
],
),
),
);
final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position;
final double max = bigHeight * 3.0 + TestDelegate().maxExtent * 2.0 - 600.0; // 600 is the height of the test viewport
assert(max < 10000.0);
expect(max, 1750.0);
expect(position.pixels, 0.0);
expect(position.minScrollExtent, 0.0);
expect(position.maxScrollExtent, max);
position.animateTo(10000.0, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 10));
expect(position.pixels, max);
expect(position.minScrollExtent, 0.0);
expect(position.maxScrollExtent, max);
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, true);
verifyPaintPosition(key3, const Offset(0.0, 100.0), true);
verifyPaintPosition(key4, Offset.zero, false);
verifyPaintPosition(key5, Offset.zero, true);
});
testWidgets('Sliver appbars - overscroll gap is below header', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
physics: const BouncingScrollPhysics(),
slivers: <Widget>[
SliverPersistentHeader(delegate: TestDelegate(), pinned: true),
SliverList(
delegate: SliverChildListDelegate(<Widget>[
const SizedBox(
height: 300.0,
child: Text('X'),
),
]),
),
],
),
),
);
expect(tester.getTopLeft(find.byType(Container)), Offset.zero);
expect(tester.getTopLeft(find.text('X')), const Offset(0.0, 200.0));
final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position;
position.jumpTo(-50.0);
await tester.pump();
expect(tester.getTopLeft(find.byType(Container)), Offset.zero);
expect(tester.getTopLeft(find.text('X')), const Offset(0.0, 250.0));
position.jumpTo(50.0);
await tester.pump();
expect(tester.getTopLeft(find.byType(Container)), Offset.zero);
expect(tester.getTopLeft(find.text('X')), const Offset(0.0, 150.0));
position.jumpTo(150.0);
await tester.pump();
expect(tester.getTopLeft(find.byType(Container)), Offset.zero);
expect(tester.getTopLeft(find.text('X')), const Offset(0.0, 50.0));
});
}
class TestDelegate extends SliverPersistentHeaderDelegate {
@override
double get maxExtent => 200.0;
@override
double get minExtent => 100.0;
@override
Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
return Container(constraints: BoxConstraints(minHeight: minExtent, maxHeight: maxExtent));
}
@override
bool shouldRebuild(TestDelegate oldDelegate) => false;
}
class TestDelegateThatCanThrow extends SliverPersistentHeaderDelegate {
bool shouldThrow = false;
@override
double get maxExtent {
return shouldThrow ? throw FlutterError('Unavailable maxExtent') : 200.0;
}
@override
double get minExtent {
return shouldThrow ? throw FlutterError('Unavailable minExtent') : 100.0;
}
@override
Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
return Container(constraints: BoxConstraints(minHeight: minExtent, maxHeight: maxExtent));
}
@override
bool shouldRebuild(TestDelegate oldDelegate) => false;
}
class RenderBigSliver extends RenderSliver {
RenderBigSliver(double height) : _height = height;
double get height => _height;
double _height;
set height(double value) {
if (value == _height) {
return;
}
_height = value;
markNeedsLayout();
}
double get paintExtent => (height - constraints.scrollOffset).clamp(0.0, constraints.remainingPaintExtent);
@override
void performLayout() {
geometry = SliverGeometry(
scrollExtent: height,
paintExtent: paintExtent,
maxPaintExtent: height,
);
}
}
class BigSliver extends LeafRenderObjectWidget {
const BigSliver({ super.key, required this.height });
final double height;
@override
RenderBigSliver createRenderObject(BuildContext context) {
return RenderBigSliver(height);
}
@override
void updateRenderObject(BuildContext context, RenderBigSliver renderObject) {
renderObject.height = height;
}
}
| flutter/packages/flutter/test/widgets/slivers_appbar_pinned_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/slivers_appbar_pinned_test.dart",
"repo_id": "flutter",
"token_count": 6484
} | 879 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'test_widgets.dart';
void main() {
testWidgets('Stateful widget smoke test', (WidgetTester tester) async {
void checkTree(BoxDecoration expectedDecoration) {
final SingleChildRenderObjectElement element = tester.element(
find.byElementPredicate((Element element) => element is SingleChildRenderObjectElement && element.renderObject is! RenderView),
);
expect(element, isNotNull);
expect(element.renderObject, isA<RenderDecoratedBox>());
final RenderDecoratedBox renderObject = element.renderObject as RenderDecoratedBox;
expect(renderObject.decoration, equals(expectedDecoration));
}
await tester.pumpWidget(
const FlipWidget(
left: DecoratedBox(decoration: kBoxDecorationA),
right: DecoratedBox(decoration: kBoxDecorationB),
),
);
checkTree(kBoxDecorationA);
await tester.pumpWidget(
const FlipWidget(
left: DecoratedBox(decoration: kBoxDecorationB),
right: DecoratedBox(decoration: kBoxDecorationA),
),
);
checkTree(kBoxDecorationB);
flipStatefulWidget(tester);
await tester.pump();
checkTree(kBoxDecorationA);
await tester.pumpWidget(
const FlipWidget(
left: DecoratedBox(decoration: kBoxDecorationA),
right: DecoratedBox(decoration: kBoxDecorationB),
),
);
checkTree(kBoxDecorationB);
});
testWidgets("Don't rebuild subwidgets", (WidgetTester tester) async {
await tester.pumpWidget(
const FlipWidget(
key: Key('rebuild test'),
left: TestBuildCounter(),
right: DecoratedBox(decoration: kBoxDecorationB),
),
);
expect(TestBuildCounter.buildCount, equals(1));
flipStatefulWidget(tester);
await tester.pump();
expect(TestBuildCounter.buildCount, equals(1));
});
}
| flutter/packages/flutter/test/widgets/stateful_component_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/stateful_component_test.dart",
"repo_id": "flutter",
"token_count": 791
} | 880 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Texture with freeze set to true', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(child: Texture(textureId: 1, freeze: true)),
);
final Texture texture = tester.firstWidget(find.byType(Texture));
expect(texture, isNotNull);
expect(texture.textureId, 1);
expect(texture.freeze, true);
final RenderObject renderObject = tester.firstRenderObject(find.byType(Texture));
expect(renderObject, isNotNull);
final TextureBox textureBox = renderObject as TextureBox;
expect(textureBox, isNotNull);
expect(textureBox.textureId, 1);
expect(textureBox.freeze, true);
final ContainerLayer containerLayer = ContainerLayer();
addTearDown(containerLayer.dispose);
final PaintingContext paintingContext = PaintingContext(containerLayer, Rect.zero);
textureBox.paint(paintingContext, Offset.zero);
final Layer layer = containerLayer.lastChild!;
expect(layer, isNotNull);
final TextureLayer textureLayer = layer as TextureLayer;
expect(textureLayer, isNotNull);
expect(textureLayer.textureId, 1);
expect(textureLayer.freeze, true);
});
testWidgets('Texture with default FilterQuality', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(child: Texture(textureId: 1)),
);
final Texture texture = tester.firstWidget(find.byType(Texture));
expect(texture, isNotNull);
expect(texture.textureId, 1);
expect(texture.filterQuality, FilterQuality.low);
final RenderObject renderObject = tester.firstRenderObject(find.byType(Texture));
expect(renderObject, isNotNull);
final TextureBox textureBox = renderObject as TextureBox;
expect(textureBox, isNotNull);
expect(textureBox.textureId, 1);
expect(textureBox.filterQuality, FilterQuality.low);
final ContainerLayer containerLayer = ContainerLayer();
addTearDown(containerLayer.dispose);
final PaintingContext paintingContext = PaintingContext(containerLayer, Rect.zero);
textureBox.paint(paintingContext, Offset.zero);
final Layer layer = containerLayer.lastChild!;
expect(layer, isNotNull);
final TextureLayer textureLayer = layer as TextureLayer;
expect(textureLayer, isNotNull);
expect(textureLayer.textureId, 1);
expect(textureLayer.filterQuality, FilterQuality.low);
});
testWidgets('Texture with FilterQuality.none', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(child: Texture(textureId: 1, filterQuality: FilterQuality.none)),
);
final Texture texture = tester.firstWidget(find.byType(Texture));
expect(texture, isNotNull);
expect(texture.textureId, 1);
expect(texture.filterQuality, FilterQuality.none);
final RenderObject renderObject = tester.firstRenderObject(find.byType(Texture));
expect(renderObject, isNotNull);
final TextureBox textureBox = renderObject as TextureBox;
expect(textureBox, isNotNull);
expect(textureBox.textureId, 1);
expect(textureBox.filterQuality, FilterQuality.none);
final ContainerLayer containerLayer = ContainerLayer();
addTearDown(containerLayer.dispose);
final PaintingContext paintingContext = PaintingContext(containerLayer, Rect.zero);
textureBox.paint(paintingContext, Offset.zero);
final Layer layer = containerLayer.lastChild!;
expect(layer, isNotNull);
final TextureLayer textureLayer = layer as TextureLayer;
expect(textureLayer, isNotNull);
expect(textureLayer.textureId, 1);
expect(textureLayer.filterQuality, FilterQuality.none);
});
testWidgets('Texture with FilterQuality.low', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(child: Texture(textureId: 1)),
);
final Texture texture = tester.firstWidget(find.byType(Texture));
expect(texture, isNotNull);
expect(texture.textureId, 1);
expect(texture.filterQuality, FilterQuality.low);
final RenderObject renderObject = tester.firstRenderObject(find.byType(Texture));
expect(renderObject, isNotNull);
final TextureBox textureBox = renderObject as TextureBox;
expect(textureBox, isNotNull);
expect(textureBox.textureId, 1);
expect(textureBox.filterQuality, FilterQuality.low);
final ContainerLayer containerLayer = ContainerLayer();
addTearDown(containerLayer.dispose);
final PaintingContext paintingContext = PaintingContext(containerLayer, Rect.zero);
textureBox.paint(paintingContext, Offset.zero);
final Layer layer = containerLayer.lastChild!;
expect(layer, isNotNull);
final TextureLayer textureLayer = layer as TextureLayer;
expect(textureLayer, isNotNull);
expect(textureLayer.textureId, 1);
expect(textureLayer.filterQuality, FilterQuality.low);
});
}
| flutter/packages/flutter/test/widgets/texture_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/texture_test.dart",
"repo_id": "flutter",
"token_count": 1599
} | 881 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'multi_view_testing.dart';
void main() {
testWidgets('Widgets running with runApp can find View', (WidgetTester tester) async {
FlutterView? viewOf;
FlutterView? viewMaybeOf;
runApp(
Builder(
builder: (BuildContext context) {
viewOf = View.of(context);
viewMaybeOf = View.maybeOf(context);
return Container();
},
),
);
expect(viewOf, isNotNull);
expect(viewOf, isA<FlutterView>());
expect(viewMaybeOf, isNotNull);
expect(viewMaybeOf, isA<FlutterView>());
});
testWidgets('Widgets running with pumpWidget can find View', (WidgetTester tester) async {
FlutterView? view;
FlutterView? viewMaybeOf;
await tester.pumpWidget(
Builder(
builder: (BuildContext context) {
view = View.of(context);
viewMaybeOf = View.maybeOf(context);
return Container();
},
),
);
expect(view, isNotNull);
expect(view, isA<FlutterView>());
expect(viewMaybeOf, isNotNull);
expect(viewMaybeOf, isA<FlutterView>());
});
testWidgets('cannot find View behind a LookupBoundary', (WidgetTester tester) async {
await tester.pumpWidget(
LookupBoundary(
child: Container(),
),
);
final BuildContext context = tester.element(find.byType(Container));
expect(View.maybeOf(context), isNull);
expect(
() => View.of(context),
throwsA(isA<FlutterError>().having(
(FlutterError error) => error.message,
'message',
contains('The context provided to View.of() does have a View widget ancestor, but it is hidden by a LookupBoundary.'),
)),
);
});
testWidgets('child of view finds view, parentPipelineOwner, mediaQuery', (WidgetTester tester) async {
FlutterView? outsideView;
FlutterView? insideView;
PipelineOwner? outsideParent;
PipelineOwner? insideParent;
await tester.pumpWidget(
wrapWithView: false,
Builder(
builder: (BuildContext context) {
outsideView = View.maybeOf(context);
outsideParent = View.pipelineOwnerOf(context);
return View(
view: tester.view,
child: Builder(
builder: (BuildContext context) {
insideView = View.maybeOf(context);
insideParent = View.pipelineOwnerOf(context);
return const SizedBox();
},
),
);
},
),
);
expect(outsideView, isNull);
expect(insideView, equals(tester.view));
expect(outsideParent, isNotNull);
expect(insideParent, isNotNull);
expect(outsideParent, isNot(equals(insideParent)));
expect(outsideParent, tester.binding.rootPipelineOwner);
expect(insideParent, equals(tester.renderObject(find.byType(SizedBox)).owner));
final List<PipelineOwner> pipelineOwners = <PipelineOwner> [];
tester.binding.rootPipelineOwner.visitChildren((PipelineOwner child) {
pipelineOwners.add(child);
});
expect(pipelineOwners.single, equals(insideParent));
});
testWidgets('cannot have multiple views with same FlutterView', (WidgetTester tester) async {
await tester.pumpWidget(
wrapWithView: false,
ViewCollection(
views: <Widget>[
View(
view: tester.view,
child: const SizedBox(),
),
View(
view: tester.view,
child: const SizedBox(),
),
],
),
);
expect(
tester.takeException(),
isFlutterError.having(
(FlutterError e) => e.message,
'message',
contains('Multiple widgets used the same GlobalKey'),
),
);
});
testWidgets('ViewCollection may start with zero views', (WidgetTester tester) async {
expect(() => const ViewCollection(views: <Widget>[]), returnsNormally);
});
testWidgets('ViewAnchor.child does not see surrounding view', (WidgetTester tester) async {
FlutterView? inside;
FlutterView? outside;
await tester.pumpWidget(
Builder(
builder: (BuildContext context) {
outside = View.maybeOf(context);
return ViewAnchor(
view: Builder(
builder: (BuildContext context) {
inside = View.maybeOf(context);
return View(view: FakeView(tester.view), child: const SizedBox());
},
),
child: const SizedBox(),
);
},
),
);
expect(inside, isNull);
expect(outside, isNotNull);
});
testWidgets('ViewAnchor layout order', (WidgetTester tester) async {
Finder findSpyWidget(int label) {
return find.byWidgetPredicate((Widget w) => w is SpyRenderWidget && w.label == label);
}
final List<String> log = <String>[];
await tester.pumpWidget(
SpyRenderWidget(
label: 1,
log: log,
child: ViewAnchor(
view: View(
view: FakeView(tester.view),
child: SpyRenderWidget(label: 2, log: log),
),
child: SpyRenderWidget(label: 3, log: log),
),
),
);
log.clear();
tester.renderObject(findSpyWidget(3)).markNeedsLayout();
tester.renderObject(findSpyWidget(2)).markNeedsLayout();
tester.renderObject(findSpyWidget(1)).markNeedsLayout();
await tester.pump();
expect(log, <String>['layout 1', 'layout 3', 'layout 2']);
});
testWidgets('visitChildren of ViewAnchor visits both children', (WidgetTester tester) async {
await tester.pumpWidget(
ViewAnchor(
view: View(
view: FakeView(tester.view),
child: const ColoredBox(color: Colors.green),
),
child: const SizedBox(),
),
);
final Element viewAnchorElement = tester.element(find.byElementPredicate((Element e) => e.runtimeType.toString() == '_MultiChildComponentElement'));
final List<Element> children = <Element>[];
viewAnchorElement.visitChildren((Element element) {
children.add(element);
});
expect(children, hasLength(2));
await tester.pumpWidget(
const ViewAnchor(
child: SizedBox(),
),
);
children.clear();
viewAnchorElement.visitChildren((Element element) {
children.add(element);
});
expect(children, hasLength(1));
});
testWidgets('visitChildren of ViewCollection visits all children', (WidgetTester tester) async {
await tester.pumpWidget(
wrapWithView: false,
ViewCollection(
views: <Widget>[
View(
view: tester.view,
child: const SizedBox(),
),
View(
view: FakeView(tester.view),
child: const SizedBox(),
),
View(
view: FakeView(tester.view, viewId: 423),
child: const SizedBox(),
),
],
),
);
final Element viewAnchorElement = tester.element(find.byElementPredicate((Element e) => e.runtimeType.toString() == '_MultiChildComponentElement'));
final List<Element> children = <Element>[];
viewAnchorElement.visitChildren((Element element) {
children.add(element);
});
expect(children, hasLength(3));
await tester.pumpWidget(
wrapWithView: false,
ViewCollection(
views: <Widget>[
View(
view: tester.view,
child: const SizedBox(),
),
],
),
);
children.clear();
viewAnchorElement.visitChildren((Element element) {
children.add(element);
});
expect(children, hasLength(1));
});
group('renderObject getter', () {
testWidgets('ancestors of view see RenderView as renderObject', (WidgetTester tester) async {
late BuildContext builderContext;
await tester.pumpWidget(
wrapWithView: false,
Builder(
builder: (BuildContext context) {
builderContext = context;
return View(
view: tester.view,
child: const SizedBox(),
);
},
),
);
final RenderObject? renderObject = builderContext.findRenderObject();
expect(renderObject, isNotNull);
expect(renderObject, isA<RenderView>());
expect(renderObject, tester.renderObject(find.byType(View)));
expect(tester.element(find.byType(Builder)).renderObject, renderObject);
});
testWidgets('ancestors of ViewCollection get null for renderObject', (WidgetTester tester) async {
late BuildContext builderContext;
await tester.pumpWidget(
wrapWithView: false,
Builder(
builder: (BuildContext context) {
builderContext = context;
return ViewCollection(
views: <Widget>[
View(
view: tester.view,
child: const SizedBox(),
),
View(
view: FakeView(tester.view),
child: const SizedBox(),
),
],
);
},
),
);
final RenderObject? renderObject = builderContext.findRenderObject();
expect(renderObject, isNull);
expect(tester.element(find.byType(Builder)).renderObject, isNull);
});
testWidgets('ancestors of a ViewAnchor see the right RenderObject', (WidgetTester tester) async {
late BuildContext builderContext;
await tester.pumpWidget(
Builder(
builder: (BuildContext context) {
builderContext = context;
return ViewAnchor(
view: View(
view: FakeView(tester.view),
child: const ColoredBox(color: Colors.green),
),
child: const SizedBox(),
);
},
),
);
final RenderObject? renderObject = builderContext.findRenderObject();
expect(renderObject, isNotNull);
expect(renderObject, isA<RenderConstrainedBox>());
expect(renderObject, tester.renderObject(find.byType(SizedBox)));
expect(tester.element(find.byType(Builder)).renderObject, renderObject);
});
});
testWidgets('correctly switches between view configurations', (WidgetTester tester) async {
await tester.pumpWidget(
wrapWithView: false,
View(
view: tester.view,
deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner: tester.binding.pipelineOwner,
deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView: tester.binding.renderView,
child: const SizedBox(),
),
);
RenderObject renderView = tester.renderObject(find.byType(View));
expect(renderView, same(tester.binding.renderView));
expect(renderView.owner, same(tester.binding.pipelineOwner));
expect(tester.renderObject(find.byType(SizedBox)).owner, same(tester.binding.pipelineOwner));
await tester.pumpWidget(
wrapWithView: false,
View(
view: tester.view,
child: const SizedBox(),
),
);
renderView = tester.renderObject(find.byType(View));
expect(renderView, isNot(same(tester.binding.renderView)));
expect(renderView.owner, isNot(same(tester.binding.pipelineOwner)));
expect(tester.renderObject(find.byType(SizedBox)).owner, isNot(same(tester.binding.pipelineOwner)));
await tester.pumpWidget(
wrapWithView: false,
View(
view: tester.view,
deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner: tester.binding.pipelineOwner,
deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView: tester.binding.renderView,
child: const SizedBox(),
),
);
renderView = tester.renderObject(find.byType(View));
expect(renderView, same(tester.binding.renderView));
expect(renderView.owner, same(tester.binding.pipelineOwner));
expect(tester.renderObject(find.byType(SizedBox)).owner, same(tester.binding.pipelineOwner));
expect(() => View(
view: tester.view,
deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner: tester.binding.pipelineOwner,
child: const SizedBox(),
), throwsAssertionError);
expect(() => View(
view: tester.view,
deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView: tester.binding.renderView,
child: const SizedBox(),
), throwsAssertionError);
expect(() => View(
view: FakeView(tester.view),
deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView: tester.binding.renderView,
deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner: tester.binding.pipelineOwner,
child: const SizedBox(),
), throwsAssertionError);
});
testWidgets('attaches itself correctly', (WidgetTester tester) async {
final Key viewKey = UniqueKey();
late final PipelineOwner parentPipelineOwner;
await tester.pumpWidget(
ViewAnchor(
view: Builder(
builder: (BuildContext context) {
parentPipelineOwner = View.pipelineOwnerOf(context);
return View(
key: viewKey,
view: FakeView(tester.view),
child: const SizedBox(),
);
},
),
child: const ColoredBox(color: Colors.green),
),
);
expect(parentPipelineOwner, isNot(RendererBinding.instance.rootPipelineOwner));
final RenderView rawView = tester.renderObject<RenderView>(find.byKey(viewKey));
expect(RendererBinding.instance.renderViews, contains(rawView));
final List<PipelineOwner> children = <PipelineOwner>[];
parentPipelineOwner.visitChildren((PipelineOwner child) {
children.add(child);
});
final PipelineOwner rawViewOwner = rawView.owner!;
expect(children, contains(rawViewOwner));
// Remove that View from the tree.
await tester.pumpWidget(
const ViewAnchor(
child: ColoredBox(color: Colors.green),
),
);
expect(rawView.owner, isNull);
expect(RendererBinding.instance.renderViews, isNot(contains(rawView)));
children.clear();
parentPipelineOwner.visitChildren((PipelineOwner child) {
children.add(child);
});
expect(children, isNot(contains(rawViewOwner)));
});
testWidgets('RenderView does not use size of child if constraints are tight', (WidgetTester tester) async {
const Size physicalSize = Size(300, 600);
final Size logicalSize = physicalSize / tester.view.devicePixelRatio;
tester.view.physicalConstraints = ViewConstraints.tight(physicalSize);
await tester.pumpWidget(const Placeholder());
final RenderView renderView = tester.renderObject<RenderView>(find.byType(View));
expect(renderView.constraints, BoxConstraints.tight(logicalSize));
expect(renderView.size, logicalSize);
final RenderBox child = renderView.child!;
expect(child.constraints, BoxConstraints.tight(logicalSize));
expect(child.debugCanParentUseSize, isFalse);
expect(child.size, logicalSize);
});
testWidgets('RenderView sizes itself to child if constraints allow it (unconstrained)', (WidgetTester tester) async {
const Size size = Size(300, 600);
tester.view.physicalConstraints = const ViewConstraints(); // unconstrained
await tester.pumpWidget(SizedBox.fromSize(size: size));
final RenderView renderView = tester.renderObject<RenderView>(find.byType(View));
expect(renderView.constraints, const BoxConstraints());
expect(renderView.size, size);
final RenderBox child = renderView.child!;
expect(child.constraints, const BoxConstraints());
expect(child.debugCanParentUseSize, isTrue);
expect(child.size, size);
});
testWidgets('RenderView sizes itself to child if constraints allow it (constrained)', (WidgetTester tester) async {
const Size size = Size(30, 60);
const ViewConstraints viewConstraints = ViewConstraints(maxWidth: 333, maxHeight: 666);
final BoxConstraints boxConstraints = BoxConstraints.fromViewConstraints(viewConstraints / tester.view.devicePixelRatio);
tester.view.physicalConstraints = viewConstraints;
await tester.pumpWidget(SizedBox.fromSize(size: size));
final RenderView renderView = tester.renderObject<RenderView>(find.byType(View));
expect(renderView.constraints, boxConstraints);
expect(renderView.size, size);
final RenderBox child = renderView.child!;
expect(child.constraints, boxConstraints);
expect(child.debugCanParentUseSize, isTrue);
expect(child.size, size);
});
testWidgets('RenderView respects constraints when child wants to be bigger than allowed', (WidgetTester tester) async {
const Size size = Size(3000, 6000);
const ViewConstraints viewConstraints = ViewConstraints(maxWidth: 300, maxHeight: 600);
tester.view.physicalConstraints = viewConstraints;
await tester.pumpWidget(SizedBox.fromSize(size: size));
final RenderView renderView = tester.renderObject<RenderView>(find.byType(View));
expect(renderView.size, const Size(100, 200)); // viewConstraints.biggest / devicePixelRatio
final RenderBox child = renderView.child!;
expect(child.debugCanParentUseSize, isTrue);
expect(child.size, const Size(100, 200));
});
}
class SpyRenderWidget extends SizedBox {
const SpyRenderWidget({super.key, required this.label, required this.log, super.child});
final int label;
final List<String> log;
@override
RenderSpy createRenderObject(BuildContext context) {
return RenderSpy(
additionalConstraints: const BoxConstraints(),
label: label,
log: log,
);
}
@override
void updateRenderObject(BuildContext context, RenderSpy renderObject) {
renderObject
..label = label
..log = log;
}
}
class RenderSpy extends RenderConstrainedBox {
RenderSpy({required super.additionalConstraints, required this.label, required this.log});
int label;
List<String> log;
@override
void performLayout() {
log.add('layout $label');
super.performLayout();
}
}
| flutter/packages/flutter/test/widgets/view_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/view_test.dart",
"repo_id": "flutter",
"token_count": 7315
} | 882 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart';
void main() {
// Change made in https://github.com/flutter/flutter/pull/28602
final PointerEnterEvent enterEvent = PointerEnterEvent.fromHoverEvent(PointerHoverEvent());
// Change made in https://github.com/flutter/flutter/pull/28602
final PointerExitEvent exitEvent = PointerExitEvent.fromHoverEvent(PointerHoverEvent());
// Changes made in https://github.com/flutter/flutter/pull/66043
VelocityTracker tracker = VelocityTracker();
tracker = VelocityTracker(PointerDeviceKind.mouse);
tracker = VelocityTracker(error: '');
// Changes made in https://github.com/flutter/flutter/pull/81858
DragGestureRecognizer();
DragGestureRecognizer(kind: PointerDeviceKind.touch);
DragGestureRecognizer(error: '');
VerticalDragGestureRecognizer();
VerticalDragGestureRecognizer(kind: PointerDeviceKind.touch);
VerticalDragGestureRecognizer(error: '');
HorizontalDragGestureRecognizer();
HorizontalDragGestureRecognizer(kind: PointerDeviceKind.touch);
HorizontalDragGestureRecognizer(error: '');
GestureRecognizer();
GestureRecognizer(kind: PointerDeviceKind.touch);
GestureRecognizer(error: '');
OneSequenceGestureRecognizer();
OneSequenceGestureRecognizer(kind: PointerDeviceKind.touch);
OneSequenceGestureRecognizer(error: '');
PrimaryPointerGestureRecognizer();
PrimaryPointerGestureRecognizer(kind: PointerDeviceKind.touch);
PrimaryPointerGestureRecognizer(error: '');
EagerGestureRecognizer();
EagerGestureRecognizer(kind: PointerDeviceKind.touch);
EagerGestureRecognizer(error: '');
ForcePressGestureRecognizer();
ForcePressGestureRecognizer(kind: PointerDeviceKind.touch);
ForcePressGestureRecognizer(error: '');
LongPressGestureRecognizer();
LongPressGestureRecognizer(kind: PointerDeviceKind.touch);
LongPressGestureRecognizer(error: '');
MultiDragGestureRecognizer();
MultiDragGestureRecognizer(kind: PointerDeviceKind.touch);
MultiDragGestureRecognizer(error: '');
ImmediateMultiDragGestureRecognizer();
ImmediateMultiDragGestureRecognizer(kind: PointerDeviceKind.touch);
ImmediateMultiDragGestureRecognizer(error: '');
HorizontalMultiDragGestureRecognizer();
HorizontalMultiDragGestureRecognizer(kind: PointerDeviceKind.touch);
HorizontalMultiDragGestureRecognizer(error: '');
VerticalMultiDragGestureRecognizer();
VerticalMultiDragGestureRecognizer(kind: PointerDeviceKind.touch);
VerticalMultiDragGestureRecognizer(error: '');
DelayedMultiDragGestureRecognizer();
DelayedMultiDragGestureRecognizer(kind: PointerDeviceKind.touch);
DelayedMultiDragGestureRecognizer(error: '');
DoubleTapGestureRecognizer();
DoubleTapGestureRecognizer(kind: PointerDeviceKind.touch);
DoubleTapGestureRecognizer(error: '');
MultiTapGestureRecognizer();
MultiTapGestureRecognizer(kind: PointerDeviceKind.touch);
MultiTapGestureRecognizer(error: '');
ScaleGestureRecognizer();
ScaleGestureRecognizer(kind: PointerDeviceKind.touch);
ScaleGestureRecognizer(error: '');
}
| flutter/packages/flutter/test_fixes/gestures/gestures.dart/0 | {
"file_path": "flutter/packages/flutter/test_fixes/gestures/gestures.dart",
"repo_id": "flutter",
"token_count": 1036
} | 883 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
void main() {
// Changes made in https://github.com/flutter/flutter/pull/66482
ThemeData(textSelectionColor: Colors.red);
ThemeData(cursorColor: Colors.blue);
ThemeData(textSelectionHandleColor: Colors.yellow);
ThemeData(useTextSelectionTheme: false);
ThemeData(textSelectionColor: Colors.red, useTextSelectionTheme: false);
ThemeData(cursorColor: Colors.blue, useTextSelectionTheme: false);
ThemeData(
textSelectionHandleColor: Colors.yellow, useTextSelectionTheme: false);
ThemeData(
textSelectionColor: Colors.red,
cursorColor: Colors.blue,
);
ThemeData(
textSelectionHandleColor: Colors.yellow,
cursorColor: Colors.blue,
);
ThemeData(
textSelectionColor: Colors.red,
textSelectionHandleColor: Colors.yellow,
);
ThemeData(
textSelectionColor: Colors.red,
cursorColor: Colors.blue,
useTextSelectionTheme: false,
);
ThemeData(
textSelectionHandleColor: Colors.yellow,
cursorColor: Colors.blue,
useTextSelectionTheme: true,
);
ThemeData(
textSelectionColor: Colors.red,
textSelectionHandleColor: Colors.yellow,
useTextSelectionTheme: false,
);
ThemeData(
textSelectionColor: Colors.red,
cursorColor: Colors.blue,
textSelectionHandleColor: Colors.yellow,
);
ThemeData(
textSelectionColor: Colors.red,
cursorColor: Colors.blue,
textSelectionHandleColor: Colors.yellow,
useTextSelectionTheme: false,
);
ThemeData(error: '');
ThemeData.raw(error: '');
ThemeData.raw(textSelectionColor: Colors.red);
ThemeData.raw(cursorColor: Colors.blue);
ThemeData.raw(textSelectionHandleColor: Colors.yellow);
ThemeData.raw(useTextSelectionTheme: false);
ThemeData.raw(textSelectionColor: Colors.red, useTextSelectionTheme: false);
ThemeData.raw(cursorColor: Colors.blue, useTextSelectionTheme: false);
ThemeData.raw(
textSelectionHandleColor: Colors.yellow, useTextSelectionTheme: false);
ThemeData.raw(
textSelectionColor: Colors.red,
cursorColor: Colors.blue,
);
ThemeData.raw(
textSelectionHandleColor: Colors.yellow,
cursorColor: Colors.blue,
);
ThemeData.raw(
textSelectionColor: Colors.red,
textSelectionHandleColor: Colors.yellow,
);
ThemeData.raw(
textSelectionColor: Colors.red,
cursorColor: Colors.blue,
useTextSelectionTheme: false,
);
ThemeData.raw(
textSelectionHandleColor: Colors.yellow,
cursorColor: Colors.blue,
useTextSelectionTheme: true,
);
ThemeData.raw(
textSelectionColor: Colors.red,
textSelectionHandleColor: Colors.yellow,
useTextSelectionTheme: false,
);
ThemeData.raw(
textSelectionColor: Colors.red,
cursorColor: Colors.blue,
textSelectionHandleColor: Colors.yellow,
);
ThemeData.raw(
textSelectionColor: Colors.red,
cursorColor: Colors.blue,
textSelectionHandleColor: Colors.yellow,
useTextSelectionTheme: false,
);
// Changes made in https://github.com/flutter/flutter/pull/81336
ThemeData themeData = ThemeData();
themeData = ThemeData(accentColor: Colors.red);
themeData = ThemeData(accentColor: Colors.red, primarySwatch: Colors.blue);
themeData = ThemeData(accentColor: Colors.red, colorScheme: ColorScheme.light());
themeData = ThemeData(accentColor: Colors.red, colorScheme: ColorScheme.light(), primarySwatch: Colors.blue);
themeData = ThemeData(error: '');
themeData = ThemeData.raw(accentColor: Colors.red);
themeData = ThemeData.raw(accentColor: Colors.red, primarySwatch: Colors.blue);
themeData = ThemeData.raw(accentColor: Colors.red, colorScheme: ColorScheme.light());
themeData = ThemeData.raw(accentColor: Colors.red, colorScheme: ColorScheme.light(), primarySwatch: Colors.blue);
themeData = ThemeData.raw(error: '');
themeData = themeData.copyWith(accentColor: Colors.red);
themeData = themeData.copyWith(error: '');
themeData = themeData.copyWith(accentColor: Colors.red, primarySwatch: Colors.blue);
themeData = themeData.copyWith(accentColor: Colors.red, colorScheme: ColorScheme.light());
themeData = themeData.copyWith(accentColor: Colors.red, colorScheme: ColorScheme.light(), primarySwatch: Colors.blue);
themeData.accentColor;
// Changes made in https://github.com/flutter/flutter/pull/81336
ThemeData themeData = ThemeData();
themeData = ThemeData(accentColorBrightness: Brightness.dark);
themeData = ThemeData.raw(accentColorBrightness: Brightness.dark);
themeData = themeData.copyWith(accentColorBrightness: Brightness.dark);
themeData.accentColorBrightness; // Removing field reference not supported.
// Changes made in https://github.com/flutter/flutter/pull/81336
ThemeData themeData = ThemeData();
themeData = ThemeData(accentTextTheme: TextTheme());
themeData = ThemeData.raw(accentTextTheme: TextTheme());
themeData = themeData.copyWith(accentTextTheme: TextTheme());
themeData.accentTextTheme; // Removing field reference not supported.
// Changes made in https://github.com/flutter/flutter/pull/81336
ThemeData themeData = ThemeData();
themeData = ThemeData(accentIconTheme: IconThemeData());
themeData = ThemeData.raw(accentIconTheme: IconThemeData());
themeData = themeData.copyWith(accentIconTheme: IconThemeData());
themeData.accentIconTheme; // Removing field reference not supported.
// Changes made in https://github.com/flutter/flutter/pull/81336
ThemeData themeData = ThemeData();
themeData = ThemeData(buttonColor: Colors.red);
themeData = ThemeData.raw(buttonColor: Colors.red);
themeData = themeData.copyWith(buttonColor: Colors.red);
themeData.buttonColor; // Removing field reference not supported.
// Changes made in https://github.com/flutter/flutter/pull/87281
ThemeData themeData = ThemeData();
themeData = ThemeData(fixTextFieldOutlineLabel: true);
themeData = ThemeData.raw(fixTextFieldOutlineLabel: true);
themeData = themeData.copyWith(fixTextFieldOutlineLabel: true);
themeData.fixTextFieldOutlineLabel; // Removing field reference not supported.
// Changes made in https://github.com/flutter/flutter/pull/93396
ThemeData themeData = ThemeData();
themeData = ThemeData(primaryColorBrightness: Brightness.dark);
themeData = ThemeData.raw(primaryColorBrightness: Brightness.dark);
themeData = themeData.copyWith(primaryColorBrightness: Brightness.dark);
themeData.primaryColorBrightness; // Removing field reference not supported.
// Changes made in https://github.com/flutter/flutter/pull/97972
ThemeData themeData = ThemeData();
themeData = ThemeData(toggleableActiveColor: Colors.black);
themeData = ThemeData(
toggleableActiveColor: Colors.black,
);
themeData = ThemeData.raw(toggleableActiveColor: Colors.black);
themeData = ThemeData.raw(
toggleableActiveColor: Colors.black,
);
themeData = themeData.copyWith(toggleableActiveColor: Colors.black);
themeData = themeData.copyWith(
toggleableActiveColor: Colors.black,
);
themeData.toggleableActiveColor; // Removing field reference not supported.
// Changes made in https://github.com/flutter/flutter/pull/109070
ThemeData themeData = ThemeData();
themeData = ThemeData(selectedRowColor: Brightness.dark);
themeData = ThemeData.raw(selectedRowColor: Brightness.dark);
themeData = themeData.copyWith(selectedRowColor: Brightness.dark);
themeData.selectedRowColor; // Removing field reference not supported.
// Changes made in https://github.com/flutter/flutter/pull/110162
ThemeData themeData = ThemeData();
themeData = ThemeData(errorColor: Colors.red);
themeData = ThemeData(errorColor: Colors.red, primarySwatch: Colors.blue);
themeData = ThemeData(errorColor: Colors.red, colorScheme: ColorScheme.light());
themeData = ThemeData(errorColor: Colors.red, colorScheme: ColorScheme.light(), primarySwatch: Colors.blue);
themeData = ThemeData(otherParam: '');
themeData = ThemeData.raw(errorColor: Colors.red);
themeData = ThemeData.raw(errorColor: Colors.red, primarySwatch: Colors.blue);
themeData = ThemeData.raw(errorColor: Colors.red, colorScheme: ColorScheme.light());
themeData = ThemeData.raw(errorColor: Colors.red, colorScheme: ColorScheme.light(), primarySwatch: Colors.blue);
themeData = ThemeData.raw(otherParam: '');
themeData = themeData.copyWith(errorColor: Colors.red);
themeData = themeData.copyWith(otherParam: '');
themeData = themeData.copyWith(errorColor: Colors.red, primarySwatch: Colors.blue);
themeData = themeData.copyWith(errorColor: Colors.red, colorScheme: ColorScheme.light());
themeData = themeData.copyWith(errorColor: Colors.red, colorScheme: ColorScheme.light(), primarySwatch: Colors.blue);
themeData.errorColor;
// Changes made in https://github.com/flutter/flutter/pull/110162
ThemeData themeData = ThemeData();
themeData = ThemeData(backgroundColor: Colors.grey);
themeData = ThemeData(backgroundColor: Colors.grey, primarySwatch: Colors.blue);
themeData = ThemeData(backgroundColor: Colors.grey, colorScheme: ColorScheme.light());
themeData = ThemeData(backgroundColor: Colors.grey, colorScheme: ColorScheme.light(), primarySwatch: Colors.blue);
themeData = ThemeData(otherParam: '');
themeData = ThemeData.raw(backgroundColor: Colors.grey);
themeData = ThemeData.raw(backgroundColor: Colors.grey, primarySwatch: Colors.blue);
themeData = ThemeData.raw(backgroundColor: Colors.grey, colorScheme: ColorScheme.light());
themeData = ThemeData.raw(backgroundColor: Colors.grey, colorScheme: ColorScheme.light(), primarySwatch: Colors.blue);
themeData = ThemeData.raw(otherParam: '');
themeData = themeData.copyWith(backgroundColor: Colors.grey);
themeData = themeData.copyWith(otherParam: '');
themeData = themeData.copyWith(backgroundColor: Colors.grey, primarySwatch: Colors.blue);
themeData = themeData.copyWith(backgroundColor: Colors.grey, colorScheme: ColorScheme.light());
themeData = themeData.copyWith(backgroundColor: Colors.grey, colorScheme: ColorScheme.light(), primarySwatch: Colors.blue);
themeData.backgroundColor;
// Changes made in https://github.com/flutter/flutter/pull/110162
ThemeData themeData = ThemeData();
themeData = ThemeData(backgroundColor: Colors.grey, errorColor: Colors.red);
themeData = ThemeData.raw(backgroundColor: Colors.grey, errorColor: Colors.red);
themeData = themeData.copyWith(backgroundColor: Colors.grey, errorColor: Colors.red);
// Changes made in https://github.com/flutter/flutter/pull/111080
ThemeData themeData = ThemeData();
themeData = ThemeData(bottomAppBarColor: Colors.green);
themeData = ThemeData.raw(bottomAppBarColor: Colors.green);
themeData = ThemeData.copyWith(bottomAppBarColor: Colors.green);
// Changes made in https://github.com/flutter/flutter/pull/131455
ThemeData themeData = ThemeData.copyWith(useMaterial3: false);
}
| flutter/packages/flutter/test_fixes/material/theme_data.dart/0 | {
"file_path": "flutter/packages/flutter/test_fixes/material/theme_data.dart",
"repo_id": "flutter",
"token_count": 3425
} | 884 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// ignore_for_file: public_member_api_docs
// This is the test for the private implementation of animated icons.
// To make the private API accessible from the test we do not import the
// material material_animated_icons library, but instead, this test file is an
// implementation of that library, using some of the parts of the real
// material_animated_icons, this give the test access to the private APIs.
library material_animated_icons;
import 'dart:math' as math show pi;
import 'dart:ui' as ui show Canvas, Paint, Path, lerpDouble;
import 'package:flutter/foundation.dart' show clampDouble;
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
part 'src/material/animated_icons/animated_icons.dart';
part 'src/material/animated_icons/animated_icons_data.dart';
// We have to import all the generated files in the material library to avoid
// analysis errors (as the generated constants are all referenced in the
// animated_icons library).
part 'src/material/animated_icons/data/add_event.g.dart';
part 'src/material/animated_icons/data/arrow_menu.g.dart';
part 'src/material/animated_icons/data/close_menu.g.dart';
part 'src/material/animated_icons/data/ellipsis_search.g.dart';
part 'src/material/animated_icons/data/event_add.g.dart';
part 'src/material/animated_icons/data/home_menu.g.dart';
part 'src/material/animated_icons/data/list_view.g.dart';
part 'src/material/animated_icons/data/menu_arrow.g.dart';
part 'src/material/animated_icons/data/menu_close.g.dart';
part 'src/material/animated_icons/data/menu_home.g.dart';
part 'src/material/animated_icons/data/pause_play.g.dart';
part 'src/material/animated_icons/data/play_pause.g.dart';
part 'src/material/animated_icons/data/search_ellipsis.g.dart';
part 'src/material/animated_icons/data/view_list.g.dart';
class MockCanvas extends Mock implements Canvas {}
class MockPath extends Mock implements Path {}
void main() {
group('Interpolate points', () {
test('- single point', () {
const List<Offset> points = <Offset>[
Offset(25.0, 1.0),
];
expect(_interpolate(points, 0.0, Offset.lerp), const Offset(25.0, 1.0));
expect(_interpolate(points, 0.5, Offset.lerp), const Offset(25.0, 1.0));
expect(_interpolate(points, 1.0, Offset.lerp), const Offset(25.0, 1.0));
});
test('- two points', () {
const List<Offset> points = <Offset>[
Offset(25.0, 1.0),
Offset(12.0, 12.0),
];
expect(_interpolate(points, 0.0, Offset.lerp), const Offset(25.0, 1.0));
expect(_interpolate(points, 0.5, Offset.lerp), const Offset(18.5, 6.5));
expect(_interpolate(points, 1.0, Offset.lerp), const Offset(12.0, 12.0));
});
test('- three points', () {
const List<Offset> points = <Offset>[
Offset(25.0, 1.0),
Offset(12.0, 12.0),
Offset(23.0, 9.0),
];
expect(_interpolate(points, 0.0, Offset.lerp), const Offset(25.0, 1.0));
expect(_interpolate(points, 0.25, Offset.lerp), const Offset(18.5, 6.5));
expect(_interpolate(points, 0.5, Offset.lerp), const Offset(12.0, 12.0));
expect(_interpolate(points, 0.75, Offset.lerp), const Offset(17.5, 10.5));
expect(_interpolate(points, 1.0, Offset.lerp), const Offset(23.0, 9.0));
});
});
group('_AnimatedIconPainter', () {
const Size size = Size(48.0, 48.0);
late MockPath mockPath;
late MockCanvas mockCanvas;
late List<MockPath> generatedPaths;
late _UiPathFactory pathFactory;
setUp(() {
generatedPaths = <MockPath>[];
mockCanvas = MockCanvas();
mockPath = MockPath();
pathFactory = () {
generatedPaths.add(mockPath);
return mockPath;
};
});
test('progress 0', () {
final _AnimatedIconPainter painter = _AnimatedIconPainter(
paths: _movingBar.paths,
progress: const AlwaysStoppedAnimation<double>(0.0),
color: const Color(0xFF00FF00),
scale: 1.0,
shouldMirror: false,
uiPathFactory: pathFactory,
);
painter.paint(mockCanvas, size);
expect(generatedPaths.length, 1);
generatedPaths[0].verifyCallsInOrder(<MockCall>[
MockCall('moveTo', <dynamic>[0.0, 0.0]),
MockCall('lineTo', <dynamic>[48.0, 0.0]),
MockCall('lineTo', <dynamic>[48.0, 10.0]),
MockCall('lineTo', <dynamic>[0.0, 10.0]),
MockCall('lineTo', <dynamic>[0.0, 0.0]),
MockCall('close'),
]);
});
test('progress 1', () {
final _AnimatedIconPainter painter = _AnimatedIconPainter(
paths: _movingBar.paths,
progress: const AlwaysStoppedAnimation<double>(1.0),
color: const Color(0xFF00FF00),
scale: 1.0,
shouldMirror: false,
uiPathFactory: pathFactory,
);
painter.paint(mockCanvas, size);
expect(generatedPaths.length, 1);
generatedPaths[0].verifyCallsInOrder(<MockCall>[
MockCall('moveTo', <dynamic>[0.0, 38.0]),
MockCall('lineTo', <dynamic>[48.0, 38.0]),
MockCall('lineTo', <dynamic>[48.0, 48.0]),
MockCall('lineTo', <dynamic>[0.0, 48.0]),
MockCall('lineTo', <dynamic>[0.0, 38.0]),
MockCall('close'),
]);
});
test('clamped progress', () {
final _AnimatedIconPainter painter = _AnimatedIconPainter(
paths: _movingBar.paths,
progress: const AlwaysStoppedAnimation<double>(1.5),
color: const Color(0xFF00FF00),
scale: 1.0,
shouldMirror: false,
uiPathFactory: pathFactory,
);
painter.paint(mockCanvas, size);
expect(generatedPaths.length, 1);
generatedPaths[0].verifyCallsInOrder(<MockCall>[
MockCall('moveTo', <dynamic>[0.0, 38.0]),
MockCall('lineTo', <dynamic>[48.0, 38.0]),
MockCall('lineTo', <dynamic>[48.0, 48.0]),
MockCall('lineTo', <dynamic>[0.0, 48.0]),
MockCall('lineTo', <dynamic>[0.0, 38.0]),
MockCall('close'),
]);
});
test('scale', () {
final _AnimatedIconPainter painter = _AnimatedIconPainter(
paths: _movingBar.paths,
progress: const AlwaysStoppedAnimation<double>(0.0),
color: const Color(0xFF00FF00),
scale: 0.5,
shouldMirror: false,
uiPathFactory: pathFactory,
);
painter.paint(mockCanvas, size);
mockCanvas.verifyCallsInOrder(<MockCall>[
MockCall('scale', <dynamic>[0.5, 0.5]),
MockCall.any('drawPath'),
]);
});
test('mirror', () {
final _AnimatedIconPainter painter = _AnimatedIconPainter(
paths: _movingBar.paths,
progress: const AlwaysStoppedAnimation<double>(0.0),
color: const Color(0xFF00FF00),
scale: 1.0,
shouldMirror: true,
uiPathFactory: pathFactory,
);
painter.paint(mockCanvas, size);
mockCanvas.verifyCallsInOrder(<MockCall>[
MockCall('rotate', <dynamic>[math.pi]),
MockCall('translate', <dynamic>[-48.0, -48.0]),
MockCall('scale', <dynamic>[1.0, 1.0]),
MockCall.any('drawPath'),
]);
});
test('interpolated frame', () {
final _AnimatedIconPainter painter = _AnimatedIconPainter(
paths: _movingBar.paths,
progress: const AlwaysStoppedAnimation<double>(0.5),
color: const Color(0xFF00FF00),
scale: 1.0,
shouldMirror: false,
uiPathFactory: pathFactory,
);
painter.paint(mockCanvas, size);
expect(generatedPaths.length, 1);
generatedPaths[0].verifyCallsInOrder(<MockCall>[
MockCall('moveTo', <dynamic>[0.0, 19.0]),
MockCall('lineTo', <dynamic>[48.0, 19.0]),
MockCall('lineTo', <dynamic>[48.0, 29.0]),
MockCall('lineTo', <dynamic>[0.0, 29.0]),
MockCall('lineTo', <dynamic>[0.0, 19.0]),
MockCall('close'),
]);
});
test('curved frame', () {
final _AnimatedIconPainter painter = _AnimatedIconPainter(
paths: _bow.paths,
progress: const AlwaysStoppedAnimation<double>(1.0),
color: const Color(0xFF00FF00),
scale: 1.0,
shouldMirror: false,
uiPathFactory: pathFactory,
);
painter.paint(mockCanvas, size);
expect(generatedPaths.length, 1);
generatedPaths[0].verifyCallsInOrder(<MockCall>[
MockCall('moveTo', <dynamic>[0.0, 24.0]),
MockCall('cubicTo', <dynamic>[16.0, 48.0, 32.0, 48.0, 48.0, 24.0]),
MockCall('lineTo', <dynamic>[0.0, 24.0]),
MockCall('close'),
]);
});
test('interpolated curved frame', () {
final _AnimatedIconPainter painter = _AnimatedIconPainter(
paths: _bow.paths,
progress: const AlwaysStoppedAnimation<double>(0.25),
color: const Color(0xFF00FF00),
scale: 1.0,
shouldMirror: false,
uiPathFactory: pathFactory,
);
painter.paint(mockCanvas, size);
expect(generatedPaths.length, 1);
generatedPaths[0].verifyCallsInOrder(<MockCall>[
MockCall('moveTo', <dynamic>[0.0, 24.0]),
MockCall('cubicTo', <dynamic>[16.0, 17.0, 32.0, 17.0, 48.0, 24.0]),
MockCall('lineTo', <dynamic>[0.0, 24.0]),
MockCall('close', <dynamic>[]),
]);
});
test('should not repaint same values', () {
final _AnimatedIconPainter painter1 = _AnimatedIconPainter(
paths: _bow.paths,
progress: const AlwaysStoppedAnimation<double>(0.0),
color: const Color(0xFF00FF00),
scale: 1.0,
shouldMirror: false,
uiPathFactory: pathFactory,
);
final _AnimatedIconPainter painter2 = _AnimatedIconPainter(
paths: _bow.paths,
progress: const AlwaysStoppedAnimation<double>(0.0),
color: const Color(0xFF00FF00),
scale: 1.0,
shouldMirror: false,
uiPathFactory: pathFactory,
);
expect(painter1.shouldRepaint(painter2), false);
});
test('should repaint on progress change', () {
final _AnimatedIconPainter painter1 = _AnimatedIconPainter(
paths: _bow.paths,
progress: const AlwaysStoppedAnimation<double>(0.0),
color: const Color(0xFF00FF00),
scale: 1.0,
shouldMirror: false,
uiPathFactory: pathFactory,
);
final _AnimatedIconPainter painter2 = _AnimatedIconPainter(
paths: _bow.paths,
progress: const AlwaysStoppedAnimation<double>(0.1),
color: const Color(0xFF00FF00),
scale: 1.0,
shouldMirror: false,
uiPathFactory: pathFactory,
);
expect(painter1.shouldRepaint(painter2), true);
});
test('should repaint on color change', () {
final _AnimatedIconPainter painter1 = _AnimatedIconPainter(
paths: _bow.paths,
progress: const AlwaysStoppedAnimation<double>(0.0),
color: const Color(0xFF00FF00),
scale: 1.0,
shouldMirror: false,
uiPathFactory: pathFactory,
);
final _AnimatedIconPainter painter2 = _AnimatedIconPainter(
paths: _bow.paths,
progress: const AlwaysStoppedAnimation<double>(0.0),
color: const Color(0xFFFF0000),
scale: 1.0,
shouldMirror: false,
uiPathFactory: pathFactory,
);
expect(painter1.shouldRepaint(painter2), true);
});
test('should repaint on paths change', () {
final _AnimatedIconPainter painter1 = _AnimatedIconPainter(
paths: _bow.paths,
progress: const AlwaysStoppedAnimation<double>(0.0),
color: const Color(0xFF0000FF),
scale: 1.0,
shouldMirror: false,
uiPathFactory: pathFactory,
);
final _AnimatedIconPainter painter2 = _AnimatedIconPainter(
paths: const <_PathFrames>[],
progress: const AlwaysStoppedAnimation<double>(0.0),
color: const Color(0xFF0000FF),
scale: 1.0,
shouldMirror: false,
uiPathFactory: pathFactory,
);
expect(painter1.shouldRepaint(painter2), true);
});
});
}
// Contains the data from an invocation used for collection of calls and for
// expectations in Mock class.
class MockCall {
// Creates a mock call with optional positional arguments.
MockCall(String memberName, [this.positionalArguments, this.acceptAny = false])
: memberSymbol = Symbol(memberName);
MockCall.fromSymbol(this.memberSymbol, [this.positionalArguments, this.acceptAny = false]);
// Creates a mock call expectation that doesn't care about what the arguments were.
MockCall.any(String memberName)
: memberSymbol = Symbol(memberName),
acceptAny = true,
positionalArguments = null;
final Symbol memberSymbol;
String get memberName {
final RegExp symbolMatch = RegExp(r'Symbol\("(?<name>.*)"\)');
final RegExpMatch? match = symbolMatch.firstMatch(memberSymbol.toString());
assert(match != null);
return match!.namedGroup('name')!;
}
final List<dynamic>? positionalArguments;
final bool acceptAny;
@override
String toString() {
return '$memberName(${positionalArguments?.join(', ') ?? ''})';
}
}
// A very simplified version of a Mock class.
//
// Only verifies positional arguments, and only can verify calls in order.
class Mock {
final List<MockCall> _calls = <MockCall>[];
// Verify that the given calls happened in the order given.
void verifyCallsInOrder(List<MockCall> expected) {
int count = 0;
expect(expected.length, equals(_calls.length),
reason: 'Incorrect number of calls received. '
'Expected ${expected.length} and received ${_calls.length}.\n'
' Calls Received: $_calls\n'
' Calls Expected: $expected');
for (final MockCall call in _calls) {
expect(call.memberSymbol, equals(expected[count].memberSymbol),
reason: 'Unexpected call to ${call.memberName}, expected a call to '
'${expected[count].memberName} instead.');
if (call.positionalArguments != null && !expected[count].acceptAny) {
int countArg = 0;
for (final dynamic arg in call.positionalArguments!) {
expect(arg, equals(expected[count].positionalArguments![countArg]),
reason: 'Failed at call $count. Positional argument $countArg to ${call.memberName} '
'not as expected. Expected ${expected[count].positionalArguments![countArg]} '
'and received $arg');
countArg++;
}
}
count++;
}
}
@override
void noSuchMethod(Invocation invocation) {
_calls.add(MockCall.fromSymbol(invocation.memberName, invocation.positionalArguments));
}
}
const _AnimatedIconData _movingBar = _AnimatedIconData(
Size(48.0, 48.0),
<_PathFrames>[
_PathFrames(
opacities: <double>[1.0, 0.2],
commands: <_PathCommand>[
_PathMoveTo(
<Offset>[
Offset.zero,
Offset(0.0, 38.0),
],
),
_PathLineTo(
<Offset>[
Offset(48.0, 0.0),
Offset(48.0, 38.0),
],
),
_PathLineTo(
<Offset>[
Offset(48.0, 10.0),
Offset(48.0, 48.0),
],
),
_PathLineTo(
<Offset>[
Offset(0.0, 10.0),
Offset(0.0, 48.0),
],
),
_PathLineTo(
<Offset>[
Offset.zero,
Offset(0.0, 38.0),
],
),
_PathClose(),
],
),
],
);
const _AnimatedIconData _bow = _AnimatedIconData(
Size(48.0, 48.0),
<_PathFrames>[
_PathFrames(
opacities: <double>[1.0, 1.0],
commands: <_PathCommand>[
_PathMoveTo(
<Offset>[
Offset(0.0, 24.0),
Offset(0.0, 24.0),
Offset(0.0, 24.0),
],
),
_PathCubicTo(
<Offset>[
Offset(16.0, 24.0),
Offset(16.0, 10.0),
Offset(16.0, 48.0),
],
<Offset>[
Offset(32.0, 24.0),
Offset(32.0, 10.0),
Offset(32.0, 48.0),
],
<Offset>[
Offset(48.0, 24.0),
Offset(48.0, 24.0),
Offset(48.0, 24.0),
],
),
_PathLineTo(
<Offset>[
Offset(0.0, 24.0),
Offset(0.0, 24.0),
Offset(0.0, 24.0),
],
),
_PathClose(),
],
),
],
);
| flutter/packages/flutter/test_private/test/animated_icons_private_test.dart.tmpl/0 | {
"file_path": "flutter/packages/flutter/test_private/test/animated_icons_private_test.dart.tmpl",
"repo_id": "flutter",
"token_count": 7462
} | 885 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'message.dart';
/// A Flutter Driver command that sends a string to the application and expects a
/// string response.
class RequestData extends Command {
/// Create a command that sends a message.
const RequestData(this.message, { super.timeout });
/// Deserializes this command from the value generated by [serialize].
RequestData.deserialize(super.json)
: message = json['message'],
super.deserialize();
/// The message being sent from the test to the application.
final String? message;
@override
String get kind => 'request_data';
@override
bool get requiresRootWidgetAttached => false;
@override
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
if (message != null)
'message': message!,
});
}
/// The result of the [RequestData] command.
class RequestDataResult extends Result {
/// Creates a result with the given [message].
const RequestDataResult(this.message);
/// The text extracted by the [RequestData] command.
final String message;
/// Deserializes the result from JSON.
static RequestDataResult fromJson(Map<String, dynamic> json) {
return RequestDataResult(json['message'] as String);
}
@override
Map<String, dynamic> toJson() => <String, String>{
'message': message,
};
}
| flutter/packages/flutter_driver/lib/src/common/request_data.dart/0 | {
"file_path": "flutter/packages/flutter_driver/lib/src/common/request_data.dart",
"repo_id": "flutter",
"token_count": 424
} | 886 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Timeline data recorded by the Flutter runtime.
class Timeline {
/// Creates a timeline given JSON-encoded timeline data.
///
/// [json] is in the `chrome://tracing` format. It can be saved to a file
/// and loaded in Chrome for visual inspection.
///
/// See https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
Timeline.fromJson(this.json) : events = _parseEvents(json);
/// The original timeline JSON.
final Map<String, dynamic> json;
/// List of all timeline events.
///
/// This is parsed from "traceEvents" data within [json] and sorted by
/// timestamp. Anything without a valid timestamp is put in the beginning.
///
/// This will be null if there are no "traceEvents" in the [json].
final List<TimelineEvent>? events;
}
/// A single timeline event.
class TimelineEvent {
/// Creates a timeline event given JSON-encoded event data.
TimelineEvent(this.json)
: name = json['name'] as String?,
category = json['cat'] as String?,
phase = json['ph'] as String?,
processId = json['pid'] as int?,
threadId = json['tid'] as int?,
duration = json['dur'] != null
? Duration(microseconds: json['dur'] as int)
: null,
threadDuration = json['tdur'] != null
? Duration(microseconds: json['tdur'] as int)
: null,
timestampMicros = json['ts'] as int?,
threadTimestampMicros = json['tts'] as int?,
arguments = json['args'] as Map<String, dynamic>?;
/// The original event JSON.
final Map<String, dynamic> json;
/// The name of the event.
///
/// Corresponds to the "name" field in the JSON event.
final String? name;
/// Event category. Events with different names may share the same category.
///
/// Corresponds to the "cat" field in the JSON event.
final String? category;
/// For a given long lasting event, denotes the phase of the event, such as
/// "B" for "event began", and "E" for "event ended".
///
/// Corresponds to the "ph" field in the JSON event.
final String? phase;
/// ID of process that emitted the event.
///
/// Corresponds to the "pid" field in the JSON event.
final int? processId;
/// ID of thread that issues the event.
///
/// Corresponds to the "tid" field in the JSON event.
final int? threadId;
/// The duration of the event.
///
/// Note, some events are reported with duration. Others are reported as a
/// pair of begin/end events.
///
/// Corresponds to the "dur" field in the JSON event.
final Duration? duration;
/// The thread duration of the event.
///
/// Note, some events are reported with duration. Others are reported as a
/// pair of begin/end events.
///
/// Corresponds to the "tdur" field in the JSON event.
final Duration? threadDuration;
/// Time passed since tracing was enabled, in microseconds.
///
/// Corresponds to the "ts" field in the JSON event.
final int? timestampMicros;
/// Thread clock time, in microseconds.
///
/// Corresponds to the "tts" field in the JSON event.
final int? threadTimestampMicros;
/// Arbitrary data attached to the event.
///
/// Corresponds to the "args" field in the JSON event.
final Map<String, dynamic>? arguments;
}
List<TimelineEvent>? _parseEvents(Map<String, dynamic> json) {
final List<dynamic>? jsonEvents = json['traceEvents'] as List<dynamic>?;
if (jsonEvents == null) {
return null;
}
final List<TimelineEvent> timelineEvents =
Iterable.castFrom<dynamic, Map<String, dynamic>>(jsonEvents)
.map<TimelineEvent>(
(Map<String, dynamic> eventJson) => TimelineEvent(eventJson))
.toList();
timelineEvents.sort((TimelineEvent e1, TimelineEvent e2) {
final int? ts1 = e1.timestampMicros;
final int? ts2 = e2.timestampMicros;
if (ts1 == null) {
if (ts2 == null) {
return 0;
} else {
return -1;
}
} else if (ts2 == null) {
return 1;
} else {
return ts1.compareTo(ts2);
}
});
return timelineEvents;
}
| flutter/packages/flutter_driver/lib/src/driver/timeline.dart/0 | {
"file_path": "flutter/packages/flutter_driver/lib/src/driver/timeline.dart",
"repo_id": "flutter",
"token_count": 1447
} | 887 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_driver/src/extension/_extension_io.dart';
import '../../common.dart';
void main() {
group('test io_extension',() {
late Future<Map<String, dynamic>> Function(Map<String, String>) call;
setUp(() {
call = (Map<String, String> args) async {
return Future<Map<String, dynamic>>.value(args);
};
});
test('io_extension should throw exception', () {
expect(() => registerWebServiceExtension(call), throwsUnsupportedError);
});
});
}
| flutter/packages/flutter_driver/test/src/real_tests/io_extension_test.dart/0 | {
"file_path": "flutter/packages/flutter_driver/test/src/real_tests/io_extension_test.dart",
"repo_id": "flutter",
"token_count": 228
} | 888 |
{
"datePickerHourSemanticsLabelOne": "$hour uur",
"datePickerHourSemanticsLabelOther": "$hour uur",
"datePickerMinuteSemanticsLabelOne": "1 minuut",
"datePickerMinuteSemanticsLabelOther": "$minute minute",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "vm.",
"postMeridiemAbbreviation": "nm.",
"todayLabel": "Vandag",
"alertDialogLabel": "Opletberig",
"timerPickerHourLabelOne": "uur",
"timerPickerHourLabelOther": "uur",
"timerPickerMinuteLabelOne": "min.",
"timerPickerMinuteLabelOther": "min.",
"timerPickerSecondLabelOne": "sek.",
"timerPickerSecondLabelOther": "sek.",
"cutButtonLabel": "Knip",
"copyButtonLabel": "Kopieer",
"pasteButtonLabel": "Plak",
"selectAllButtonLabel": "Kies alles",
"tabSemanticsLabel": "Oortjie $tabIndex van $tabCount",
"modalBarrierDismissLabel": "Maak toe",
"searchTextFieldPlaceholderLabel": "Soek",
"noSpellCheckReplacementsLabel": "Geen plaasvervangers gevind nie",
"menuDismissLabel": "Maak kieslys toe",
"lookUpButtonLabel": "Kyk op",
"searchWebButtonLabel": "Deursoek web",
"shareButtonLabel": "Deel …",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_af.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_af.arb",
"repo_id": "flutter",
"token_count": 435
} | 889 |
{
"@datePickerHourSemanticsLabelZero": {
"optional": true
},
"datePickerHourSemanticsLabelOne": "$hour o'clock",
"@datePickerHourSemanticsLabelOne": {
"optional": true
},
"@datePickerHourSemanticsLabelTwo": {
"optional": true
},
"@datePickerHourSemanticsLabelFew": {
"optional": true
},
"@datePickerHourSemanticsLabelMany": {
"optional": true
},
"datePickerHourSemanticsLabelOther": "$hour o'clock",
"@datePickerHourSemanticsLabel": {
"description": "Accessibility announcement for the selected hour on a time picker such as '5 o'clock' or '5点'",
"plural": "hour"
},
"@datePickerMinuteSemanticsLabelZero": {
"optional": true
},
"datePickerMinuteSemanticsLabelOne": "1 minute",
"@datePickerMinuteSemanticsLabelOne": {
"optional": true
},
"@datePickerMinuteSemanticsLabelTwo": {
"optional": true
},
"@datePickerMinuteSemanticsLabelFew": {
"optional": true
},
"@datePickerMinuteSemanticsLabelMany": {
"optional": true
},
"datePickerMinuteSemanticsLabelOther": "$minute minutes",
"@datePickerMinuteSemanticsLabel": {
"description": "Accessibility announcement for the selected minute on a time picker such as '15 minutes' or '15分'",
"plural": "minute"
},
"datePickerDateOrder": "mdy",
"@datePickerDateOrder": {
"description": "Choose a standard order for the locale to arrange day, month and year in a date. Do not transliterate the abbreviations themselves. The only options are dmy, mdy, ymd and ydm. For instance, in French, use dmy (for day month year) but do not translate into jma (for jour mois année). "
},
"datePickerDateTimeOrder": "date_time_dayPeriod",
"@datePickerDateTimeOrder": {
"description": "Choose a standard order for the locale to arrange date, time and am/pm in a datetime. Do not transliterate the choices themselves. The only options are date_time_dayPeriod, date_dayPeriod_time, time_dayPeriod_date and dayPeriod_time_date where 'dayPeriod' is am/pm. You can ignore the position of dayPeriod if the locale uses 24h time only. For instance, in French, use date_time_dayPeriod, but do not translate into date_heure_périodeDuJour or some such."
},
"anteMeridiemAbbreviation": "AM",
"@anteMeridiemAbbreviation": {
"description": "The abbreviation for ante meridiem (before noon) shown in the time picker when it's not using the 24h format. Reference the text iOS uses such as in the iOS clock app."
},
"postMeridiemAbbreviation": "PM",
"@postMeridiemAbbreviation": {
"description": "The abbreviation for post meridiem (after noon) shown in the time picker when it's not using the 24h format. Reference the text iOS uses such as in the iOS clock app."
},
"todayLabel": "Today",
"@todayLabel": {
"description": "A label shown in the date picker when the date is today."
},
"alertDialogLabel": "Alert",
"@alertDialogLabel": {
"description": "The accessibility audio announcement made when an iOS style alert dialog is opened."
},
"tabSemanticsLabel": "Tab $tabIndex of $tabCount",
"@tabSemanticsLabel": {
"description": "The accessibility label used on a tab. This message describes the index of the selected tab and how many tabs there are, e.g. 'tab, 1 of 2'. All values are greater than or equal to one.",
"parameters": "tabIndex, tabCount"
},
"@timerPickerHourLabelZero": {
"optional": true
},
"timerPickerHourLabelOne": "hour",
"@timerPickerHourLabelOne": {
"optional": true
},
"@timerPickerHourLabelTwo": {
"optional": true
},
"@timerPickerHourLabelFew": {
"optional": true
},
"@timerPickerHourLabelMany": {
"optional": true
},
"timerPickerHourLabelOther": "hours",
"@timerPickerHourLabel": {
"description": "The label adjacent to an hour integer number in a countdown timer. The reference abbreviation is what iOS does in the stock clock app's countdown timer.",
"plural": "hour"
},
"@timerPickerMinuteLabelZero": {
"optional": true
},
"timerPickerMinuteLabelOne": "min.",
"@timerPickerMinuteLabelOne": {
"optional": true
},
"@timerPickerMinuteLabelTwo": {
"optional": true
},
"@timerPickerMinuteLabelFew": {
"optional": true
},
"@timerPickerMinuteLabelMany": {
"optional": true
},
"timerPickerMinuteLabelOther": "min.",
"@timerPickerMinuteLabel": {
"description": "The label adjacent to a minute integer number in a countdown timer. The reference abbreviation is what iOS does in the stock clock app's countdown timer.",
"plural": "minute"
},
"@timerPickerSecondLabelZero": {
"optional": true
},
"timerPickerSecondLabelOne": "sec.",
"@timerPickerSecondLabelOne": {
"optional": true
},
"@timerPickerSecondLabelTwo": {
"optional": true
},
"@timerPickerSecondLabelFew": {
"optional": true
},
"@timerPickerSecondLabelMany": {
"optional": true
},
"timerPickerSecondLabelOther": "sec.",
"@timerPickerSecondLabel": {
"description": "The label adjacent to a second integer number in a countdown timer. The reference abbreviation is what iOS does in the stock clock app's countdown timer.",
"plural": "second"
},
"cutButtonLabel": "Cut",
"@cutButtonLabel": {
"description": "The label for cut buttons and menu items. The reference abbreviation is what iOS shows on text selection toolbars."
},
"copyButtonLabel": "Copy",
"@copyButtonLabel": {
"description": "The label for copy buttons and menu items. The reference abbreviation is what iOS shows on text selection toolbars."
},
"pasteButtonLabel": "Paste",
"@pasteButtonLabel": {
"description": "The label for paste buttons and menu items. The reference abbreviation is what iOS shows on text selection toolbars."
},
"clearButtonLabel": "Clear",
"@clearButtonLabel": {
"description": "The label for clear buttons and menu items."
},
"selectAllButtonLabel": "Select All",
"@selectAllButtonLabel": {
"description": "The label for select-all buttons and menu items. The reference abbreviation is what iOS shows on text selection toolbars."
},
"lookUpButtonLabel": "Look Up",
"@lookUpButtonLabel": {
"description": "The label for the Look Up button and menu items on iOS."
},
"searchWebButtonLabel": "Search Web",
"@searchWebButtonLabel": {
"description": "The label for the Search Web button and menu items on iOS."
},
"shareButtonLabel": "Share...",
"@shareButtonLabel": {
"description": "The label for the Share button and menu items on iOS."
},
"noSpellCheckReplacementsLabel": "No Replacements Found",
"@noSpellCheckReplacementsLabel": {
"description": "The label shown in the text selection context menu on iOS when a misspelled word is tapped but the spell checker found no reasonable fixes for it."
},
"searchTextFieldPlaceholderLabel": "Search",
"@searchTextFieldPlaceholderLabel": {
"description": "The default placeholder label used in an iOS styled search bar."
},
"modalBarrierDismissLabel": "Dismiss",
"@modalBarrierDismissLabel": {
"description": "Label read out by accessibility tools (VoiceOver) for a modal barrier to indicate that a tap dismisses the barrier. A modal barrier can, for example, be found behind an alert or popup to block user interaction with elements behind it."
},
"menuDismissLabel": "Dismiss menu",
"@menuDismissLabel": {
"description": "Label read out by accessibility tools (TalkBack or VoiceOver) for the area around a menu to indicate that a tap dismisses the menu."
}
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_en.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_en.arb",
"repo_id": "flutter",
"token_count": 2316
} | 890 |
{
"searchWebButtonLabel": "Buscar en la Web",
"shareButtonLabel": "Compartir…",
"lookUpButtonLabel": "Mirar hacia arriba",
"noSpellCheckReplacementsLabel": "No se encontraron reemplazos",
"menuDismissLabel": "Descartar menú",
"searchTextFieldPlaceholderLabel": "Buscar",
"tabSemanticsLabel": "Pestaña $tabIndex de $tabCount",
"datePickerHourSemanticsLabelOne": "$hour en punto",
"datePickerHourSemanticsLabelOther": "$hour en punto",
"datePickerMinuteSemanticsLabelOne": "1 minuto",
"datePickerMinuteSemanticsLabelOther": "$minute minutos",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "a.m.",
"postMeridiemAbbreviation": "p.m.",
"todayLabel": "Hoy",
"alertDialogLabel": "Alerta",
"timerPickerHourLabelOne": "hora",
"timerPickerHourLabelOther": "horas",
"timerPickerMinuteLabelOne": "min",
"timerPickerMinuteLabelOther": "min",
"timerPickerSecondLabelOne": "s",
"timerPickerSecondLabelOther": "s",
"cutButtonLabel": "Cortar",
"copyButtonLabel": "Copiar",
"pasteButtonLabel": "Pegar",
"selectAllButtonLabel": "Seleccionar todo",
"modalBarrierDismissLabel": "Descartar"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_es_DO.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_es_DO.arb",
"repo_id": "flutter",
"token_count": 434
} | 891 |
{
"datePickerHourSemanticsLabelOne": "ساعت $hour",
"datePickerHourSemanticsLabelOther": "ساعت $hour",
"datePickerMinuteSemanticsLabelOne": "۱ دقیقه",
"datePickerMinuteSemanticsLabelOther": "$minute دقیقه",
"datePickerDateOrder": "ymd",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "ق.ظ.",
"postMeridiemAbbreviation": "ب.ظ.",
"todayLabel": "امروز",
"alertDialogLabel": "هشدار",
"timerPickerHourLabelOne": "ساعت",
"timerPickerHourLabelOther": "ساعت",
"timerPickerMinuteLabelOne": "دقیقه",
"timerPickerMinuteLabelOther": "دقیقه",
"timerPickerSecondLabelOne": "ثانیه",
"timerPickerSecondLabelOther": "ثانیه",
"cutButtonLabel": "برش",
"copyButtonLabel": "کپی",
"pasteButtonLabel": "جایگذاری",
"selectAllButtonLabel": "انتخاب همه",
"tabSemanticsLabel": "برگه $tabIndex از $tabCount",
"modalBarrierDismissLabel": "نپذیرفتن",
"searchTextFieldPlaceholderLabel": "جستجو",
"noSpellCheckReplacementsLabel": "جایگزینی پیدا نشد",
"menuDismissLabel": "بستن منو",
"lookUpButtonLabel": "جستجو",
"searchWebButtonLabel": "جستجو در وب",
"shareButtonLabel": "همرسانی…",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_fa.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_fa.arb",
"repo_id": "flutter",
"token_count": 569
} | 892 |
{
"datePickerHourSemanticsLabelOne": "$hour時",
"datePickerHourSemanticsLabelOther": "$hour時",
"datePickerMinuteSemanticsLabelOne": "1分",
"datePickerMinuteSemanticsLabelOther": "$minute分",
"datePickerDateOrder": "ymd",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"todayLabel": "今日",
"alertDialogLabel": "通知",
"timerPickerHourLabelOne": "時間",
"timerPickerHourLabelOther": "時間",
"timerPickerMinuteLabelOne": "分",
"timerPickerMinuteLabelOther": "分",
"timerPickerSecondLabelOne": "秒",
"timerPickerSecondLabelOther": "秒",
"cutButtonLabel": "切り取り",
"copyButtonLabel": "コピー",
"pasteButtonLabel": "貼り付け",
"selectAllButtonLabel": "すべてを選択",
"tabSemanticsLabel": "タブ: $tabIndex/$tabCount",
"modalBarrierDismissLabel": "閉じる",
"searchTextFieldPlaceholderLabel": "検索",
"noSpellCheckReplacementsLabel": "置き換えるものがありません",
"menuDismissLabel": "メニューを閉じる",
"lookUpButtonLabel": "調べる",
"searchWebButtonLabel": "ウェブを検索",
"shareButtonLabel": "共有...",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_ja.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_ja.arb",
"repo_id": "flutter",
"token_count": 484
} | 893 |
{
"datePickerHourSemanticsLabelOne": "$hour null-null",
"datePickerHourSemanticsLabelOther": "$hour null-null",
"datePickerMinuteSemanticsLabelOne": "1 minutt",
"datePickerMinuteSemanticsLabelOther": "$minute minutter",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"todayLabel": "I dag",
"alertDialogLabel": "Varsel",
"tabSemanticsLabel": "Fane $tabIndex av $tabCount",
"timerPickerHourLabelOne": "time",
"timerPickerHourLabelOther": "timer",
"timerPickerMinuteLabelOne": "min.",
"timerPickerMinuteLabelOther": "min.",
"timerPickerSecondLabelOne": "sek.",
"timerPickerSecondLabelOther": "sek.",
"cutButtonLabel": "Klipp ut",
"copyButtonLabel": "Kopiér",
"pasteButtonLabel": "Lim inn",
"selectAllButtonLabel": "Velg alle",
"modalBarrierDismissLabel": "Avvis",
"searchTextFieldPlaceholderLabel": "Søk",
"noSpellCheckReplacementsLabel": "Fant ingen erstatninger",
"menuDismissLabel": "Lukk menyen",
"lookUpButtonLabel": "Slå opp",
"searchWebButtonLabel": "Søk på nettet",
"shareButtonLabel": "Del…",
"clearButtonLabel": "Clear"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_nb.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_nb.arb",
"repo_id": "flutter",
"token_count": 427
} | 894 |
{
"lookUpButtonLabel": "Pogled nagore",
"searchWebButtonLabel": "Pretraži veb",
"shareButtonLabel": "Deli…",
"noSpellCheckReplacementsLabel": "Nisu pronađene zamene",
"menuDismissLabel": "Odbacite meni",
"searchTextFieldPlaceholderLabel": "Pretražite",
"tabSemanticsLabel": "$tabIndex. kartica od $tabCount",
"datePickerHourSemanticsLabelFew": "$hour sata",
"datePickerMinuteSemanticsLabelFew": "$minute minuta",
"timerPickerHourLabelFew": "sata",
"timerPickerMinuteLabelFew": "min",
"timerPickerSecondLabelFew": "sek",
"datePickerHourSemanticsLabelOne": "$hour sat",
"datePickerHourSemanticsLabelOther": "$hour sati",
"datePickerMinuteSemanticsLabelOne": "1 minut",
"datePickerMinuteSemanticsLabelOther": "$minute minuta",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "pre podne",
"postMeridiemAbbreviation": "po podne",
"todayLabel": "Danas",
"alertDialogLabel": "Obaveštenje",
"timerPickerHourLabelOne": "sat",
"timerPickerHourLabelOther": "sati",
"timerPickerMinuteLabelOne": "min",
"timerPickerMinuteLabelOther": "min",
"timerPickerSecondLabelOne": "sek",
"timerPickerSecondLabelOther": "sek",
"cutButtonLabel": "Iseci",
"copyButtonLabel": "Kopiraj",
"pasteButtonLabel": "Nalepi",
"selectAllButtonLabel": "Izaberi sve",
"modalBarrierDismissLabel": "Odbaci"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_sr_Latn.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_sr_Latn.arb",
"repo_id": "flutter",
"token_count": 515
} | 895 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been automatically generated. Please do not edit it manually.
// To regenerate the file, use:
// dart dev/tools/localization/bin/gen_localizations.dart --overwrite
import 'dart:collection';
import 'package:flutter/cupertino.dart';
import 'package:intl/intl.dart' as intl;
import '../cupertino_localizations.dart';
// The classes defined here encode all of the translations found in the
// `flutter_localizations/lib/src/l10n/*.arb` files.
//
// These classes are constructed by the [getCupertinoTranslation] method at the
// bottom of this file, and used by the [_GlobalCupertinoLocalizationsDelegate.load]
// method defined in `flutter_localizations/lib/src/cupertino_localizations.dart`.
/// The translations for Afrikaans (`af`).
class CupertinoLocalizationAf extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Afrikaans.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationAf({
super.localeName = 'af',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Opletberig';
@override
String get anteMeridiemAbbreviation => 'vm.';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopieer';
@override
String get cutButtonLabel => 'Knip';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour uur';
@override
String get datePickerHourSemanticsLabelOther => r'$hour uur';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minuut';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minute';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Kyk op';
@override
String get menuDismissLabel => 'Maak kieslys toe';
@override
String get modalBarrierDismissLabel => 'Maak toe';
@override
String get noSpellCheckReplacementsLabel => 'Geen plaasvervangers gevind nie';
@override
String get pasteButtonLabel => 'Plak';
@override
String get postMeridiemAbbreviation => 'nm.';
@override
String get searchTextFieldPlaceholderLabel => 'Soek';
@override
String get searchWebButtonLabel => 'Deursoek web';
@override
String get selectAllButtonLabel => 'Kies alles';
@override
String get shareButtonLabel => 'Deel …';
@override
String get tabSemanticsLabelRaw => r'Oortjie $tabIndex van $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'uur';
@override
String get timerPickerHourLabelOther => 'uur';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min.';
@override
String get timerPickerMinuteLabelOther => 'min.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'sek.';
@override
String get timerPickerSecondLabelOther => 'sek.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Vandag';
}
/// The translations for Amharic (`am`).
class CupertinoLocalizationAm extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Amharic.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationAm({
super.localeName = 'am',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'ማንቂያ';
@override
String get anteMeridiemAbbreviation => 'ጥዋት';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'ቅዳ';
@override
String get cutButtonLabel => 'ቁረጥ';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour ሰዓት';
@override
String get datePickerHourSemanticsLabelOther => r'$hour ሰዓት';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 ደቂቃ';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute ደቂቃዎች';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'ይመልከቱ';
@override
String get menuDismissLabel => 'ምናሌን አሰናብት';
@override
String get modalBarrierDismissLabel => 'አሰናብት';
@override
String get noSpellCheckReplacementsLabel => 'ምንም ተተኪዎች አልተገኙም';
@override
String get pasteButtonLabel => 'ለጥፍ';
@override
String get postMeridiemAbbreviation => 'ከሰዓት';
@override
String get searchTextFieldPlaceholderLabel => 'ፍለጋ';
@override
String get searchWebButtonLabel => 'ድርን ፈልግ';
@override
String get selectAllButtonLabel => 'ሁሉንም ምረጥ';
@override
String get shareButtonLabel => 'አጋራ...';
@override
String get tabSemanticsLabelRaw => r'ትር $tabIndex ከ$tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'ሰዓት';
@override
String get timerPickerHourLabelOther => 'ሰዓቶች';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'ደቂቃ';
@override
String get timerPickerMinuteLabelOther => 'ደቂቃ';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'ሴኮ';
@override
String get timerPickerSecondLabelOther => 'ሴኮ';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'ዛሬ';
}
/// The translations for Arabic (`ar`).
class CupertinoLocalizationAr extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Arabic.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationAr({
super.localeName = 'ar',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'تنبيه';
@override
String get anteMeridiemAbbreviation => 'ص';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'نسخ';
@override
String get cutButtonLabel => 'قص';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => r'$hour بالضبط';
@override
String? get datePickerHourSemanticsLabelMany => r'$hour بالضبط';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour بالضبط';
@override
String get datePickerHourSemanticsLabelOther => r'$hour بالضبط';
@override
String? get datePickerHourSemanticsLabelTwo => r'$hour بالضبط';
@override
String? get datePickerHourSemanticsLabelZero => r'$hour بالضبط';
@override
String? get datePickerMinuteSemanticsLabelFew => r'$minute دقائق';
@override
String? get datePickerMinuteSemanticsLabelMany => r'$minute دقيقة';
@override
String? get datePickerMinuteSemanticsLabelOne => 'دقيقة واحدة';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute دقيقة';
@override
String? get datePickerMinuteSemanticsLabelTwo => r'دقيقتان ($minute)';
@override
String? get datePickerMinuteSemanticsLabelZero => r'$minute دقيقة';
@override
String get lookUpButtonLabel => 'النظر إلى أعلى';
@override
String get menuDismissLabel => 'إغلاق القائمة';
@override
String get modalBarrierDismissLabel => 'رفض';
@override
String get noSpellCheckReplacementsLabel => 'لم يتم العثور على بدائل';
@override
String get pasteButtonLabel => 'لصق';
@override
String get postMeridiemAbbreviation => 'م';
@override
String get searchTextFieldPlaceholderLabel => 'بحث';
@override
String get searchWebButtonLabel => 'البحث على الويب';
@override
String get selectAllButtonLabel => 'اختيار الكل';
@override
String get shareButtonLabel => 'مشاركة…';
@override
String get tabSemanticsLabelRaw => r'علامة التبويب $tabIndex من $tabCount';
@override
String? get timerPickerHourLabelFew => 'ساعات';
@override
String? get timerPickerHourLabelMany => 'ساعة';
@override
String? get timerPickerHourLabelOne => 'ساعة';
@override
String get timerPickerHourLabelOther => 'ساعة';
@override
String? get timerPickerHourLabelTwo => 'ساعتان';
@override
String? get timerPickerHourLabelZero => 'ساعة';
@override
String? get timerPickerMinuteLabelFew => 'دقائق';
@override
String? get timerPickerMinuteLabelMany => 'دقيقة';
@override
String? get timerPickerMinuteLabelOne => 'دقيقة واحدة';
@override
String get timerPickerMinuteLabelOther => 'دقيقة';
@override
String? get timerPickerMinuteLabelTwo => 'دقيقتان';
@override
String? get timerPickerMinuteLabelZero => 'دقيقة';
@override
String? get timerPickerSecondLabelFew => 'ثوانٍ';
@override
String? get timerPickerSecondLabelMany => 'ثانية';
@override
String? get timerPickerSecondLabelOne => 'ثانية واحدة';
@override
String get timerPickerSecondLabelOther => 'ثانية';
@override
String? get timerPickerSecondLabelTwo => 'ثانيتان';
@override
String? get timerPickerSecondLabelZero => 'ثانية';
@override
String get todayLabel => 'اليوم';
}
/// The translations for Assamese (`as`).
class CupertinoLocalizationAs extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Assamese.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationAs({
super.localeName = 'as',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'সতৰ্কবাৰ্তা';
@override
String get anteMeridiemAbbreviation => 'পূৰ্বাহ্ন';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'প্ৰতিলিপি কৰক';
@override
String get cutButtonLabel => 'কাট কৰক';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour বাজিছে';
@override
String get datePickerHourSemanticsLabelOther => r'$hour বাজিছে';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '১মিনিট';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minuteমিনিট';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'ওপৰলৈ চাওক';
@override
String get menuDismissLabel => 'অগ্ৰাহ্য কৰাৰ মেনু';
@override
String get modalBarrierDismissLabel => 'অগ্ৰাহ্য কৰক';
@override
String get noSpellCheckReplacementsLabel => 'এইটোৰ সলনি ব্যৱহাৰ কৰিব পৰা শব্দ পোৱা নগ’ল';
@override
String get pasteButtonLabel => "পে'ষ্ট কৰক";
@override
String get postMeridiemAbbreviation => 'অপৰাহ্ন';
@override
String get searchTextFieldPlaceholderLabel => 'সন্ধান কৰক';
@override
String get searchWebButtonLabel => 'ৱেবত সন্ধান কৰক';
@override
String get selectAllButtonLabel => 'সকলো বাছনি কৰক';
@override
String get shareButtonLabel => 'শ্বেয়াৰ কৰক…';
@override
String get tabSemanticsLabelRaw => r'$tabCount টা টেবৰ $tabIndex নম্বৰটো';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'ঘণ্টা';
@override
String get timerPickerHourLabelOther => 'ঘণ্টা';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'মিনিট।';
@override
String get timerPickerMinuteLabelOther => 'মিনিট।';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'ছেকেণ্ড।';
@override
String get timerPickerSecondLabelOther => 'ছেকেণ্ড।';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'আজি';
}
/// The translations for Azerbaijani (`az`).
class CupertinoLocalizationAz extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Azerbaijani.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationAz({
super.localeName = 'az',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Bildiriş';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopyalayın';
@override
String get cutButtonLabel => 'Kəsin';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'Saat $hour';
@override
String get datePickerHourSemanticsLabelOther => r'Saat $hour';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 dəqiqə';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute dəqiqə';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Axtarın';
@override
String get menuDismissLabel => 'Menyunu qapadın';
@override
String get modalBarrierDismissLabel => 'İmtina edin';
@override
String get noSpellCheckReplacementsLabel => 'Əvəzləmə Tapılmadı';
@override
String get pasteButtonLabel => 'Yerləşdirin';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Axtarın';
@override
String get searchWebButtonLabel => 'Vebdə axtarın';
@override
String get selectAllButtonLabel => 'Hamısını seçin';
@override
String get shareButtonLabel => 'Paylaşın...';
@override
String get tabSemanticsLabelRaw => r'Tab $tabIndex/$tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'saat';
@override
String get timerPickerHourLabelOther => 'saat';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'dəq.';
@override
String get timerPickerMinuteLabelOther => 'dəq.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'san.';
@override
String get timerPickerSecondLabelOther => 'san.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Bu gün';
}
/// The translations for Belarusian (`be`).
class CupertinoLocalizationBe extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Belarusian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationBe({
super.localeName = 'be',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Абвестка';
@override
String get anteMeridiemAbbreviation => 'раніцы';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Капіраваць';
@override
String get cutButtonLabel => 'Выразаць';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => r'$hour гадзіны нуль хвілін';
@override
String? get datePickerHourSemanticsLabelMany => r'$hour гадзін нуль хвілін';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour гадзіна нуль хвілін';
@override
String get datePickerHourSemanticsLabelOther => r'$hour гадзіны нуль хвілін';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => r'$minute хвіліны';
@override
String? get datePickerMinuteSemanticsLabelMany => r'$minute хвілін';
@override
String? get datePickerMinuteSemanticsLabelOne => '1 хвіліна';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute хвіліны';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Знайсці';
@override
String get menuDismissLabel => 'Закрыць меню';
@override
String get modalBarrierDismissLabel => 'Адхіліць';
@override
String get noSpellCheckReplacementsLabel => 'Замен не знойдзена';
@override
String get pasteButtonLabel => 'Уставіць';
@override
String get postMeridiemAbbreviation => 'вечара';
@override
String get searchTextFieldPlaceholderLabel => 'Пошук';
@override
String get searchWebButtonLabel => 'Пошук у сетцы';
@override
String get selectAllButtonLabel => 'Выбраць усе';
@override
String get shareButtonLabel => 'Абагуліць...';
@override
String get tabSemanticsLabelRaw => r'Укладка $tabIndex з $tabCount';
@override
String? get timerPickerHourLabelFew => 'гадзіны';
@override
String? get timerPickerHourLabelMany => 'гадзін';
@override
String? get timerPickerHourLabelOne => 'гадзіна';
@override
String get timerPickerHourLabelOther => 'гадзіны';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => 'хв';
@override
String? get timerPickerMinuteLabelMany => 'хв';
@override
String? get timerPickerMinuteLabelOne => 'хв';
@override
String get timerPickerMinuteLabelOther => 'хв';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => 'с';
@override
String? get timerPickerSecondLabelMany => 'с';
@override
String? get timerPickerSecondLabelOne => 'с';
@override
String get timerPickerSecondLabelOther => 'с';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Сёння';
}
/// The translations for Bulgarian (`bg`).
class CupertinoLocalizationBg extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Bulgarian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationBg({
super.localeName = 'bg',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Сигнал';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Копиране';
@override
String get cutButtonLabel => 'Изрязване';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour часа';
@override
String get datePickerHourSemanticsLabelOther => r'$hour часа';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 минута';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute минути';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Look Up';
@override
String get menuDismissLabel => 'Отхвърляне на менюто';
@override
String get modalBarrierDismissLabel => 'Отхвърляне';
@override
String get noSpellCheckReplacementsLabel => 'Не бяха намерени замествания';
@override
String get pasteButtonLabel => 'Поставяне';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Търсене';
@override
String get searchWebButtonLabel => 'Търсене в мрежата';
@override
String get selectAllButtonLabel => 'Избиране на всички';
@override
String get shareButtonLabel => 'Споделяне...';
@override
String get tabSemanticsLabelRaw => r'Раздел $tabIndex от $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'час';
@override
String get timerPickerHourLabelOther => 'часа';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'мин';
@override
String get timerPickerMinuteLabelOther => 'мин';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'сек';
@override
String get timerPickerSecondLabelOther => 'сек';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Днес';
}
/// The translations for Bengali Bangla (`bn`).
class CupertinoLocalizationBn extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Bengali Bangla.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationBn({
super.localeName = 'bn',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'সতর্কতা';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'কপি করুন';
@override
String get cutButtonLabel => 'কাট করুন';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hourটা বাজে';
@override
String get datePickerHourSemanticsLabelOther => r'$hourটা বাজে';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '১ মিনিট';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute মিনিট';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'লুক-আপ';
@override
String get menuDismissLabel => 'বাতিল করার মেনু';
@override
String get modalBarrierDismissLabel => 'খারিজ করুন';
@override
String get noSpellCheckReplacementsLabel => 'কোনও বিকল্প বানান দেখানো হয়নি';
@override
String get pasteButtonLabel => 'পেস্ট করুন';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'সার্চ করুন';
@override
String get searchWebButtonLabel => 'ওয়েবে সার্চ করুন';
@override
String get selectAllButtonLabel => 'সব বেছে নিন';
@override
String get shareButtonLabel => 'শেয়ার করুন...';
@override
String get tabSemanticsLabelRaw => r'$tabCount-এর মধ্যে $tabIndex নম্বর ট্যাব';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'ঘণ্টা';
@override
String get timerPickerHourLabelOther => 'ঘণ্টা';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'মিনিট।';
@override
String get timerPickerMinuteLabelOther => 'মিনিট।';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'সেকেন্ড।';
@override
String get timerPickerSecondLabelOther => 'সেকেন্ড।';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'আজ';
}
/// The translations for Bosnian (`bs`).
class CupertinoLocalizationBs extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Bosnian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationBs({
super.localeName = 'bs',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Upozorenje';
@override
String get anteMeridiemAbbreviation => 'prijepodne';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopiraj';
@override
String get cutButtonLabel => 'Izreži';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => r'$hour sata';
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour sat';
@override
String get datePickerHourSemanticsLabelOther => r'$hour sati';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => r'$minute minute';
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minuta';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minuta';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Pogled nagore';
@override
String get menuDismissLabel => 'Odbacivanje menija';
@override
String get modalBarrierDismissLabel => 'Odbaci';
@override
String get noSpellCheckReplacementsLabel => 'Nije pronađena nijedna zamjena';
@override
String get pasteButtonLabel => 'Zalijepi';
@override
String get postMeridiemAbbreviation => 'poslijepodne';
@override
String get searchTextFieldPlaceholderLabel => 'Pretraživanje';
@override
String get searchWebButtonLabel => 'Pretraži Web';
@override
String get selectAllButtonLabel => 'Odaberi sve';
@override
String get shareButtonLabel => 'Dijeli...';
@override
String get tabSemanticsLabelRaw => r'Kartica $tabIndex od $tabCount';
@override
String? get timerPickerHourLabelFew => 'sata';
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'sat';
@override
String get timerPickerHourLabelOther => 'sati';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => 'min';
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min';
@override
String get timerPickerMinuteLabelOther => 'min';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => 'sec.';
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'sec.';
@override
String get timerPickerSecondLabelOther => 'sec.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Danas';
}
/// The translations for Catalan Valencian (`ca`).
class CupertinoLocalizationCa extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Catalan Valencian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationCa({
super.localeName = 'ca',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Alerta';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Copia';
@override
String get cutButtonLabel => 'Retalla';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punt';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punt';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minut';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minuts';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Mira amunt';
@override
String get menuDismissLabel => 'Ignora el menú';
@override
String get modalBarrierDismissLabel => 'Ignora';
@override
String get noSpellCheckReplacementsLabel => "No s'ha trobat cap substitució";
@override
String get pasteButtonLabel => 'Enganxa';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Cerca';
@override
String get searchWebButtonLabel => 'Cerca al web';
@override
String get selectAllButtonLabel => 'Seleccionar-ho tot';
@override
String get shareButtonLabel => 'Comparteix...';
@override
String get tabSemanticsLabelRaw => r'Pestanya $tabIndex de $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'hora';
@override
String get timerPickerHourLabelOther => 'hores';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min';
@override
String get timerPickerMinuteLabelOther => 'min';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 's';
@override
String get timerPickerSecondLabelOther => 's';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Avui';
}
/// The translations for Czech (`cs`).
class CupertinoLocalizationCs extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Czech.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationCs({
super.localeName = 'cs',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Upozornění';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopírovat';
@override
String get cutButtonLabel => 'Vyjmout';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => r'$hour hodiny';
@override
String? get datePickerHourSemanticsLabelMany => r'$hour hodiny';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour hodina';
@override
String get datePickerHourSemanticsLabelOther => r'$hour hodin';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => r'$minute minuty';
@override
String? get datePickerMinuteSemanticsLabelMany => r'$minute minuty';
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minuta';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minut';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Vyhledat';
@override
String get menuDismissLabel => 'Zavřít nabídku';
@override
String get modalBarrierDismissLabel => 'Zavřít';
@override
String get noSpellCheckReplacementsLabel => 'Žádná nahrazení nenalezena';
@override
String get pasteButtonLabel => 'Vložit';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Hledat';
@override
String get searchWebButtonLabel => 'Vyhledávat na webu';
@override
String get selectAllButtonLabel => 'Vybrat vše';
@override
String get shareButtonLabel => 'Sdílet…';
@override
String get tabSemanticsLabelRaw => r'Karta $tabIndex z $tabCount';
@override
String? get timerPickerHourLabelFew => 'hodiny';
@override
String? get timerPickerHourLabelMany => 'hodiny';
@override
String? get timerPickerHourLabelOne => 'hodina';
@override
String get timerPickerHourLabelOther => 'hodin';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => 'min';
@override
String? get timerPickerMinuteLabelMany => 'min';
@override
String? get timerPickerMinuteLabelOne => 'min';
@override
String get timerPickerMinuteLabelOther => 'min';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => 's';
@override
String? get timerPickerSecondLabelMany => 's';
@override
String? get timerPickerSecondLabelOne => 's';
@override
String get timerPickerSecondLabelOther => 's';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Dnes';
}
/// The translations for Welsh (`cy`).
class CupertinoLocalizationCy extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Welsh.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationCy({
super.localeName = 'cy',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Rhybudd';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Copïo';
@override
String get cutButtonLabel => 'Torri';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => r"$hour o'r gloch";
@override
String? get datePickerHourSemanticsLabelMany => r"$hour o'r gloch";
@override
String? get datePickerHourSemanticsLabelOne => r"$hour o'r gloch";
@override
String get datePickerHourSemanticsLabelOther => r"$hour o'r gloch";
@override
String? get datePickerHourSemanticsLabelTwo => r"$hour o'r gloch";
@override
String? get datePickerHourSemanticsLabelZero => r"$hour o'r gloch";
@override
String? get datePickerMinuteSemanticsLabelFew => r'$minute munud';
@override
String? get datePickerMinuteSemanticsLabelMany => r'$minute munud';
@override
String? get datePickerMinuteSemanticsLabelOne => '1 funud';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute munud';
@override
String? get datePickerMinuteSemanticsLabelTwo => r'$minute funud';
@override
String? get datePickerMinuteSemanticsLabelZero => r'$minute munud';
@override
String get lookUpButtonLabel => 'Chwilio';
@override
String get menuDismissLabel => "Diystyru'r ddewislen";
@override
String get modalBarrierDismissLabel => 'Diystyru';
@override
String get noSpellCheckReplacementsLabel => "Dim Ailosodiadau wedi'u Canfod";
@override
String get pasteButtonLabel => 'Gludo';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Chwilio';
@override
String get searchWebButtonLabel => "Chwilio'r We";
@override
String get selectAllButtonLabel => 'Dewis y Cyfan';
@override
String get shareButtonLabel => 'Rhannu...';
@override
String get tabSemanticsLabelRaw => r'Tab $tabIndex o $tabCount';
@override
String? get timerPickerHourLabelFew => 'awr';
@override
String? get timerPickerHourLabelMany => 'awr';
@override
String? get timerPickerHourLabelOne => 'awr';
@override
String get timerPickerHourLabelOther => 'awr';
@override
String? get timerPickerHourLabelTwo => 'awr';
@override
String? get timerPickerHourLabelZero => 'awr';
@override
String? get timerPickerMinuteLabelFew => 'munud';
@override
String? get timerPickerMinuteLabelMany => 'munud';
@override
String? get timerPickerMinuteLabelOne => 'funud';
@override
String get timerPickerMinuteLabelOther => 'munud';
@override
String? get timerPickerMinuteLabelTwo => 'funud';
@override
String? get timerPickerMinuteLabelZero => 'munud';
@override
String? get timerPickerSecondLabelFew => 'eiliad';
@override
String? get timerPickerSecondLabelMany => 'eiliad';
@override
String? get timerPickerSecondLabelOne => 'eiliad';
@override
String get timerPickerSecondLabelOther => 'eiliad';
@override
String? get timerPickerSecondLabelTwo => 'eiliad';
@override
String? get timerPickerSecondLabelZero => 'eiliad';
@override
String get todayLabel => 'Heddiw';
}
/// The translations for Danish (`da`).
class CupertinoLocalizationDa extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Danish.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationDa({
super.localeName = 'da',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Underretning';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopiér';
@override
String get cutButtonLabel => 'Klip';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'klokken $hour';
@override
String get datePickerHourSemanticsLabelOther => r'klokken $hour';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minut';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minutter';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Slå op';
@override
String get menuDismissLabel => 'Luk menu';
@override
String get modalBarrierDismissLabel => 'Afvis';
@override
String get noSpellCheckReplacementsLabel => 'Der blev ikke fundet nogen erstatninger';
@override
String get pasteButtonLabel => 'Indsæt';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Søg';
@override
String get searchWebButtonLabel => 'Søg på nettet';
@override
String get selectAllButtonLabel => 'Vælg alt';
@override
String get shareButtonLabel => 'Del…';
@override
String get tabSemanticsLabelRaw => r'Fane $tabIndex af $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'time';
@override
String get timerPickerHourLabelOther => 'timer';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min.';
@override
String get timerPickerMinuteLabelOther => 'min.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'sek.';
@override
String get timerPickerSecondLabelOther => 'sek.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'I dag';
}
/// The translations for German (`de`).
class CupertinoLocalizationDe extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for German.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationDe({
super.localeName = 'de',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Benachrichtigung';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopieren';
@override
String get cutButtonLabel => 'Ausschneiden';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour Uhr';
@override
String get datePickerHourSemanticsLabelOther => r'$hour Uhr';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 Minute';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute Minuten';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Nachschlagen';
@override
String get menuDismissLabel => 'Menü schließen';
@override
String get modalBarrierDismissLabel => 'Schließen';
@override
String get noSpellCheckReplacementsLabel => 'Keine Ersetzungen gefunden';
@override
String get pasteButtonLabel => 'Einsetzen';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Suche';
@override
String get searchWebButtonLabel => 'Im Web suchen';
@override
String get selectAllButtonLabel => 'Alle auswählen';
@override
String get shareButtonLabel => 'Teilen…';
@override
String get tabSemanticsLabelRaw => r'Tab $tabIndex von $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'Stunde';
@override
String get timerPickerHourLabelOther => 'Stunden';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'Min.';
@override
String get timerPickerMinuteLabelOther => 'Min.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 's';
@override
String get timerPickerSecondLabelOther => 's';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Heute';
}
/// The translations for German, as used in Switzerland (`de_CH`).
class CupertinoLocalizationDeCh extends CupertinoLocalizationDe {
/// Create an instance of the translation bundle for German, as used in Switzerland.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationDeCh({
super.localeName = 'de_CH',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get selectAllButtonLabel => 'Alles auswählen';
@override
String get modalBarrierDismissLabel => 'Schliessen';
}
/// The translations for Modern Greek (`el`).
class CupertinoLocalizationEl extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Modern Greek.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEl({
super.localeName = 'el',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Ειδοποίηση';
@override
String get anteMeridiemAbbreviation => 'π.μ.';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Αντιγραφή';
@override
String get cutButtonLabel => 'Αποκοπή';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour ακριβώς';
@override
String get datePickerHourSemanticsLabelOther => r'$hour ακριβώς';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 λεπτό';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute λεπτά';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Look Up';
@override
String get menuDismissLabel => 'Παράβλεψη μενού';
@override
String get modalBarrierDismissLabel => 'Παράβλεψη';
@override
String get noSpellCheckReplacementsLabel => 'Δεν βρέθηκαν αντικαταστάσεις';
@override
String get pasteButtonLabel => 'Επικόλληση';
@override
String get postMeridiemAbbreviation => 'μ.μ.';
@override
String get searchTextFieldPlaceholderLabel => 'Αναζήτηση';
@override
String get searchWebButtonLabel => 'Αναζήτηση στον ιστό';
@override
String get selectAllButtonLabel => 'Επιλογή όλων';
@override
String get shareButtonLabel => 'Κοινοποίηση…';
@override
String get tabSemanticsLabelRaw => r'Καρτέλα $tabIndex από $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'ώρα';
@override
String get timerPickerHourLabelOther => 'ώρες';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'λεπ.';
@override
String get timerPickerMinuteLabelOther => 'λεπ.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'δευτ.';
@override
String get timerPickerSecondLabelOther => 'δευτ.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Σήμερα';
}
/// The translations for English (`en`).
class CupertinoLocalizationEn extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for English.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEn({
super.localeName = 'en',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Alert';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Copy';
@override
String get cutButtonLabel => 'Cut';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r"$hour o'clock";
@override
String get datePickerHourSemanticsLabelOther => r"$hour o'clock";
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minute';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minutes';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Look Up';
@override
String get menuDismissLabel => 'Dismiss menu';
@override
String get modalBarrierDismissLabel => 'Dismiss';
@override
String get noSpellCheckReplacementsLabel => 'No Replacements Found';
@override
String get pasteButtonLabel => 'Paste';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Search';
@override
String get searchWebButtonLabel => 'Search Web';
@override
String get selectAllButtonLabel => 'Select All';
@override
String get shareButtonLabel => 'Share...';
@override
String get tabSemanticsLabelRaw => r'Tab $tabIndex of $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'hour';
@override
String get timerPickerHourLabelOther => 'hours';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min.';
@override
String get timerPickerMinuteLabelOther => 'min.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'sec.';
@override
String get timerPickerSecondLabelOther => 'sec.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Today';
}
/// The translations for English, as used in Australia (`en_AU`).
class CupertinoLocalizationEnAu extends CupertinoLocalizationEn {
/// Create an instance of the translation bundle for English, as used in Australia.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEnAu({
super.localeName = 'en_AU',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get lookUpButtonLabel => 'Look up';
@override
String get noSpellCheckReplacementsLabel => 'No replacements found';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get selectAllButtonLabel => 'Select all';
}
/// The translations for English, as used in Canada (`en_CA`).
class CupertinoLocalizationEnCa extends CupertinoLocalizationEn {
/// Create an instance of the translation bundle for English, as used in Canada.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEnCa({
super.localeName = 'en_CA',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get datePickerDateOrderString => 'dmy';
@override
String get selectAllButtonLabel => 'Select all';
}
/// The translations for English, as used in the United Kingdom (`en_GB`).
class CupertinoLocalizationEnGb extends CupertinoLocalizationEn {
/// Create an instance of the translation bundle for English, as used in the United Kingdom.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEnGb({
super.localeName = 'en_GB',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get lookUpButtonLabel => 'Look up';
@override
String get noSpellCheckReplacementsLabel => 'No replacements found';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get selectAllButtonLabel => 'Select all';
}
/// The translations for English, as used in Ireland (`en_IE`).
class CupertinoLocalizationEnIe extends CupertinoLocalizationEn {
/// Create an instance of the translation bundle for English, as used in Ireland.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEnIe({
super.localeName = 'en_IE',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get lookUpButtonLabel => 'Look up';
@override
String get noSpellCheckReplacementsLabel => 'No replacements found';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get selectAllButtonLabel => 'Select all';
}
/// The translations for English, as used in India (`en_IN`).
class CupertinoLocalizationEnIn extends CupertinoLocalizationEn {
/// Create an instance of the translation bundle for English, as used in India.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEnIn({
super.localeName = 'en_IN',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get lookUpButtonLabel => 'Look up';
@override
String get noSpellCheckReplacementsLabel => 'No replacements found';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get selectAllButtonLabel => 'Select all';
}
/// The translations for English, as used in New Zealand (`en_NZ`).
class CupertinoLocalizationEnNz extends CupertinoLocalizationEn {
/// Create an instance of the translation bundle for English, as used in New Zealand.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEnNz({
super.localeName = 'en_NZ',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get lookUpButtonLabel => 'Look up';
@override
String get noSpellCheckReplacementsLabel => 'No replacements found';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get selectAllButtonLabel => 'Select all';
}
/// The translations for English, as used in Singapore (`en_SG`).
class CupertinoLocalizationEnSg extends CupertinoLocalizationEn {
/// Create an instance of the translation bundle for English, as used in Singapore.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEnSg({
super.localeName = 'en_SG',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get lookUpButtonLabel => 'Look up';
@override
String get noSpellCheckReplacementsLabel => 'No replacements found';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get selectAllButtonLabel => 'Select all';
}
/// The translations for English, as used in South Africa (`en_ZA`).
class CupertinoLocalizationEnZa extends CupertinoLocalizationEn {
/// Create an instance of the translation bundle for English, as used in South Africa.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEnZa({
super.localeName = 'en_ZA',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get lookUpButtonLabel => 'Look up';
@override
String get noSpellCheckReplacementsLabel => 'No replacements found';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get selectAllButtonLabel => 'Select all';
}
/// The translations for Spanish Castilian (`es`).
class CupertinoLocalizationEs extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Spanish Castilian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEs({
super.localeName = 'es',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Alerta';
@override
String get anteMeridiemAbbreviation => 'a. m.';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Copiar';
@override
String get cutButtonLabel => 'Cortar';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minuto';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minutos';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Buscador visual';
@override
String get menuDismissLabel => 'Cerrar menú';
@override
String get modalBarrierDismissLabel => 'Cerrar';
@override
String get noSpellCheckReplacementsLabel => 'No se ha encontrado ninguna sustitución';
@override
String get pasteButtonLabel => 'Pegar';
@override
String get postMeridiemAbbreviation => 'p. m.';
@override
String get searchTextFieldPlaceholderLabel => 'Buscar';
@override
String get searchWebButtonLabel => 'Buscar en la Web';
@override
String get selectAllButtonLabel => 'Seleccionar todo';
@override
String get shareButtonLabel => 'Compartir...';
@override
String get tabSemanticsLabelRaw => r'Pestaña $tabIndex de $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'hora';
@override
String get timerPickerHourLabelOther => 'horas';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min';
@override
String get timerPickerMinuteLabelOther => 'min';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 's';
@override
String get timerPickerSecondLabelOther => 's';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Hoy';
}
/// The translations for Spanish Castilian, as used in Latin America and the Caribbean (`es_419`).
class CupertinoLocalizationEs419 extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in Latin America and the Caribbean.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEs419({
super.localeName = 'es_419',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in Argentina (`es_AR`).
class CupertinoLocalizationEsAr extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in Argentina.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsAr({
super.localeName = 'es_AR',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in Bolivia (`es_BO`).
class CupertinoLocalizationEsBo extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in Bolivia.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsBo({
super.localeName = 'es_BO',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in Chile (`es_CL`).
class CupertinoLocalizationEsCl extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in Chile.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsCl({
super.localeName = 'es_CL',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in Colombia (`es_CO`).
class CupertinoLocalizationEsCo extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in Colombia.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsCo({
super.localeName = 'es_CO',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in Costa Rica (`es_CR`).
class CupertinoLocalizationEsCr extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in Costa Rica.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsCr({
super.localeName = 'es_CR',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in the Dominican Republic (`es_DO`).
class CupertinoLocalizationEsDo extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in the Dominican Republic.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsDo({
super.localeName = 'es_DO',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in Ecuador (`es_EC`).
class CupertinoLocalizationEsEc extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in Ecuador.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsEc({
super.localeName = 'es_EC',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in Guatemala (`es_GT`).
class CupertinoLocalizationEsGt extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in Guatemala.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsGt({
super.localeName = 'es_GT',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in Honduras (`es_HN`).
class CupertinoLocalizationEsHn extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in Honduras.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsHn({
super.localeName = 'es_HN',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in Mexico (`es_MX`).
class CupertinoLocalizationEsMx extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in Mexico.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsMx({
super.localeName = 'es_MX',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in Nicaragua (`es_NI`).
class CupertinoLocalizationEsNi extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in Nicaragua.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsNi({
super.localeName = 'es_NI',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in Panama (`es_PA`).
class CupertinoLocalizationEsPa extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in Panama.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsPa({
super.localeName = 'es_PA',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in Peru (`es_PE`).
class CupertinoLocalizationEsPe extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in Peru.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsPe({
super.localeName = 'es_PE',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in Puerto Rico (`es_PR`).
class CupertinoLocalizationEsPr extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in Puerto Rico.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsPr({
super.localeName = 'es_PR',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in Paraguay (`es_PY`).
class CupertinoLocalizationEsPy extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in Paraguay.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsPy({
super.localeName = 'es_PY',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in El Salvador (`es_SV`).
class CupertinoLocalizationEsSv extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in El Salvador.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsSv({
super.localeName = 'es_SV',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in the United States (`es_US`).
class CupertinoLocalizationEsUs extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in the United States.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsUs({
super.localeName = 'es_US',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in Uruguay (`es_UY`).
class CupertinoLocalizationEsUy extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in Uruguay.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsUy({
super.localeName = 'es_UY',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Spanish Castilian, as used in Venezuela (`es_VE`).
class CupertinoLocalizationEsVe extends CupertinoLocalizationEs {
/// Create an instance of the translation bundle for Spanish Castilian, as used in Venezuela.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEsVe({
super.localeName = 'es_VE',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Compartir…';
@override
String get lookUpButtonLabel => 'Mirar hacia arriba';
@override
String get noSpellCheckReplacementsLabel => 'No se encontraron reemplazos';
@override
String get menuDismissLabel => 'Descartar menú';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get modalBarrierDismissLabel => 'Descartar';
}
/// The translations for Estonian (`et`).
class CupertinoLocalizationEt extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Estonian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEt({
super.localeName = 'et',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Märguanne';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopeeri';
@override
String get cutButtonLabel => 'Lõika';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'Kell $hour';
@override
String get datePickerHourSemanticsLabelOther => r'Kell $hour';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minut';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minutit';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Look Up';
@override
String get menuDismissLabel => 'Sulge menüü';
@override
String get modalBarrierDismissLabel => 'Loobu';
@override
String get noSpellCheckReplacementsLabel => 'Asendusi ei leitud';
@override
String get pasteButtonLabel => 'Kleebi';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Otsige';
@override
String get searchWebButtonLabel => 'Otsi veebist';
@override
String get selectAllButtonLabel => 'Vali kõik';
@override
String get shareButtonLabel => 'Jaga …';
@override
String get tabSemanticsLabelRaw => r'$tabIndex. vaheleht $tabCount-st';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'tund';
@override
String get timerPickerHourLabelOther => 'tundi';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min';
@override
String get timerPickerMinuteLabelOther => 'min';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 's';
@override
String get timerPickerSecondLabelOther => 's';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Täna';
}
/// The translations for Basque (`eu`).
class CupertinoLocalizationEu extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Basque.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationEu({
super.localeName = 'eu',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Alerta';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopiatu';
@override
String get cutButtonLabel => 'Ebaki';
@override
String get datePickerDateOrderString => 'ymd';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'Ordu$houra da';
@override
String get datePickerHourSemanticsLabelOther => r'$hourak dira';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => 'Minutu bat';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minutu';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Bilatu';
@override
String get menuDismissLabel => 'Baztertu menua';
@override
String get modalBarrierDismissLabel => 'Baztertu';
@override
String get noSpellCheckReplacementsLabel => 'Ez da aurkitu ordezteko hitzik';
@override
String get pasteButtonLabel => 'Itsatsi';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Bilatu';
@override
String get searchWebButtonLabel => 'Bilatu sarean';
@override
String get selectAllButtonLabel => 'Hautatu dena';
@override
String get shareButtonLabel => 'Partekatu...';
@override
String get tabSemanticsLabelRaw => r'$tabIndex/$tabCount fitxa';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'ordu';
@override
String get timerPickerHourLabelOther => 'ordu';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min.';
@override
String get timerPickerMinuteLabelOther => 'min.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 's';
@override
String get timerPickerSecondLabelOther => 's';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Gaur';
}
/// The translations for Persian (`fa`).
class CupertinoLocalizationFa extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Persian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationFa({
super.localeName = 'fa',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'هشدار';
@override
String get anteMeridiemAbbreviation => 'ق.ظ.';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'کپی';
@override
String get cutButtonLabel => 'برش';
@override
String get datePickerDateOrderString => 'ymd';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'ساعت $hour';
@override
String get datePickerHourSemanticsLabelOther => r'ساعت $hour';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '۱ دقیقه';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute دقیقه';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'جستجو';
@override
String get menuDismissLabel => 'بستن منو';
@override
String get modalBarrierDismissLabel => 'نپذیرفتن';
@override
String get noSpellCheckReplacementsLabel => 'جایگزینی پیدا نشد';
@override
String get pasteButtonLabel => 'جایگذاری';
@override
String get postMeridiemAbbreviation => 'ب.ظ.';
@override
String get searchTextFieldPlaceholderLabel => 'جستجو';
@override
String get searchWebButtonLabel => 'جستجو در وب';
@override
String get selectAllButtonLabel => 'انتخاب همه';
@override
String get shareButtonLabel => 'همرسانی…';
@override
String get tabSemanticsLabelRaw => r'برگه $tabIndex از $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'ساعت';
@override
String get timerPickerHourLabelOther => 'ساعت';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'دقیقه';
@override
String get timerPickerMinuteLabelOther => 'دقیقه';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'ثانیه';
@override
String get timerPickerSecondLabelOther => 'ثانیه';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'امروز';
}
/// The translations for Finnish (`fi`).
class CupertinoLocalizationFi extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Finnish.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationFi({
super.localeName = 'fi',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Ilmoitus';
@override
String get anteMeridiemAbbreviation => 'ap';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopioi';
@override
String get cutButtonLabel => 'Leikkaa';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'klo $hour';
@override
String get datePickerHourSemanticsLabelOther => r'klo $hour';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minuutti';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minuuttia';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Hae';
@override
String get menuDismissLabel => 'Hylkää valikko';
@override
String get modalBarrierDismissLabel => 'Ohita';
@override
String get noSpellCheckReplacementsLabel => 'Korvaavia sanoja ei löydy';
@override
String get pasteButtonLabel => 'Liitä';
@override
String get postMeridiemAbbreviation => 'ip';
@override
String get searchTextFieldPlaceholderLabel => 'Hae';
@override
String get searchWebButtonLabel => 'Hae verkosta';
@override
String get selectAllButtonLabel => 'Valitse kaikki';
@override
String get shareButtonLabel => 'Jaa…';
@override
String get tabSemanticsLabelRaw => r'Välilehti $tabIndex kautta $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'tunti';
@override
String get timerPickerHourLabelOther => 'tuntia';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min';
@override
String get timerPickerMinuteLabelOther => 'min';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 's';
@override
String get timerPickerSecondLabelOther => 's';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Tänään';
}
/// The translations for Filipino Pilipino (`fil`).
class CupertinoLocalizationFil extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Filipino Pilipino.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationFil({
super.localeName = 'fil',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Alerto';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopyahin';
@override
String get cutButtonLabel => 'I-cut';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'Ala $hour';
@override
String get datePickerHourSemanticsLabelOther => r'Alas $hour';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minuto';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute na minuto';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Tumingin sa Itaas';
@override
String get menuDismissLabel => 'I-dismiss ang menu';
@override
String get modalBarrierDismissLabel => 'I-dismiss';
@override
String get noSpellCheckReplacementsLabel => 'Walang Nahanap na Kapalit';
@override
String get pasteButtonLabel => 'I-paste';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Hanapin';
@override
String get searchWebButtonLabel => 'Maghanap sa Web';
@override
String get selectAllButtonLabel => 'Piliin Lahat';
@override
String get shareButtonLabel => 'Ibahagi...';
@override
String get tabSemanticsLabelRaw => r'Tab $tabIndex ng $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'oras';
@override
String get timerPickerHourLabelOther => 'na oras';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min.';
@override
String get timerPickerMinuteLabelOther => 'na min.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'seg.';
@override
String get timerPickerSecondLabelOther => 'na seg.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Ngayon';
}
/// The translations for French (`fr`).
class CupertinoLocalizationFr extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for French.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationFr({
super.localeName = 'fr',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Alerte';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Copier';
@override
String get cutButtonLabel => 'Couper';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour heure';
@override
String get datePickerHourSemanticsLabelOther => r'$hour heures';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minute';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minutes';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Recherche visuelle';
@override
String get menuDismissLabel => 'Fermer le menu';
@override
String get modalBarrierDismissLabel => 'Ignorer';
@override
String get noSpellCheckReplacementsLabel => 'Aucun remplacement trouvé';
@override
String get pasteButtonLabel => 'Coller';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Rechercher';
@override
String get searchWebButtonLabel => 'Rechercher sur le Web';
@override
String get selectAllButtonLabel => 'Tout sélectionner';
@override
String get shareButtonLabel => 'Partager…';
@override
String get tabSemanticsLabelRaw => r'Onglet $tabIndex sur $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'heure';
@override
String get timerPickerHourLabelOther => 'heures';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'minute';
@override
String get timerPickerMinuteLabelOther => 'minutes';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 's';
@override
String get timerPickerSecondLabelOther => 's';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => "aujourd'hui";
}
/// The translations for French, as used in Canada (`fr_CA`).
class CupertinoLocalizationFrCa extends CupertinoLocalizationFr {
/// Create an instance of the translation bundle for French, as used in Canada.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationFrCa({
super.localeName = 'fr_CA',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get lookUpButtonLabel => 'Regarder en haut';
@override
String get menuDismissLabel => 'Ignorer le menu';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour heure';
@override
String get datePickerHourSemanticsLabelOther => r'$hour heures';
@override
String get anteMeridiemAbbreviation => 'am';
@override
String get postMeridiemAbbreviation => 'pm';
@override
String get todayLabel => "Aujourd'hui";
@override
String? get timerPickerMinuteLabelOne => 'min';
@override
String get timerPickerMinuteLabelOther => 'min';
}
/// The translations for Galician (`gl`).
class CupertinoLocalizationGl extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Galician.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationGl({
super.localeName = 'gl',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Alerta';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Copiar';
@override
String get cutButtonLabel => 'Cortar';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour en punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour en punto';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minuto';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minutos';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Mirar cara arriba';
@override
String get menuDismissLabel => 'Pechar menú';
@override
String get modalBarrierDismissLabel => 'Ignorar';
@override
String get noSpellCheckReplacementsLabel => 'Non se encontrou ningunha substitución';
@override
String get pasteButtonLabel => 'Pegar';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get searchTextFieldPlaceholderLabel => 'Fai unha busca';
@override
String get searchWebButtonLabel => 'Buscar na Web';
@override
String get selectAllButtonLabel => 'Seleccionar todo';
@override
String get shareButtonLabel => 'Compartir…';
@override
String get tabSemanticsLabelRaw => r'Pestana $tabIndex de $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'hora';
@override
String get timerPickerHourLabelOther => 'horas';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min';
@override
String get timerPickerMinuteLabelOther => 'min';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 's';
@override
String get timerPickerSecondLabelOther => 's';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Hoxe';
}
/// The translations for Swiss German Alemannic Alsatian (`gsw`).
class CupertinoLocalizationGsw extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Swiss German Alemannic Alsatian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationGsw({
super.localeName = 'gsw',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Benachrichtigung';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopieren';
@override
String get cutButtonLabel => 'Ausschneiden';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour Uhr';
@override
String get datePickerHourSemanticsLabelOther => r'$hour Uhr';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 Minute';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute Minuten';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Nachschlagen';
@override
String get menuDismissLabel => 'Menü schließen';
@override
String get modalBarrierDismissLabel => 'Schließen';
@override
String get noSpellCheckReplacementsLabel => 'Keine Ersetzungen gefunden';
@override
String get pasteButtonLabel => 'Einsetzen';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Suche';
@override
String get searchWebButtonLabel => 'Im Web suchen';
@override
String get selectAllButtonLabel => 'Alle auswählen';
@override
String get shareButtonLabel => 'Teilen…';
@override
String get tabSemanticsLabelRaw => r'Tab $tabIndex von $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'Stunde';
@override
String get timerPickerHourLabelOther => 'Stunden';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'Min.';
@override
String get timerPickerMinuteLabelOther => 'Min.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 's';
@override
String get timerPickerSecondLabelOther => 's';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Heute';
}
/// The translations for Gujarati (`gu`).
class CupertinoLocalizationGu extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Gujarati.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationGu({
super.localeName = 'gu',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'અલર્ટ';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'કૉપિ કરો';
@override
String get cutButtonLabel => 'કાપો';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour વાગ્યો છે';
@override
String get datePickerHourSemanticsLabelOther => r'$hour વાગ્યા છે';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 મિનિટ';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute મિનિટ';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'શોધો';
@override
String get menuDismissLabel => 'મેનૂ છોડી દો';
@override
String get modalBarrierDismissLabel => 'છોડી દો';
@override
String get noSpellCheckReplacementsLabel => 'બદલવા માટે કોઈ શબ્દ મળ્યો નથી';
@override
String get pasteButtonLabel => 'પેસ્ટ કરો';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'શોધો';
@override
String get searchWebButtonLabel => 'વેબ પર શોધો';
@override
String get selectAllButtonLabel => 'બધા પસંદ કરો';
@override
String get shareButtonLabel => 'શેર કરો…';
@override
String get tabSemanticsLabelRaw => r'$tabCountમાંથી $tabIndex ટૅબ';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'કલાક';
@override
String get timerPickerHourLabelOther => 'કલાક';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'મિનિટ';
@override
String get timerPickerMinuteLabelOther => 'મિનિટ';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'સેકન્ડ';
@override
String get timerPickerSecondLabelOther => 'સેકન્ડ';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'આજે';
}
/// The translations for Hebrew (`he`).
class CupertinoLocalizationHe extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Hebrew.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationHe({
super.localeName = 'he',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'התראה';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'העתקה';
@override
String get cutButtonLabel => 'גזירה';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => r'$hour בדיוק';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour בדיוק';
@override
String get datePickerHourSemanticsLabelOther => r'$hour בדיוק';
@override
String? get datePickerHourSemanticsLabelTwo => r'$hour בדיוק';
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => r'$minute דקות';
@override
String? get datePickerMinuteSemanticsLabelOne => 'דקה אחת';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute דקות';
@override
String? get datePickerMinuteSemanticsLabelTwo => r'$minute דקות';
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'חיפוש';
@override
String get menuDismissLabel => 'סגירת התפריט';
@override
String get modalBarrierDismissLabel => 'סגירה';
@override
String get noSpellCheckReplacementsLabel => 'לא נמצאו חלופות';
@override
String get pasteButtonLabel => 'הדבקה';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'חיפוש';
@override
String get searchWebButtonLabel => 'חיפוש באינטרנט';
@override
String get selectAllButtonLabel => 'בחירת הכול';
@override
String get shareButtonLabel => 'שיתוף…';
@override
String get tabSemanticsLabelRaw => r'כרטיסייה $tabIndex מתוך $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => 'שעות';
@override
String? get timerPickerHourLabelOne => 'שעה';
@override
String get timerPickerHourLabelOther => 'שעות';
@override
String? get timerPickerHourLabelTwo => 'שעות';
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => 'דק’';
@override
String? get timerPickerMinuteLabelOne => 'דק’';
@override
String get timerPickerMinuteLabelOther => 'דק’';
@override
String? get timerPickerMinuteLabelTwo => 'דק’';
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => 'שנ’';
@override
String? get timerPickerSecondLabelOne => 'שנ’';
@override
String get timerPickerSecondLabelOther => 'שנ’';
@override
String? get timerPickerSecondLabelTwo => 'שנ’';
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'היום';
}
/// The translations for Hindi (`hi`).
class CupertinoLocalizationHi extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Hindi.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationHi({
super.localeName = 'hi',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'अलर्ट';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'कॉपी करें';
@override
String get cutButtonLabel => 'काटें';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour बजे';
@override
String get datePickerHourSemanticsLabelOther => r'$hour बजे';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 मिनट';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute मिनट';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'लुक अप बटन';
@override
String get menuDismissLabel => 'मेन्यू खारिज करें';
@override
String get modalBarrierDismissLabel => 'खारिज करें';
@override
String get noSpellCheckReplacementsLabel => 'सही वर्तनी वाला कोई शब्द नहीं मिला';
@override
String get pasteButtonLabel => 'चिपकाएं';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'खोजें';
@override
String get searchWebButtonLabel => 'वेब पर खोजें';
@override
String get selectAllButtonLabel => 'सभी चुनें';
@override
String get shareButtonLabel => 'शेयर करें…';
@override
String get tabSemanticsLabelRaw => r'$tabCount का टैब $tabIndex';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'घंटा';
@override
String get timerPickerHourLabelOther => 'घंटे';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'मिनट';
@override
String get timerPickerMinuteLabelOther => 'मिनट';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'सेकंड';
@override
String get timerPickerSecondLabelOther => 'सेकंड';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'आज';
}
/// The translations for Croatian (`hr`).
class CupertinoLocalizationHr extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Croatian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationHr({
super.localeName = 'hr',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Upozorenje';
@override
String get anteMeridiemAbbreviation => 'prijepodne';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopiraj';
@override
String get cutButtonLabel => 'Izreži';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => r'$hour sata';
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour sat';
@override
String get datePickerHourSemanticsLabelOther => r'$hour sati';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => r'$minute minute';
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => 'Jedna minuta';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minuta';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Pogled prema gore';
@override
String get menuDismissLabel => 'Odbacivanje izbornika';
@override
String get modalBarrierDismissLabel => 'Odbaci';
@override
String get noSpellCheckReplacementsLabel => 'Nema pronađenih zamjena';
@override
String get pasteButtonLabel => 'Zalijepi';
@override
String get postMeridiemAbbreviation => 'popodne';
@override
String get searchTextFieldPlaceholderLabel => 'Pretraživanje';
@override
String get searchWebButtonLabel => 'Pretraži web';
@override
String get selectAllButtonLabel => 'Odaberi sve';
@override
String get shareButtonLabel => 'Dijeli...';
@override
String get tabSemanticsLabelRaw => r'Kartica $tabIndex od $tabCount';
@override
String? get timerPickerHourLabelFew => 'sata';
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'sat';
@override
String get timerPickerHourLabelOther => 'sati';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => 'min';
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min';
@override
String get timerPickerMinuteLabelOther => 'min';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => 's';
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 's';
@override
String get timerPickerSecondLabelOther => 's';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Danas';
}
/// The translations for Hungarian (`hu`).
class CupertinoLocalizationHu extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Hungarian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationHu({
super.localeName = 'hu',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Értesítés';
@override
String get anteMeridiemAbbreviation => 'de.';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Másolás';
@override
String get cutButtonLabel => 'Kivágás';
@override
String get datePickerDateOrderString => 'ymd';
@override
String get datePickerDateTimeOrderString => 'date_dayPeriod_time';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour óra';
@override
String get datePickerHourSemanticsLabelOther => r'$hour óra';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 perc';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute perc';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Felfelé nézés';
@override
String get menuDismissLabel => 'Menü bezárása';
@override
String get modalBarrierDismissLabel => 'Elvetés';
@override
String get noSpellCheckReplacementsLabel => 'Nem található javítás';
@override
String get pasteButtonLabel => 'Beillesztés';
@override
String get postMeridiemAbbreviation => 'du.';
@override
String get searchTextFieldPlaceholderLabel => 'Keresés';
@override
String get searchWebButtonLabel => 'Keresés az interneten';
@override
String get selectAllButtonLabel => 'Összes kijelölése';
@override
String get shareButtonLabel => 'Megosztás…';
@override
String get tabSemanticsLabelRaw => r'$tabCount/$tabIndex. lap';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'óra';
@override
String get timerPickerHourLabelOther => 'óra';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'perc';
@override
String get timerPickerMinuteLabelOther => 'perc';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'mp';
@override
String get timerPickerSecondLabelOther => 'mp';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Ma';
}
/// The translations for Armenian (`hy`).
class CupertinoLocalizationHy extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Armenian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationHy({
super.localeName = 'hy',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Ծանուցում';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Պատճենել';
@override
String get cutButtonLabel => 'Կտրել';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour:00';
@override
String get datePickerHourSemanticsLabelOther => r'$hour:00';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 րոպե';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute րոպե';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Փնտրել';
@override
String get menuDismissLabel => 'Փակել ընտրացանկը';
@override
String get modalBarrierDismissLabel => 'Փակել';
@override
String get noSpellCheckReplacementsLabel => 'Փոխարինումներ չեն գտնվել';
@override
String get pasteButtonLabel => 'Տեղադրել';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Որոնում';
@override
String get searchWebButtonLabel => 'Որոնել համացանցում';
@override
String get selectAllButtonLabel => 'Նշել բոլորը';
@override
String get shareButtonLabel => 'Կիսվել...';
@override
String get tabSemanticsLabelRaw => r'Ներդիր $tabIndex՝ $tabCount-ից';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'ժամ';
@override
String get timerPickerHourLabelOther => 'ժամ';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'րոպե';
@override
String get timerPickerMinuteLabelOther => 'րոպե';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'վրկ';
@override
String get timerPickerSecondLabelOther => 'վրկ';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Այսօր';
}
/// The translations for Indonesian (`id`).
class CupertinoLocalizationId extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Indonesian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationId({
super.localeName = 'id',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Notifikasi';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Salin';
@override
String get cutButtonLabel => 'Potong';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour tepat';
@override
String get datePickerHourSemanticsLabelOther => r'$hour tepat';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 menit';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute menit';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Cari';
@override
String get menuDismissLabel => 'Tutup menu';
@override
String get modalBarrierDismissLabel => 'Tutup';
@override
String get noSpellCheckReplacementsLabel => 'Penggantian Tidak Ditemukan';
@override
String get pasteButtonLabel => 'Tempel';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Telusuri';
@override
String get searchWebButtonLabel => 'Telusuri di Web';
@override
String get selectAllButtonLabel => 'Pilih Semua';
@override
String get shareButtonLabel => 'Bagikan...';
@override
String get tabSemanticsLabelRaw => r'Tab $tabIndex dari $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'jam';
@override
String get timerPickerHourLabelOther => 'jam';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'mnt.';
@override
String get timerPickerMinuteLabelOther => 'mnt.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'dtk.';
@override
String get timerPickerSecondLabelOther => 'dtk.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Hari ini';
}
/// The translations for Icelandic (`is`).
class CupertinoLocalizationIs extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Icelandic.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationIs({
super.localeName = 'is',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Tilkynning';
@override
String get anteMeridiemAbbreviation => 'f.h.';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Afrita';
@override
String get cutButtonLabel => 'Klippa';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'klukkan $hour';
@override
String get datePickerHourSemanticsLabelOther => r'klukkan $hour';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 mínúta';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute mínútur';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Look Up';
@override
String get menuDismissLabel => 'Loka valmynd';
@override
String get modalBarrierDismissLabel => 'Hunsa';
@override
String get noSpellCheckReplacementsLabel => 'Engir staðgenglar fundust';
@override
String get pasteButtonLabel => 'Líma';
@override
String get postMeridiemAbbreviation => 'e.h.';
@override
String get searchTextFieldPlaceholderLabel => 'Leit';
@override
String get searchWebButtonLabel => 'Leita á vefnum';
@override
String get selectAllButtonLabel => 'Velja allt';
@override
String get shareButtonLabel => 'Deila...';
@override
String get tabSemanticsLabelRaw => r'Flipi $tabIndex af $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'klukkustund';
@override
String get timerPickerHourLabelOther => 'klukkustundir';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'mín.';
@override
String get timerPickerMinuteLabelOther => 'mín.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'sek.';
@override
String get timerPickerSecondLabelOther => 'sek.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Í dag';
}
/// The translations for Italian (`it`).
class CupertinoLocalizationIt extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Italian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationIt({
super.localeName = 'it',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Avviso';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Copia';
@override
String get cutButtonLabel => 'Taglia';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour in punto';
@override
String get datePickerHourSemanticsLabelOther => r'$hour in punto';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minuto';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minuti';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Cerca';
@override
String get menuDismissLabel => 'Ignora menu';
@override
String get modalBarrierDismissLabel => 'Ignora';
@override
String get noSpellCheckReplacementsLabel => 'Nessuna sostituzione trovata';
@override
String get pasteButtonLabel => 'Incolla';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Cerca';
@override
String get searchWebButtonLabel => 'Cerca sul web';
@override
String get selectAllButtonLabel => 'Seleziona tutto';
@override
String get shareButtonLabel => 'Condividi…';
@override
String get tabSemanticsLabelRaw => r'Scheda $tabIndex di $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'ora';
@override
String get timerPickerHourLabelOther => 'ore';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min.';
@override
String get timerPickerMinuteLabelOther => 'min.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'sec.';
@override
String get timerPickerSecondLabelOther => 'sec.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Oggi';
}
/// The translations for Japanese (`ja`).
class CupertinoLocalizationJa extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Japanese.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationJa({
super.localeName = 'ja',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => '通知';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'コピー';
@override
String get cutButtonLabel => '切り取り';
@override
String get datePickerDateOrderString => 'ymd';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour時';
@override
String get datePickerHourSemanticsLabelOther => r'$hour時';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1分';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute分';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => '調べる';
@override
String get menuDismissLabel => 'メニューを閉じる';
@override
String get modalBarrierDismissLabel => '閉じる';
@override
String get noSpellCheckReplacementsLabel => '置き換えるものがありません';
@override
String get pasteButtonLabel => '貼り付け';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => '検索';
@override
String get searchWebButtonLabel => 'ウェブを検索';
@override
String get selectAllButtonLabel => 'すべてを選択';
@override
String get shareButtonLabel => '共有...';
@override
String get tabSemanticsLabelRaw => r'タブ: $tabIndex/$tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => '時間';
@override
String get timerPickerHourLabelOther => '時間';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => '分';
@override
String get timerPickerMinuteLabelOther => '分';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => '秒';
@override
String get timerPickerSecondLabelOther => '秒';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => '今日';
}
/// The translations for Georgian (`ka`).
class CupertinoLocalizationKa extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Georgian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationKa({
super.localeName = 'ka',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'გაფრთხილება';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'კოპირება';
@override
String get cutButtonLabel => 'ამოჭრა';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_dayPeriod_time';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour საათი';
@override
String get datePickerHourSemanticsLabelOther => r'$hour საათი';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 წუთი';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute წუთი';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'აიხედეთ ზემოთ';
@override
String get menuDismissLabel => 'მენიუს უარყოფა';
@override
String get modalBarrierDismissLabel => 'დახურვა';
@override
String get noSpellCheckReplacementsLabel => 'ჩანაცვლება არ მოიძებნა';
@override
String get pasteButtonLabel => 'ჩასმა';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'ძიება';
@override
String get searchWebButtonLabel => 'ვებში ძიება';
@override
String get selectAllButtonLabel => 'ყველას არჩევა';
@override
String get shareButtonLabel => 'გაზიარება...';
@override
String get tabSemanticsLabelRaw => r'ჩანართი $tabIndex / $tabCount-დან';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'საათი';
@override
String get timerPickerHourLabelOther => 'საათი';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'წთ';
@override
String get timerPickerMinuteLabelOther => 'წთ';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'წმ';
@override
String get timerPickerSecondLabelOther => 'წმ';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'დღეს';
}
/// The translations for Kazakh (`kk`).
class CupertinoLocalizationKk extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Kazakh.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationKk({
super.localeName = 'kk',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Дабыл';
@override
String get anteMeridiemAbbreviation => 'түстен кейін';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Көшіру';
@override
String get cutButtonLabel => 'Қию';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'Сағат: $hour';
@override
String get datePickerHourSemanticsLabelOther => r'Сағат: $hour';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 минут';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute минут';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Іздеу';
@override
String get menuDismissLabel => 'Мәзірді жабу';
@override
String get modalBarrierDismissLabel => 'Жабу';
@override
String get noSpellCheckReplacementsLabel => 'Ауыстыратын ешнәрсе табылмады.';
@override
String get pasteButtonLabel => 'Қою';
@override
String get postMeridiemAbbreviation => 'түстен кейін';
@override
String get searchTextFieldPlaceholderLabel => 'Іздеу';
@override
String get searchWebButtonLabel => 'Интернеттен іздеу';
@override
String get selectAllButtonLabel => 'Барлығын таңдау';
@override
String get shareButtonLabel => 'Бөлісу…';
@override
String get tabSemanticsLabelRaw => r'Қойынды: $tabIndex/$tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'сағат';
@override
String get timerPickerHourLabelOther => 'сағат';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'мин';
@override
String get timerPickerMinuteLabelOther => 'мин';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'сек';
@override
String get timerPickerSecondLabelOther => 'сек';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Бүгін';
}
/// The translations for Khmer Central Khmer (`km`).
class CupertinoLocalizationKm extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Khmer Central Khmer.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationKm({
super.localeName = 'km',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'ជូនដំណឹង';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'ចម្លង';
@override
String get cutButtonLabel => 'កាត់';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'ម៉ោង $hour';
@override
String get datePickerHourSemanticsLabelOther => r'ម៉ោង $hour';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 នាទី';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute នាទី';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'រកមើល';
@override
String get menuDismissLabel => 'ច្រានចោលម៉ឺនុយ';
@override
String get modalBarrierDismissLabel => 'ច្រានចោល';
@override
String get noSpellCheckReplacementsLabel => 'រកមិនឃើញការជំនួសទេ';
@override
String get pasteButtonLabel => 'ដាក់ចូល';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'ស្វែងរក';
@override
String get searchWebButtonLabel => 'ស្វែងរកលើបណ្ដាញ';
@override
String get selectAllButtonLabel => 'ជ្រើសរើសទាំងអស់';
@override
String get shareButtonLabel => 'ចែករំលែក...';
@override
String get tabSemanticsLabelRaw => r'ផ្ទាំងទី $tabIndex នៃ $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'ម៉ោង';
@override
String get timerPickerHourLabelOther => 'ម៉ោង';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'នាទី';
@override
String get timerPickerMinuteLabelOther => 'នាទី';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'វិនាទី';
@override
String get timerPickerSecondLabelOther => 'វិនាទី';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'ថ្ងៃនេះ';
}
/// The translations for Kannada (`kn`).
class CupertinoLocalizationKn extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Kannada.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationKn({
super.localeName = 'kn',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => '\u{c8e}\u{c9a}\u{ccd}\u{c9a}\u{cb0}\u{cbf}\u{c95}\u{cc6}';
@override
String get anteMeridiemAbbreviation => '\u{cac}\u{cc6}\u{cb3}\u{cbf}\u{c97}\u{ccd}\u{c97}\u{cc6}';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => '\u{ca8}\u{c95}\u{cb2}\u{cbf}\u{cb8}\u{cbf}';
@override
String get cutButtonLabel => '\u{c95}\u{ca4}\u{ccd}\u{ca4}\u{cb0}\u{cbf}\u{cb8}\u{cbf}';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => '\u{24}\u{68}\u{6f}\u{75}\u{72}\u{20}\u{c97}\u{c82}\u{c9f}\u{cc6}';
@override
String get datePickerHourSemanticsLabelOther => '\u{24}\u{68}\u{6f}\u{75}\u{72}\u{20}\u{c97}\u{c82}\u{c9f}\u{cc6}';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '\u{31}\u{20}\u{ca8}\u{cbf}\u{cae}\u{cbf}\u{cb7}';
@override
String get datePickerMinuteSemanticsLabelOther => '\u{24}\u{6d}\u{69}\u{6e}\u{75}\u{74}\u{65}\u{20}\u{ca8}\u{cbf}\u{cae}\u{cbf}\u{cb7}\u{c97}\u{cb3}\u{cc1}';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => '\u{cae}\u{cc7}\u{cb2}\u{cc6}\u{20}\u{ca8}\u{ccb}\u{ca1}\u{cbf}';
@override
String get menuDismissLabel => '\u{cae}\u{cc6}\u{ca8}\u{cc1}\u{cb5}\u{ca8}\u{ccd}\u{ca8}\u{cc1}\u{20}\u{cb5}\u{c9c}\u{cbe}\u{c97}\u{cc6}\u{cc2}\u{cb3}\u{cbf}\u{cb8}\u{cbf}';
@override
String get modalBarrierDismissLabel => '\u{cb5}\u{c9c}\u{cbe}\u{c97}\u{cca}\u{cb3}\u{cbf}\u{cb8}\u{cbf}';
@override
String get noSpellCheckReplacementsLabel => '\u{caf}\u{cbe}\u{cb5}\u{cc1}\u{ca6}\u{cc7}\u{20}\u{cac}\u{ca6}\u{cb2}\u{cbe}\u{cb5}\u{ca3}\u{cc6}\u{c97}\u{cb3}\u{cc1}\u{20}\u{c95}\u{c82}\u{ca1}\u{cc1}\u{cac}\u{c82}\u{ca6}\u{cbf}\u{cb2}\u{ccd}\u{cb2}';
@override
String get pasteButtonLabel => '\u{c85}\u{c82}\u{c9f}\u{cbf}\u{cb8}\u{cbf}';
@override
String get postMeridiemAbbreviation => '\u{cb8}\u{c82}\u{c9c}\u{cc6}';
@override
String get searchTextFieldPlaceholderLabel => '\u{cb9}\u{cc1}\u{ca1}\u{cc1}\u{c95}\u{cbf}';
@override
String get searchWebButtonLabel => '\u{cb5}\u{cc6}\u{cac}\u{ccd}\u{200c}\u{ca8}\u{cb2}\u{ccd}\u{cb2}\u{cbf}\u{20}\u{cb9}\u{cc1}\u{ca1}\u{cc1}\u{c95}\u{cbf}';
@override
String get selectAllButtonLabel => '\u{c8e}\u{cb2}\u{ccd}\u{cb2}\u{cb5}\u{ca8}\u{ccd}\u{ca8}\u{cc2}\u{20}\u{c86}\u{caf}\u{ccd}\u{c95}\u{cc6}\u{cae}\u{cbe}\u{ca1}\u{cbf}';
@override
String get shareButtonLabel => '\u{cb9}\u{c82}\u{c9a}\u{cbf}\u{c95}\u{cca}\u{cb3}\u{ccd}\u{cb3}\u{cbf}\u{2e}\u{2e}\u{2e}';
@override
String get tabSemanticsLabelRaw => '\u{24}\u{74}\u{61}\u{62}\u{43}\u{6f}\u{75}\u{6e}\u{74}\u{20}\u{cb0}\u{cb2}\u{ccd}\u{cb2}\u{cbf}\u{ca8}\u{20}\u{24}\u{74}\u{61}\u{62}\u{49}\u{6e}\u{64}\u{65}\u{78}\u{20}\u{c9f}\u{ccd}\u{caf}\u{cbe}\u{cac}\u{ccd}';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => '\u{c97}\u{c82}\u{c9f}\u{cc6}';
@override
String get timerPickerHourLabelOther => '\u{c97}\u{c82}\u{c9f}\u{cc6}\u{c97}\u{cb3}\u{cc1}';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => '\u{ca8}\u{cbf}\u{cae}\u{cbf}\u{2e}';
@override
String get timerPickerMinuteLabelOther => '\u{ca8}\u{cbf}\u{cae}\u{cbf}\u{2e}';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => '\u{cb8}\u{cc6}\u{2e}';
@override
String get timerPickerSecondLabelOther => '\u{cb8}\u{cc6}\u{2e}';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => '\u{c87}\u{c82}\u{ca6}\u{cc1}';
}
/// The translations for Korean (`ko`).
class CupertinoLocalizationKo extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Korean.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationKo({
super.localeName = 'ko',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => '알림';
@override
String get anteMeridiemAbbreviation => '오전';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => '복사';
@override
String get cutButtonLabel => '잘라냄';
@override
String get datePickerDateOrderString => 'ymd';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour시 정각';
@override
String get datePickerHourSemanticsLabelOther => r'$hour시 정각';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1분';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute분';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => '찾기';
@override
String get menuDismissLabel => '메뉴 닫기';
@override
String get modalBarrierDismissLabel => '닫기';
@override
String get noSpellCheckReplacementsLabel => '수정사항 없음';
@override
String get pasteButtonLabel => '붙여넣기';
@override
String get postMeridiemAbbreviation => '오후';
@override
String get searchTextFieldPlaceholderLabel => '검색';
@override
String get searchWebButtonLabel => '웹 검색';
@override
String get selectAllButtonLabel => '전체 선택';
@override
String get shareButtonLabel => '공유...';
@override
String get tabSemanticsLabelRaw => r'탭 $tabCount개 중 $tabIndex번째';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => '시간';
@override
String get timerPickerHourLabelOther => '시간';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => '분';
@override
String get timerPickerMinuteLabelOther => '분';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => '초';
@override
String get timerPickerSecondLabelOther => '초';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => '오늘';
}
/// The translations for Kirghiz Kyrgyz (`ky`).
class CupertinoLocalizationKy extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Kirghiz Kyrgyz.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationKy({
super.localeName = 'ky',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Эскертүү';
@override
String get anteMeridiemAbbreviation => 'түшкө чейин';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Көчүрүү';
@override
String get cutButtonLabel => 'Кесүү';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'Саат $hour';
@override
String get datePickerHourSemanticsLabelOther => r'Саат $hour';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 мүнөт';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute мүнөт';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Издөө';
@override
String get menuDismissLabel => 'Менюну жабуу';
@override
String get modalBarrierDismissLabel => 'Жабуу';
@override
String get noSpellCheckReplacementsLabel => 'Алмаштыруу үчүн сөз табылган жок';
@override
String get pasteButtonLabel => 'Чаптоо';
@override
String get postMeridiemAbbreviation => 'түштөн кийин';
@override
String get searchTextFieldPlaceholderLabel => 'Издөө';
@override
String get searchWebButtonLabel => 'Интернеттен издөө';
@override
String get selectAllButtonLabel => 'Баарын тандоо';
@override
String get shareButtonLabel => 'Бөлүшүү…';
@override
String get tabSemanticsLabelRaw => r'$tabCount ичинен $tabIndex-өтмөк';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'саат';
@override
String get timerPickerHourLabelOther => 'саат';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'мүн.';
@override
String get timerPickerMinuteLabelOther => 'мүн.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'сек.';
@override
String get timerPickerSecondLabelOther => 'сек.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Бүгүн';
}
/// The translations for Lao (`lo`).
class CupertinoLocalizationLo extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Lao.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationLo({
super.localeName = 'lo',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'ການເຕືອນ';
@override
String get anteMeridiemAbbreviation => 'ກ່ອນທ່ຽງ';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'ສຳເນົາ';
@override
String get cutButtonLabel => 'ຕັດ';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour ໂມງກົງ';
@override
String get datePickerHourSemanticsLabelOther => r'$hour ໂມງກົງ';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 ນາທີ';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute ນາທີ';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'ຊອກຫາຂໍ້ມູນ';
@override
String get menuDismissLabel => 'ປິດເມນູ';
@override
String get modalBarrierDismissLabel => 'ປິດໄວ້';
@override
String get noSpellCheckReplacementsLabel => 'ບໍ່ພົບການແທນທີ່';
@override
String get pasteButtonLabel => 'ວາງ';
@override
String get postMeridiemAbbreviation => 'ຫຼັງທ່ຽງ';
@override
String get searchTextFieldPlaceholderLabel => 'ຊອກຫາ';
@override
String get searchWebButtonLabel => 'ຊອກຫາຢູ່ອິນເຕີເນັດ';
@override
String get selectAllButtonLabel => 'ເລືອກທັງໝົດ';
@override
String get shareButtonLabel => 'ແບ່ງປັນ...';
@override
String get tabSemanticsLabelRaw => r'ແຖບທີ $tabIndex ຈາກທັງໝົດ $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'ຊົ່ວໂມງ';
@override
String get timerPickerHourLabelOther => 'ຊົ່ວໂມງ';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'ນທ.';
@override
String get timerPickerMinuteLabelOther => 'ນທ.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'ວິ.';
@override
String get timerPickerSecondLabelOther => 'ວິ.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'ມື້ນີ້';
}
/// The translations for Lithuanian (`lt`).
class CupertinoLocalizationLt extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Lithuanian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationLt({
super.localeName = 'lt',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Įspėjimas';
@override
String get anteMeridiemAbbreviation => 'priešpiet';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopijuoti';
@override
String get cutButtonLabel => 'Iškirpti';
@override
String get datePickerDateOrderString => 'ymd';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => r'$hour val.';
@override
String? get datePickerHourSemanticsLabelMany => r'$hour val.';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour val.';
@override
String get datePickerHourSemanticsLabelOther => r'$hour val.';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => r'$minute min.';
@override
String? get datePickerMinuteSemanticsLabelMany => r'$minute min.';
@override
String? get datePickerMinuteSemanticsLabelOne => '1 min.';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute min.';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Ieškoti';
@override
String get menuDismissLabel => 'Atsisakyti meniu';
@override
String get modalBarrierDismissLabel => 'Atsisakyti';
@override
String get noSpellCheckReplacementsLabel => 'Nerasta jokių pakeitimų';
@override
String get pasteButtonLabel => 'Įklijuoti';
@override
String get postMeridiemAbbreviation => 'popiet';
@override
String get searchTextFieldPlaceholderLabel => 'Paieška';
@override
String get searchWebButtonLabel => 'Ieškoti žiniatinklyje';
@override
String get selectAllButtonLabel => 'Pasirinkti viską';
@override
String get shareButtonLabel => 'Bendrinti...';
@override
String get tabSemanticsLabelRaw => r'$tabIndex skirtukas iš $tabCount';
@override
String? get timerPickerHourLabelFew => 'val.';
@override
String? get timerPickerHourLabelMany => 'val.';
@override
String? get timerPickerHourLabelOne => 'val.';
@override
String get timerPickerHourLabelOther => 'val.';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => 'min.';
@override
String? get timerPickerMinuteLabelMany => 'min.';
@override
String? get timerPickerMinuteLabelOne => 'min.';
@override
String get timerPickerMinuteLabelOther => 'min.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => 'sek.';
@override
String? get timerPickerSecondLabelMany => 'sek.';
@override
String? get timerPickerSecondLabelOne => 'sek.';
@override
String get timerPickerSecondLabelOther => 'sek.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Šiandien';
}
/// The translations for Latvian (`lv`).
class CupertinoLocalizationLv extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Latvian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationLv({
super.localeName = 'lv',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Brīdinājums';
@override
String get anteMeridiemAbbreviation => 'priekšpusdienā';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopēt';
@override
String get cutButtonLabel => 'Izgriezt';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'plkst. $hour';
@override
String get datePickerHourSemanticsLabelOther => r'plkst. $hour';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => r'plkst. $hour';
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minūte';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minūtes';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => r'$minute minūtes';
@override
String get lookUpButtonLabel => 'Meklēt';
@override
String get menuDismissLabel => 'Nerādīt izvēlni';
@override
String get modalBarrierDismissLabel => 'Nerādīt';
@override
String get noSpellCheckReplacementsLabel => 'Netika atrasts neviens vārds aizstāšanai';
@override
String get pasteButtonLabel => 'Ielīmēt';
@override
String get postMeridiemAbbreviation => 'pēcpusdienā';
@override
String get searchTextFieldPlaceholderLabel => 'Meklēšana';
@override
String get searchWebButtonLabel => 'Meklēt tīmeklī';
@override
String get selectAllButtonLabel => 'Atlasīt visu';
@override
String get shareButtonLabel => 'Kopīgot…';
@override
String get tabSemanticsLabelRaw => r'$tabIndex. cilne no $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'h';
@override
String get timerPickerHourLabelOther => 'h';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => 'h';
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min';
@override
String get timerPickerMinuteLabelOther => 'min';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => 'min';
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 's';
@override
String get timerPickerSecondLabelOther => 's';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => 's';
@override
String get todayLabel => 'Šodien';
}
/// The translations for Macedonian (`mk`).
class CupertinoLocalizationMk extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Macedonian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationMk({
super.localeName = 'mk',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Предупредување';
@override
String get anteMeridiemAbbreviation => 'ПРЕТПЛАДНЕ';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Копирај';
@override
String get cutButtonLabel => 'Исечи';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour часот';
@override
String get datePickerHourSemanticsLabelOther => r'$hour часот';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 минута';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute минути';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Погледнете нагоре';
@override
String get menuDismissLabel => 'Отфрлете го менито';
@override
String get modalBarrierDismissLabel => 'Отфрли';
@override
String get noSpellCheckReplacementsLabel => 'Не се најдени заменски зборови';
@override
String get pasteButtonLabel => 'Залепи';
@override
String get postMeridiemAbbreviation => 'ПОПЛАДНЕ';
@override
String get searchTextFieldPlaceholderLabel => 'Пребарувајте';
@override
String get searchWebButtonLabel => 'Пребарајте на интернет';
@override
String get selectAllButtonLabel => 'Избери ги сите';
@override
String get shareButtonLabel => 'Споделете...';
@override
String get tabSemanticsLabelRaw => r'Картичка $tabIndex од $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'час';
@override
String get timerPickerHourLabelOther => 'часа';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'мин.';
@override
String get timerPickerMinuteLabelOther => 'мин.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'сек.';
@override
String get timerPickerSecondLabelOther => 'сек.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Денес';
}
/// The translations for Malayalam (`ml`).
class CupertinoLocalizationMl extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Malayalam.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationMl({
super.localeName = 'ml',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'മുന്നറിയിപ്പ്';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'പകർത്തുക';
@override
String get cutButtonLabel => 'മുറിക്കുക';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour മണി';
@override
String get datePickerHourSemanticsLabelOther => r'$hour മണി';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => 'ഒരു മിനിറ്റ്';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute മിനിറ്റ്';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'മുകളിലേക്ക് നോക്കുക';
@override
String get menuDismissLabel => 'മെനു ഡിസ്മിസ് ചെയ്യുക';
@override
String get modalBarrierDismissLabel => 'നിരസിക്കുക';
@override
String get noSpellCheckReplacementsLabel => 'റീപ്ലേസ്മെന്റുകളൊന്നും കണ്ടെത്തിയില്ല';
@override
String get pasteButtonLabel => 'ഒട്ടിക്കുക';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'തിരയുക';
@override
String get searchWebButtonLabel => 'വെബിൽ തിരയുക';
@override
String get selectAllButtonLabel => 'എല്ലാം തിരഞ്ഞെടുക്കുക';
@override
String get shareButtonLabel => 'പങ്കിടുക...';
@override
String get tabSemanticsLabelRaw => r'$tabCount ടാബിൽ $tabIndex-ാമത്തേത്';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'മണിക്കൂർ';
@override
String get timerPickerHourLabelOther => 'മണിക്കൂർ';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'മിനിറ്റ്';
@override
String get timerPickerMinuteLabelOther => 'മിനിറ്റ്';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'സെക്കൻഡ്';
@override
String get timerPickerSecondLabelOther => 'സെക്കൻഡ്';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'ഇന്ന്';
}
/// The translations for Mongolian (`mn`).
class CupertinoLocalizationMn extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Mongolian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationMn({
super.localeName = 'mn',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Сэрэмжлүүлэг';
@override
String get anteMeridiemAbbreviation => 'ӨГЛӨӨ';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Хуулах';
@override
String get cutButtonLabel => 'Таслах';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour цаг';
@override
String get datePickerHourSemanticsLabelOther => r'$hour цаг';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 минут';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute минут';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Дээшээ харах';
@override
String get menuDismissLabel => 'Цэсийг хаах';
@override
String get modalBarrierDismissLabel => 'Үл хэрэгсэх';
@override
String get noSpellCheckReplacementsLabel => 'Ямар ч орлуулалт олдсонгүй';
@override
String get pasteButtonLabel => 'Буулгах';
@override
String get postMeridiemAbbreviation => 'ОРОЙ';
@override
String get searchTextFieldPlaceholderLabel => 'Хайх';
@override
String get searchWebButtonLabel => 'Вебээс хайх';
@override
String get selectAllButtonLabel => 'Бүгдийг сонгох';
@override
String get shareButtonLabel => 'Хуваалцах...';
@override
String get tabSemanticsLabelRaw => r'$tabCount-н $tabIndex-р таб';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'цаг';
@override
String get timerPickerHourLabelOther => 'цаг';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'минут.';
@override
String get timerPickerMinuteLabelOther => 'минут.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'секунд.';
@override
String get timerPickerSecondLabelOther => 'секунд.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Өнөөдөр';
}
/// The translations for Marathi (`mr`).
class CupertinoLocalizationMr extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Marathi.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationMr({
super.localeName = 'mr',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'सूचना';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'कॉपी करा';
@override
String get cutButtonLabel => 'कट करा';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour वाजता';
@override
String get datePickerHourSemanticsLabelOther => r'$hour वाजता';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => 'एक मिनिट';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute मिनिटे';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'शोध घ्या';
@override
String get menuDismissLabel => 'मेनू डिसमिस करा';
@override
String get modalBarrierDismissLabel => 'डिसमिस करा';
@override
String get noSpellCheckReplacementsLabel => 'कोणतेही बदल आढळले नाहीत';
@override
String get pasteButtonLabel => 'पेस्ट करा';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'शोधा';
@override
String get searchWebButtonLabel => 'वेबवर शोधा';
@override
String get selectAllButtonLabel => 'सर्व निवडा';
@override
String get shareButtonLabel => 'शेअर करा...';
@override
String get tabSemanticsLabelRaw => r'$tabCount पैकी $tabIndex टॅब';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'तास';
@override
String get timerPickerHourLabelOther => 'तास';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'मि.';
@override
String get timerPickerMinuteLabelOther => 'मि.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'से.';
@override
String get timerPickerSecondLabelOther => 'से.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'आज';
}
/// The translations for Malay (`ms`).
class CupertinoLocalizationMs extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Malay.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationMs({
super.localeName = 'ms',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Makluman';
@override
String get anteMeridiemAbbreviation => 'PG';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Salin';
@override
String get cutButtonLabel => 'Potong';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'Pukul $hour';
@override
String get datePickerHourSemanticsLabelOther => r'Pukul $hour';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minit';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minit';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Lihat ke Atas';
@override
String get menuDismissLabel => 'Ketepikan menu';
@override
String get modalBarrierDismissLabel => 'Tolak';
@override
String get noSpellCheckReplacementsLabel => 'Tiada Penggantian Ditemukan';
@override
String get pasteButtonLabel => 'Tampal';
@override
String get postMeridiemAbbreviation => 'P/M';
@override
String get searchTextFieldPlaceholderLabel => 'Cari';
@override
String get searchWebButtonLabel => 'Buat carian pada Web';
@override
String get selectAllButtonLabel => 'Pilih Semua';
@override
String get shareButtonLabel => 'Kongsi...';
@override
String get tabSemanticsLabelRaw => r'Tab $tabIndex daripada $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'jam';
@override
String get timerPickerHourLabelOther => 'jam';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'minit';
@override
String get timerPickerMinuteLabelOther => 'minit';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'saat';
@override
String get timerPickerSecondLabelOther => 'saat';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Hari ini';
}
/// The translations for Burmese (`my`).
class CupertinoLocalizationMy extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Burmese.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationMy({
super.localeName = 'my',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'သတိပေးချက်';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'မိတ္တူကူးရန်';
@override
String get cutButtonLabel => 'ဖြတ်ယူရန်';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour နာရီ';
@override
String get datePickerHourSemanticsLabelOther => r'$hour နာရီ';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '၁ မိနစ်';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute မိနစ်';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'အပေါ်ကြည့်ရန်';
@override
String get menuDismissLabel => 'မီနူးကိုပယ်ပါ';
@override
String get modalBarrierDismissLabel => 'ပယ်ရန်';
@override
String get noSpellCheckReplacementsLabel => 'အစားထိုးမှုများ မတွေ့ပါ';
@override
String get pasteButtonLabel => 'ကူးထည့်ရန်';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'ရှာရန်';
@override
String get searchWebButtonLabel => 'ဝဘ်တွင်ရှာရန်';
@override
String get selectAllButtonLabel => 'အားလုံး ရွေးရန်';
@override
String get shareButtonLabel => 'မျှဝေရန်...';
@override
String get tabSemanticsLabelRaw => r'တဘ် $tabCount ခုအနက် $tabIndex ခု';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'နာရီ';
@override
String get timerPickerHourLabelOther => 'နာရီ';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'မိနစ်';
@override
String get timerPickerMinuteLabelOther => 'မိနစ်';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'စက္ကန့်';
@override
String get timerPickerSecondLabelOther => 'စက္ကန့်';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'ယနေ့';
}
/// The translations for Norwegian Bokmål (`nb`).
class CupertinoLocalizationNb extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Norwegian Bokmål.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationNb({
super.localeName = 'nb',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Varsel';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopiér';
@override
String get cutButtonLabel => 'Klipp ut';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour null-null';
@override
String get datePickerHourSemanticsLabelOther => r'$hour null-null';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minutt';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minutter';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Slå opp';
@override
String get menuDismissLabel => 'Lukk menyen';
@override
String get modalBarrierDismissLabel => 'Avvis';
@override
String get noSpellCheckReplacementsLabel => 'Fant ingen erstatninger';
@override
String get pasteButtonLabel => 'Lim inn';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Søk';
@override
String get searchWebButtonLabel => 'Søk på nettet';
@override
String get selectAllButtonLabel => 'Velg alle';
@override
String get shareButtonLabel => 'Del…';
@override
String get tabSemanticsLabelRaw => r'Fane $tabIndex av $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'time';
@override
String get timerPickerHourLabelOther => 'timer';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min.';
@override
String get timerPickerMinuteLabelOther => 'min.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'sek.';
@override
String get timerPickerSecondLabelOther => 'sek.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'I dag';
}
/// The translations for Nepali (`ne`).
class CupertinoLocalizationNe extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Nepali.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationNe({
super.localeName = 'ne',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'अलर्ट';
@override
String get anteMeridiemAbbreviation => 'पूर्वाह्न';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'प्रतिलिपि गर्नुहोस्';
@override
String get cutButtonLabel => 'काट्नुहोस्';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour बजे';
@override
String get datePickerHourSemanticsLabelOther => r'$hour बजे';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '१ मिनेट';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute मिनेट';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'माथितिर हेर्नुहोस्';
@override
String get menuDismissLabel => 'मेनु खारेज गर्नुहोस्';
@override
String get modalBarrierDismissLabel => 'खारेज गर्नुहोस्';
@override
String get noSpellCheckReplacementsLabel => 'बदल्नु पर्ने कुनै पनि कुरा भेटिएन';
@override
String get pasteButtonLabel => 'टाँस्नुहोस्';
@override
String get postMeridiemAbbreviation => 'अपराह्न';
@override
String get searchTextFieldPlaceholderLabel => 'खोज्नुहोस्';
@override
String get searchWebButtonLabel => 'वेबमा खोज्नुहोस्';
@override
String get selectAllButtonLabel => 'सबै चयन गर्नुहोस्';
@override
String get shareButtonLabel => 'सेयर गर्नुहोस्...';
@override
String get tabSemanticsLabelRaw => r'$tabCount मध्ये $tabIndex ट्याब';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'घन्टा';
@override
String get timerPickerHourLabelOther => 'घन्टा';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'मिनेट';
@override
String get timerPickerMinuteLabelOther => 'मिनेट';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'सेकेन्ड';
@override
String get timerPickerSecondLabelOther => 'सेकेन्ड';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'आज';
}
/// The translations for Dutch Flemish (`nl`).
class CupertinoLocalizationNl extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Dutch Flemish.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationNl({
super.localeName = 'nl',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Melding';
@override
String get anteMeridiemAbbreviation => 'am';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopiëren';
@override
String get cutButtonLabel => 'Knippen';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour uur';
@override
String get datePickerHourSemanticsLabelOther => r'$hour uur';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minuut';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minuten';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Opzoeken';
@override
String get menuDismissLabel => 'Menu sluiten';
@override
String get modalBarrierDismissLabel => 'Sluiten';
@override
String get noSpellCheckReplacementsLabel => 'Geen vervangingen gevonden';
@override
String get pasteButtonLabel => 'Plakken';
@override
String get postMeridiemAbbreviation => 'pm';
@override
String get searchTextFieldPlaceholderLabel => 'Zoeken';
@override
String get searchWebButtonLabel => 'Op internet zoeken';
@override
String get selectAllButtonLabel => 'Alles selecteren';
@override
String get shareButtonLabel => 'Delen...';
@override
String get tabSemanticsLabelRaw => r'Tabblad $tabIndex van $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'uur';
@override
String get timerPickerHourLabelOther => 'uur';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min.';
@override
String get timerPickerMinuteLabelOther => 'min.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'sec.';
@override
String get timerPickerSecondLabelOther => 'sec.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Vandaag';
}
/// The translations for Norwegian (`no`).
class CupertinoLocalizationNo extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Norwegian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationNo({
super.localeName = 'no',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Varsel';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopiér';
@override
String get cutButtonLabel => 'Klipp ut';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour null-null';
@override
String get datePickerHourSemanticsLabelOther => r'$hour null-null';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minutt';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minutter';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Slå opp';
@override
String get menuDismissLabel => 'Lukk menyen';
@override
String get modalBarrierDismissLabel => 'Avvis';
@override
String get noSpellCheckReplacementsLabel => 'Fant ingen erstatninger';
@override
String get pasteButtonLabel => 'Lim inn';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Søk';
@override
String get searchWebButtonLabel => 'Søk på nettet';
@override
String get selectAllButtonLabel => 'Velg alle';
@override
String get shareButtonLabel => 'Del…';
@override
String get tabSemanticsLabelRaw => r'Fane $tabIndex av $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'time';
@override
String get timerPickerHourLabelOther => 'timer';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min.';
@override
String get timerPickerMinuteLabelOther => 'min.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'sek.';
@override
String get timerPickerSecondLabelOther => 'sek.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'I dag';
}
/// The translations for Oriya (`or`).
class CupertinoLocalizationOr extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Oriya.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationOr({
super.localeName = 'or',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'ଆଲର୍ଟ';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'କପି କରନ୍ତୁ';
@override
String get cutButtonLabel => 'କଟ୍ କରନ୍ତୁ';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hourଟା';
@override
String get datePickerHourSemanticsLabelOther => r'$hourଟା';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 ମିନିଟ୍';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute ମିନିଟ୍';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'ଉପରକୁ ଦେଖନ୍ତୁ';
@override
String get menuDismissLabel => 'ମେନୁ ଖାରଜ କରନ୍ତୁ';
@override
String get modalBarrierDismissLabel => 'ଖାରଜ କରନ୍ତୁ';
@override
String get noSpellCheckReplacementsLabel => 'କୌଣସି ରିପ୍ଲେସମେଣ୍ଟ ମିଳିଲା ନାହିଁ';
@override
String get pasteButtonLabel => 'ପେଷ୍ଟ କରନ୍ତୁ';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'ସନ୍ଧାନ କରନ୍ତୁ';
@override
String get searchWebButtonLabel => 'ୱେବ ସର୍ଚ୍ଚ କରନ୍ତୁ';
@override
String get selectAllButtonLabel => 'ସମସ୍ତ ଚୟନ କରନ୍ତୁ';
@override
String get shareButtonLabel => 'ସେୟାର୍ କରନ୍ତୁ...';
@override
String get tabSemanticsLabelRaw => r'$tabCountର $tabIndex ଟାବ୍';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'ଘଣ୍ଟା';
@override
String get timerPickerHourLabelOther => 'ଘଣ୍ଟା';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'ମିନିଟ୍';
@override
String get timerPickerMinuteLabelOther => 'ମିନିଟ୍';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'ସେକେଣ୍ଡ';
@override
String get timerPickerSecondLabelOther => 'ସେକେଣ୍ଡ';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'ଆଜି';
}
/// The translations for Panjabi Punjabi (`pa`).
class CupertinoLocalizationPa extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Panjabi Punjabi.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationPa({
super.localeName = 'pa',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'ਸੁਚੇਤਨਾ';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'ਕਾਪੀ ਕਰੋ';
@override
String get cutButtonLabel => 'ਕੱਟ ਕਰੋ';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour ਵਜੇ';
@override
String get datePickerHourSemanticsLabelOther => r'$hour ਵਜੇ';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 ਮਿੰਟ';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute ਮਿੰਟ';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'ਖੋਜੋ';
@override
String get menuDismissLabel => 'ਮੀਨੂ ਖਾਰਜ ਕਰੋ';
@override
String get modalBarrierDismissLabel => 'ਖਾਰਜ ਕਰੋ';
@override
String get noSpellCheckReplacementsLabel => 'ਕੋਈ ਸੁਝਾਅ ਨਹੀਂ ਮਿਲਿਆ';
@override
String get pasteButtonLabel => 'ਪੇਸਟ ਕਰੋ';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'ਖੋਜੋ';
@override
String get searchWebButtonLabel => "ਵੈੱਬ 'ਤੇ ਖੋਜੋ";
@override
String get selectAllButtonLabel => 'ਸਭ ਚੁਣੋ';
@override
String get shareButtonLabel => 'ਸਾਂਝਾ ਕਰੋ...';
@override
String get tabSemanticsLabelRaw => r'$tabCount ਵਿੱਚੋਂ $tabIndex ਟੈਬ';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'ਘੰਟਾ';
@override
String get timerPickerHourLabelOther => 'ਘੰਟੇ';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'ਮਿੰ.';
@override
String get timerPickerMinuteLabelOther => 'ਮਿੰ.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'ਸਕਿੰ.';
@override
String get timerPickerSecondLabelOther => 'ਸਕਿੰ.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'ਅੱਜ';
}
/// The translations for Polish (`pl`).
class CupertinoLocalizationPl extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Polish.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationPl({
super.localeName = 'pl',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Alert';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopiuj';
@override
String get cutButtonLabel => 'Wytnij';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => r'$hour';
@override
String? get datePickerHourSemanticsLabelMany => r'$hour';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour';
@override
String get datePickerHourSemanticsLabelOther => r'$hour';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => r'$minute minuty';
@override
String? get datePickerMinuteSemanticsLabelMany => r'$minute minut';
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minuta';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minuty';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Sprawdź';
@override
String get menuDismissLabel => 'Zamknij menu';
@override
String get modalBarrierDismissLabel => 'Zamknij';
@override
String get noSpellCheckReplacementsLabel => 'Brak wyników zamieniania';
@override
String get pasteButtonLabel => 'Wklej';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Szukaj';
@override
String get searchWebButtonLabel => 'Szukaj w internecie';
@override
String get selectAllButtonLabel => 'Wybierz wszystkie';
@override
String get shareButtonLabel => 'Udostępnij…';
@override
String get tabSemanticsLabelRaw => r'Karta $tabIndex z $tabCount';
@override
String? get timerPickerHourLabelFew => 'godziny';
@override
String? get timerPickerHourLabelMany => 'godzin';
@override
String? get timerPickerHourLabelOne => 'godzina';
@override
String get timerPickerHourLabelOther => 'godziny';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => 'min';
@override
String? get timerPickerMinuteLabelMany => 'min';
@override
String? get timerPickerMinuteLabelOne => 'min';
@override
String get timerPickerMinuteLabelOther => 'min';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => 's';
@override
String? get timerPickerSecondLabelMany => 's';
@override
String? get timerPickerSecondLabelOne => 's';
@override
String get timerPickerSecondLabelOther => 's';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Dziś';
}
/// The translations for Portuguese (`pt`).
class CupertinoLocalizationPt extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Portuguese.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationPt({
super.localeName = 'pt',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Alerta';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Copiar';
@override
String get cutButtonLabel => 'Cortar';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour hora';
@override
String get datePickerHourSemanticsLabelOther => r'$hour horas';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minuto';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minutos';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Pesquisar';
@override
String get menuDismissLabel => 'Dispensar menu';
@override
String get modalBarrierDismissLabel => 'Dispensar';
@override
String get noSpellCheckReplacementsLabel => 'Nenhuma alternativa encontrada';
@override
String get pasteButtonLabel => 'Colar';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Pesquisar';
@override
String get searchWebButtonLabel => 'Pesquisar na Web';
@override
String get selectAllButtonLabel => 'Selecionar tudo';
@override
String get shareButtonLabel => 'Compartilhar…';
@override
String get tabSemanticsLabelRaw => r'Guia $tabIndex de $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'hora';
@override
String get timerPickerHourLabelOther => 'horas';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min';
@override
String get timerPickerMinuteLabelOther => 'min';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 's';
@override
String get timerPickerSecondLabelOther => 's';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Hoje';
}
/// The translations for Portuguese, as used in Portugal (`pt_PT`).
class CupertinoLocalizationPtPt extends CupertinoLocalizationPt {
/// Create an instance of the translation bundle for Portuguese, as used in Portugal.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationPtPt({
super.localeName = 'pt_PT',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get shareButtonLabel => 'Partilhar…';
@override
String get lookUpButtonLabel => 'Procurar';
@override
String get noSpellCheckReplacementsLabel => 'Não foram encontradas substituições';
@override
String get menuDismissLabel => 'Ignorar menu';
@override
String get searchTextFieldPlaceholderLabel => 'Pesquise';
@override
String get tabSemanticsLabelRaw => r'Separador $tabIndex de $tabCount';
@override
String get datePickerHourSemanticsLabelOther => r'$hour hora';
@override
String? get timerPickerSecondLabelOne => 'seg';
@override
String get timerPickerSecondLabelOther => 'seg';
@override
String get modalBarrierDismissLabel => 'Ignorar';
}
/// The translations for Romanian Moldavian Moldovan (`ro`).
class CupertinoLocalizationRo extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Romanian Moldavian Moldovan.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationRo({
super.localeName = 'ro',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Alertă';
@override
String get anteMeridiemAbbreviation => 'a.m.';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Copiați';
@override
String get cutButtonLabel => 'Decupați';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => r'Ora $hour';
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'Ora $hour';
@override
String get datePickerHourSemanticsLabelOther => r'Ora $hour';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => r'$minute minute';
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minut';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute de minute';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Privire în sus';
@override
String get menuDismissLabel => 'Respingeți meniul';
@override
String get modalBarrierDismissLabel => 'Închideți';
@override
String get noSpellCheckReplacementsLabel => 'Nu s-au găsit înlocuiri';
@override
String get pasteButtonLabel => 'Inserați';
@override
String get postMeridiemAbbreviation => 'p.m.';
@override
String get searchTextFieldPlaceholderLabel => 'Căutați';
@override
String get searchWebButtonLabel => 'Căutați pe web';
@override
String get selectAllButtonLabel => 'Selectează tot';
@override
String get shareButtonLabel => 'Trimiteți…';
@override
String get tabSemanticsLabelRaw => r'Fila $tabIndex din $tabCount';
@override
String? get timerPickerHourLabelFew => 'ore';
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'oră';
@override
String get timerPickerHourLabelOther => 'de ore';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => 'min.';
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min.';
@override
String get timerPickerMinuteLabelOther => 'min.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => 'sec.';
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'sec.';
@override
String get timerPickerSecondLabelOther => 'sec.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Azi';
}
/// The translations for Russian (`ru`).
class CupertinoLocalizationRu extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Russian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationRu({
super.localeName = 'ru',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Оповещение';
@override
String get anteMeridiemAbbreviation => 'АМ';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Копировать';
@override
String get cutButtonLabel => 'Вырезать';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => r'$hour часа';
@override
String? get datePickerHourSemanticsLabelMany => r'$hour часов';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour час';
@override
String get datePickerHourSemanticsLabelOther => r'$hour часа';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => r'$minute минуты';
@override
String? get datePickerMinuteSemanticsLabelMany => r'$minute минут';
@override
String? get datePickerMinuteSemanticsLabelOne => '1 минута';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute минуты';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Найти';
@override
String get menuDismissLabel => 'Закрыть меню';
@override
String get modalBarrierDismissLabel => 'Закрыть';
@override
String get noSpellCheckReplacementsLabel => 'Варианты замены не найдены';
@override
String get pasteButtonLabel => 'Вставить';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Поиск';
@override
String get searchWebButtonLabel => 'Искать в интернете';
@override
String get selectAllButtonLabel => 'Выбрать все';
@override
String get shareButtonLabel => 'Поделиться';
@override
String get tabSemanticsLabelRaw => r'Вкладка $tabIndex из $tabCount';
@override
String? get timerPickerHourLabelFew => 'часа';
@override
String? get timerPickerHourLabelMany => 'часов';
@override
String? get timerPickerHourLabelOne => 'час';
@override
String get timerPickerHourLabelOther => 'часа';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => 'мин.';
@override
String? get timerPickerMinuteLabelMany => 'мин.';
@override
String? get timerPickerMinuteLabelOne => 'мин.';
@override
String get timerPickerMinuteLabelOther => 'мин.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => 'сек.';
@override
String? get timerPickerSecondLabelMany => 'сек.';
@override
String? get timerPickerSecondLabelOne => 'сек.';
@override
String get timerPickerSecondLabelOther => 'сек.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Сегодня';
}
/// The translations for Sinhala Sinhalese (`si`).
class CupertinoLocalizationSi extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Sinhala Sinhalese.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationSi({
super.localeName = 'si',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'ඇඟවීම';
@override
String get anteMeridiemAbbreviation => 'පෙ.ව.';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'පිටපත් කරන්න';
@override
String get cutButtonLabel => 'කපන්න';
@override
String get datePickerDateOrderString => 'ymd';
@override
String get datePickerDateTimeOrderString => 'date_dayPeriod_time';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hourයි';
@override
String get datePickerHourSemanticsLabelOther => r'$hourයි';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => 'මිනිත්තු 1';
@override
String get datePickerMinuteSemanticsLabelOther => r'මිනිත්තු $minute';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'උඩ බලන්න';
@override
String get menuDismissLabel => 'මෙනුව අස් කරන්න';
@override
String get modalBarrierDismissLabel => 'ඉවත ලන්න';
@override
String get noSpellCheckReplacementsLabel => 'ප්රතිස්ථාපන හමු නොවිණි';
@override
String get pasteButtonLabel => 'අලවන්න';
@override
String get postMeridiemAbbreviation => 'ප.ව.';
@override
String get searchTextFieldPlaceholderLabel => 'සෙවීම';
@override
String get searchWebButtonLabel => 'වෙබය සොයන්න';
@override
String get selectAllButtonLabel => 'සියල්ල තෝරන්න';
@override
String get shareButtonLabel => 'බෙදා ගන්න...';
@override
String get tabSemanticsLabelRaw => r'ටැබ $tabCount න් $tabIndex';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'පැය';
@override
String get timerPickerHourLabelOther => 'පැය';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'මිනි.';
@override
String get timerPickerMinuteLabelOther => 'මිනි.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'තත්.';
@override
String get timerPickerSecondLabelOther => 'තත්.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'අද';
}
/// The translations for Slovak (`sk`).
class CupertinoLocalizationSk extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Slovak.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationSk({
super.localeName = 'sk',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Upozornenie';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopírovať';
@override
String get cutButtonLabel => 'Vystrihnúť';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => r'$hour hodiny';
@override
String? get datePickerHourSemanticsLabelMany => r'$hour hodiny';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour hodina';
@override
String get datePickerHourSemanticsLabelOther => r'$hour hodín';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => r'$minute minúty';
@override
String? get datePickerMinuteSemanticsLabelMany => r'$minute minúty';
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minúta';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minút';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Pohľad nahor';
@override
String get menuDismissLabel => 'Zavrieť ponuku';
@override
String get modalBarrierDismissLabel => 'Odmietnuť';
@override
String get noSpellCheckReplacementsLabel => 'Nenašli sa žiadne náhrady';
@override
String get pasteButtonLabel => 'Prilepiť';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Hľadať';
@override
String get searchWebButtonLabel => 'Hľadať na webe';
@override
String get selectAllButtonLabel => 'Označiť všetko';
@override
String get shareButtonLabel => 'Zdieľať…';
@override
String get tabSemanticsLabelRaw => r'Karta $tabIndex z $tabCount';
@override
String? get timerPickerHourLabelFew => 'hodiny';
@override
String? get timerPickerHourLabelMany => 'hodiny';
@override
String? get timerPickerHourLabelOne => 'hodina';
@override
String get timerPickerHourLabelOther => 'hodín';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => 'min';
@override
String? get timerPickerMinuteLabelMany => 'min';
@override
String? get timerPickerMinuteLabelOne => 'min';
@override
String get timerPickerMinuteLabelOther => 'min';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => 's';
@override
String? get timerPickerSecondLabelMany => 's';
@override
String? get timerPickerSecondLabelOne => 's';
@override
String get timerPickerSecondLabelOther => 's';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Dnes';
}
/// The translations for Slovenian (`sl`).
class CupertinoLocalizationSl extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Slovenian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationSl({
super.localeName = 'sl',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Opozorilo';
@override
String get anteMeridiemAbbreviation => 'DOP.';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopiraj';
@override
String get cutButtonLabel => 'Izreži';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => r'$hour';
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour';
@override
String get datePickerHourSemanticsLabelOther => r'$hour';
@override
String? get datePickerHourSemanticsLabelTwo => r'$hour';
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => r'$minute minute';
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minuta';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minut';
@override
String? get datePickerMinuteSemanticsLabelTwo => r'$minute minuti';
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Pogled gor';
@override
String get menuDismissLabel => 'Opusti meni';
@override
String get modalBarrierDismissLabel => 'Opusti';
@override
String get noSpellCheckReplacementsLabel => 'Ni zamenjav';
@override
String get pasteButtonLabel => 'Prilepi';
@override
String get postMeridiemAbbreviation => 'POP.';
@override
String get searchTextFieldPlaceholderLabel => 'Iskanje';
@override
String get searchWebButtonLabel => 'Iskanje v spletu';
@override
String get selectAllButtonLabel => 'Izberi vse';
@override
String get shareButtonLabel => 'Deli …';
@override
String get tabSemanticsLabelRaw => r'Zavihek $tabIndex od $tabCount';
@override
String? get timerPickerHourLabelFew => 'ure';
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'ura';
@override
String get timerPickerHourLabelOther => 'ure';
@override
String? get timerPickerHourLabelTwo => 'ure';
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => 'min';
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min';
@override
String get timerPickerMinuteLabelOther => 'min';
@override
String? get timerPickerMinuteLabelTwo => 'min';
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => 's';
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 's';
@override
String get timerPickerSecondLabelOther => 's';
@override
String? get timerPickerSecondLabelTwo => 's';
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Danes';
}
/// The translations for Albanian (`sq`).
class CupertinoLocalizationSq extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Albanian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationSq({
super.localeName = 'sq',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Sinjalizim';
@override
String get anteMeridiemAbbreviation => 'paradite';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopjo';
@override
String get cutButtonLabel => 'Prit';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour fiks';
@override
String get datePickerHourSemanticsLabelOther => r'$hour fiks';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minutë';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minuta';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Kërko';
@override
String get menuDismissLabel => 'Hiqe menynë';
@override
String get modalBarrierDismissLabel => 'Hiq';
@override
String get noSpellCheckReplacementsLabel => 'Nuk u gjetën zëvendësime';
@override
String get pasteButtonLabel => 'Ngjit';
@override
String get postMeridiemAbbreviation => 'pasdite';
@override
String get searchTextFieldPlaceholderLabel => 'Kërko';
@override
String get searchWebButtonLabel => 'Kërko në ueb';
@override
String get selectAllButtonLabel => 'Zgjidhi të gjitha';
@override
String get shareButtonLabel => 'Ndaj...';
@override
String get tabSemanticsLabelRaw => r'Skeda $tabIndex nga $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'orë';
@override
String get timerPickerHourLabelOther => 'orë';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min.';
@override
String get timerPickerMinuteLabelOther => 'min.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'sek.';
@override
String get timerPickerSecondLabelOther => 'sek.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Sot';
}
/// The translations for Serbian (`sr`).
class CupertinoLocalizationSr extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Serbian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationSr({
super.localeName = 'sr',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Обавештење';
@override
String get anteMeridiemAbbreviation => 'пре подне';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Копирај';
@override
String get cutButtonLabel => 'Исеци';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => r'$hour сата';
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour сат';
@override
String get datePickerHourSemanticsLabelOther => r'$hour сати';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => r'$minute минута';
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 минут';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute минута';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Поглед нагоре';
@override
String get menuDismissLabel => 'Одбаците мени';
@override
String get modalBarrierDismissLabel => 'Одбаци';
@override
String get noSpellCheckReplacementsLabel => 'Нису пронађене замене';
@override
String get pasteButtonLabel => 'Налепи';
@override
String get postMeridiemAbbreviation => 'по подне';
@override
String get searchTextFieldPlaceholderLabel => 'Претражите';
@override
String get searchWebButtonLabel => 'Претражи веб';
@override
String get selectAllButtonLabel => 'Изабери све';
@override
String get shareButtonLabel => 'Дели…';
@override
String get tabSemanticsLabelRaw => r'$tabIndex. картица од $tabCount';
@override
String? get timerPickerHourLabelFew => 'сата';
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'сат';
@override
String get timerPickerHourLabelOther => 'сати';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => 'мин';
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'мин';
@override
String get timerPickerMinuteLabelOther => 'мин';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => 'сек';
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'сек';
@override
String get timerPickerSecondLabelOther => 'сек';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Данас';
}
/// The translations for Serbian, using the Cyrillic script (`sr_Cyrl`).
class CupertinoLocalizationSrCyrl extends CupertinoLocalizationSr {
/// Create an instance of the translation bundle for Serbian, using the Cyrillic script.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationSrCyrl({
super.localeName = 'sr_Cyrl',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
}
/// The translations for Serbian, using the Latin script (`sr_Latn`).
class CupertinoLocalizationSrLatn extends CupertinoLocalizationSr {
/// Create an instance of the translation bundle for Serbian, using the Latin script.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationSrLatn({
super.localeName = 'sr_Latn',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Obaveštenje';
@override
String get anteMeridiemAbbreviation => 'pre podne';
@override
String get copyButtonLabel => 'Kopiraj';
@override
String get cutButtonLabel => 'Iseci';
@override
String? get datePickerHourSemanticsLabelFew => r'$hour sata';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour sat';
@override
String get datePickerHourSemanticsLabelOther => r'$hour sati';
@override
String? get datePickerMinuteSemanticsLabelFew => r'$minute minuta';
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minut';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minuta';
@override
String get lookUpButtonLabel => 'Pogled nagore';
@override
String get menuDismissLabel => 'Odbacite meni';
@override
String get modalBarrierDismissLabel => 'Odbaci';
@override
String get noSpellCheckReplacementsLabel => 'Nisu pronađene zamene';
@override
String get pasteButtonLabel => 'Nalepi';
@override
String get postMeridiemAbbreviation => 'po podne';
@override
String get searchTextFieldPlaceholderLabel => 'Pretražite';
@override
String get searchWebButtonLabel => 'Pretraži veb';
@override
String get selectAllButtonLabel => 'Izaberi sve';
@override
String get shareButtonLabel => 'Deli…';
@override
String get tabSemanticsLabelRaw => r'$tabIndex. kartica od $tabCount';
@override
String? get timerPickerHourLabelFew => 'sata';
@override
String? get timerPickerHourLabelOne => 'sat';
@override
String get timerPickerHourLabelOther => 'sati';
@override
String? get timerPickerMinuteLabelFew => 'min';
@override
String? get timerPickerMinuteLabelOne => 'min';
@override
String get timerPickerMinuteLabelOther => 'min';
@override
String? get timerPickerSecondLabelFew => 'sek';
@override
String? get timerPickerSecondLabelOne => 'sek';
@override
String get timerPickerSecondLabelOther => 'sek';
@override
String get todayLabel => 'Danas';
}
/// The translations for Swedish (`sv`).
class CupertinoLocalizationSv extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Swedish.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationSv({
super.localeName = 'sv',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Varning';
@override
String get anteMeridiemAbbreviation => 'FM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopiera';
@override
String get cutButtonLabel => 'Klipp ut';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'Klockan $hour';
@override
String get datePickerHourSemanticsLabelOther => r'Klockan $hour';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minut';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute minuter';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Titta upp';
@override
String get menuDismissLabel => 'Stäng menyn';
@override
String get modalBarrierDismissLabel => 'Stäng';
@override
String get noSpellCheckReplacementsLabel => 'Inga ersättningar hittades';
@override
String get pasteButtonLabel => 'Klistra in';
@override
String get postMeridiemAbbreviation => 'EM';
@override
String get searchTextFieldPlaceholderLabel => 'Sök';
@override
String get searchWebButtonLabel => 'Sök på webben';
@override
String get selectAllButtonLabel => 'Markera allt';
@override
String get shareButtonLabel => 'Dela …';
@override
String get tabSemanticsLabelRaw => r'Flik $tabIndex av $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'timme';
@override
String get timerPickerHourLabelOther => 'timmar';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min';
@override
String get timerPickerMinuteLabelOther => 'min';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'sek';
@override
String get timerPickerSecondLabelOther => 'sek';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'I dag';
}
/// The translations for Swahili (`sw`).
class CupertinoLocalizationSw extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Swahili.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationSw({
super.localeName = 'sw',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Arifa';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Nakili';
@override
String get cutButtonLabel => 'Kata';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'Saa $hour kamili';
@override
String get datePickerHourSemanticsLabelOther => r'Saa $hour kamili';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => 'Dakika 1';
@override
String get datePickerMinuteSemanticsLabelOther => r'Dakika $minute';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Tafuta';
@override
String get menuDismissLabel => 'Ondoa menyu';
@override
String get modalBarrierDismissLabel => 'Ondoa';
@override
String get noSpellCheckReplacementsLabel => 'Hakuna Neno Mbadala Lilopatikana';
@override
String get pasteButtonLabel => 'Bandika';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Tafuta';
@override
String get searchWebButtonLabel => 'Tafuta kwenye Wavuti';
@override
String get selectAllButtonLabel => 'Teua Zote';
@override
String get shareButtonLabel => 'Shiriki...';
@override
String get tabSemanticsLabelRaw => r'Kichupo cha $tabIndex kati ya $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'saa';
@override
String get timerPickerHourLabelOther => 'saa';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'dakika';
@override
String get timerPickerMinuteLabelOther => 'dakika';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'sekunde';
@override
String get timerPickerSecondLabelOther => 'sekunde';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Leo';
}
/// The translations for Tamil (`ta`).
class CupertinoLocalizationTa extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Tamil.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationTa({
super.localeName = 'ta',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'விழிப்பூட்டல்';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'நகலெடு';
@override
String get cutButtonLabel => 'வெட்டு';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour மணி';
@override
String get datePickerHourSemanticsLabelOther => r'$hour மணி';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 நிமிடம்';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute நிமிடங்கள்';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'தேடு';
@override
String get menuDismissLabel => 'மெனுவை மூடும்';
@override
String get modalBarrierDismissLabel => 'நிராகரிக்கும்';
@override
String get noSpellCheckReplacementsLabel => 'மாற்று வார்த்தைகள் கிடைக்கவில்லை';
@override
String get pasteButtonLabel => 'ஒட்டு';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'தேடுக';
@override
String get searchWebButtonLabel => 'இணையத்தில் தேடு';
@override
String get selectAllButtonLabel => 'எல்லாம் தேர்ந்தெடு';
@override
String get shareButtonLabel => 'பகிர்...';
@override
String get tabSemanticsLabelRaw => r'தாவல் $tabIndex / $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'மணிநேரம்';
@override
String get timerPickerHourLabelOther => 'மணிநேரம்';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'நிமி.';
@override
String get timerPickerMinuteLabelOther => 'நிமி.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'வி.';
@override
String get timerPickerSecondLabelOther => 'வி.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'இன்று';
}
/// The translations for Telugu (`te`).
class CupertinoLocalizationTe extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Telugu.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationTe({
super.localeName = 'te',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'అలర్ట్';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'కాపీ చేయి';
@override
String get cutButtonLabel => 'కత్తిరించండి';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour అవుతుంది';
@override
String get datePickerHourSemanticsLabelOther => r'$hour అవుతుంది';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 నిమిషం';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute నిమిషాలు';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'వెతకండి';
@override
String get menuDismissLabel => 'మెనూను తీసివేయండి';
@override
String get modalBarrierDismissLabel => 'విస్మరించు';
@override
String get noSpellCheckReplacementsLabel => 'రీప్లేస్మెంట్లు ఏవీ కనుగొనబడలేదు';
@override
String get pasteButtonLabel => 'పేస్ట్ చేయండి';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'సెర్చ్ చేయి';
@override
String get searchWebButtonLabel => 'వెబ్లో సెర్చ్ చేయండి';
@override
String get selectAllButtonLabel => 'అన్నింటినీ ఎంచుకోండి';
@override
String get shareButtonLabel => 'షేర్ చేయండి...';
@override
String get tabSemanticsLabelRaw => r'$tabCountలో $tabIndexవ ట్యాబ్';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'గంట';
@override
String get timerPickerHourLabelOther => 'గంటలు';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'నిమి.';
@override
String get timerPickerMinuteLabelOther => 'నిమి.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'సెకన్లు.';
@override
String get timerPickerSecondLabelOther => 'సెకన్లు.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'ఈరోజు';
}
/// The translations for Thai (`th`).
class CupertinoLocalizationTh extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Thai.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationTh({
super.localeName = 'th',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'การแจ้งเตือน';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'คัดลอก';
@override
String get cutButtonLabel => 'ตัด';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour นาฬิกา';
@override
String get datePickerHourSemanticsLabelOther => r'$hour นาฬิกา';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 นาที';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute นาที';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'ค้นหา';
@override
String get menuDismissLabel => 'ปิดเมนู';
@override
String get modalBarrierDismissLabel => 'ปิด';
@override
String get noSpellCheckReplacementsLabel => 'ไม่พบรายการแทนที่';
@override
String get pasteButtonLabel => 'วาง';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'ค้นหา';
@override
String get searchWebButtonLabel => 'ค้นหาบนอินเทอร์เน็ต';
@override
String get selectAllButtonLabel => 'เลือกทั้งหมด';
@override
String get shareButtonLabel => 'แชร์...';
@override
String get tabSemanticsLabelRaw => r'แท็บที่ $tabIndex จาก $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'ชั่วโมง';
@override
String get timerPickerHourLabelOther => 'ชั่วโมง';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'นาที';
@override
String get timerPickerMinuteLabelOther => 'นาที';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'วินาที';
@override
String get timerPickerSecondLabelOther => 'วินาที';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'วันนี้';
}
/// The translations for Tagalog (`tl`).
class CupertinoLocalizationTl extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Tagalog.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationTl({
super.localeName = 'tl',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Alerto';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopyahin';
@override
String get cutButtonLabel => 'I-cut';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'Ala $hour';
@override
String get datePickerHourSemanticsLabelOther => r'Alas $hour';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 minuto';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute na minuto';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Tumingin sa Itaas';
@override
String get menuDismissLabel => 'I-dismiss ang menu';
@override
String get modalBarrierDismissLabel => 'I-dismiss';
@override
String get noSpellCheckReplacementsLabel => 'Walang Nahanap na Kapalit';
@override
String get pasteButtonLabel => 'I-paste';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Hanapin';
@override
String get searchWebButtonLabel => 'Maghanap sa Web';
@override
String get selectAllButtonLabel => 'Piliin Lahat';
@override
String get shareButtonLabel => 'Ibahagi...';
@override
String get tabSemanticsLabelRaw => r'Tab $tabIndex ng $tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'oras';
@override
String get timerPickerHourLabelOther => 'na oras';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'min.';
@override
String get timerPickerMinuteLabelOther => 'na min.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'seg.';
@override
String get timerPickerSecondLabelOther => 'na seg.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Ngayon';
}
/// The translations for Turkish (`tr`).
class CupertinoLocalizationTr extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Turkish.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationTr({
super.localeName = 'tr',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Uyarı';
@override
String get anteMeridiemAbbreviation => 'ÖÖ';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopyala';
@override
String get cutButtonLabel => 'Kes';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'Saat $hour';
@override
String get datePickerHourSemanticsLabelOther => r'Saat $hour';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 dakika';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute dakika';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Ara';
@override
String get menuDismissLabel => 'Menüyü kapat';
@override
String get modalBarrierDismissLabel => 'Kapat';
@override
String get noSpellCheckReplacementsLabel => 'Yerine Kelime Bulunamadı';
@override
String get pasteButtonLabel => 'Yapıştır';
@override
String get postMeridiemAbbreviation => 'ÖS';
@override
String get searchTextFieldPlaceholderLabel => 'Ara';
@override
String get searchWebButtonLabel => "Web'de Ara";
@override
String get selectAllButtonLabel => 'Tümünü Seç';
@override
String get shareButtonLabel => 'Paylaş...';
@override
String get tabSemanticsLabelRaw => r'Sekme $tabIndex/$tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'saat';
@override
String get timerPickerHourLabelOther => 'saat';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'dk.';
@override
String get timerPickerMinuteLabelOther => 'dk.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'sn.';
@override
String get timerPickerSecondLabelOther => 'sn.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Bugün';
}
/// The translations for Ukrainian (`uk`).
class CupertinoLocalizationUk extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Ukrainian.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationUk({
super.localeName = 'uk',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Сповіщення';
@override
String get anteMeridiemAbbreviation => 'дп';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Копіювати';
@override
String get cutButtonLabel => 'Вирізати';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => r'$hour години';
@override
String? get datePickerHourSemanticsLabelMany => r'$hour годин';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour година';
@override
String get datePickerHourSemanticsLabelOther => r'$hour години';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => r'$minute хвилини';
@override
String? get datePickerMinuteSemanticsLabelMany => r'$minute хвилин';
@override
String? get datePickerMinuteSemanticsLabelOne => '1 хвилина';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute хвилини';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Шукати';
@override
String get menuDismissLabel => 'Закрити меню';
@override
String get modalBarrierDismissLabel => 'Закрити';
@override
String get noSpellCheckReplacementsLabel => 'Замін не знайдено';
@override
String get pasteButtonLabel => 'Вставити';
@override
String get postMeridiemAbbreviation => 'пп';
@override
String get searchTextFieldPlaceholderLabel => 'Шукайте';
@override
String get searchWebButtonLabel => 'Пошук в Інтернеті';
@override
String get selectAllButtonLabel => 'Вибрати все';
@override
String get shareButtonLabel => 'Поділитися…';
@override
String get tabSemanticsLabelRaw => r'Вкладка $tabIndex з $tabCount';
@override
String? get timerPickerHourLabelFew => 'години';
@override
String? get timerPickerHourLabelMany => 'годин';
@override
String? get timerPickerHourLabelOne => 'година';
@override
String get timerPickerHourLabelOther => 'години';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => 'хв';
@override
String? get timerPickerMinuteLabelMany => 'хв';
@override
String? get timerPickerMinuteLabelOne => 'хв';
@override
String get timerPickerMinuteLabelOther => 'хв';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => 'с';
@override
String? get timerPickerSecondLabelMany => 'с';
@override
String? get timerPickerSecondLabelOne => 'с';
@override
String get timerPickerSecondLabelOther => 'с';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Сьогодні';
}
/// The translations for Urdu (`ur`).
class CupertinoLocalizationUr extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Urdu.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationUr({
super.localeName = 'ur',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'الرٹ';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'کاپی کریں';
@override
String get cutButtonLabel => 'کٹ کریں';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour بجے';
@override
String get datePickerHourSemanticsLabelOther => r'$hour بجے';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 منٹ';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute منٹس';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'تفصیل دیکھیں';
@override
String get menuDismissLabel => 'مینو برخاست کریں';
@override
String get modalBarrierDismissLabel => 'برخاست کریں';
@override
String get noSpellCheckReplacementsLabel => 'کوئی تبدیلیاں نہیں ملیں';
@override
String get pasteButtonLabel => 'پیسٹ کریں';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'تلاش کریں';
@override
String get searchWebButtonLabel => 'ویب تلاش کریں';
@override
String get selectAllButtonLabel => 'سبھی منتخب کریں';
@override
String get shareButtonLabel => 'اشتراک کریں...';
@override
String get tabSemanticsLabelRaw => r'$tabCount میں سے $tabIndex ٹیب';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'گھنٹہ';
@override
String get timerPickerHourLabelOther => 'گھنٹے';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'منٹ۔';
@override
String get timerPickerMinuteLabelOther => 'منٹ۔';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'سیکنڈ۔';
@override
String get timerPickerSecondLabelOther => 'سیکنڈ۔';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'آج';
}
/// The translations for Uzbek (`uz`).
class CupertinoLocalizationUz extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Uzbek.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationUz({
super.localeName = 'uz',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Ogohlantirish';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Nusxa olish';
@override
String get cutButtonLabel => 'Kesib olish';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour soat';
@override
String get datePickerHourSemanticsLabelOther => r'$hour soat';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 daqiqa';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute daqiqa';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Tepaga qarang';
@override
String get menuDismissLabel => 'Menyuni yopish';
@override
String get modalBarrierDismissLabel => 'Yopish';
@override
String get noSpellCheckReplacementsLabel => 'Almashtirish uchun soʻz topilmadi';
@override
String get pasteButtonLabel => 'Joylash';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Qidiruv';
@override
String get searchWebButtonLabel => 'Internetdan qidirish';
@override
String get selectAllButtonLabel => 'Barchasini tanlash';
@override
String get shareButtonLabel => 'Ulashish…';
@override
String get tabSemanticsLabelRaw => r'$tabCount varaqdan $tabIndex';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'soat';
@override
String get timerPickerHourLabelOther => 'soat';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'daqiqa';
@override
String get timerPickerMinuteLabelOther => 'daqiqa';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'soniya';
@override
String get timerPickerSecondLabelOther => 'soniya';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Bugun';
}
/// The translations for Vietnamese (`vi`).
class CupertinoLocalizationVi extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Vietnamese.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationVi({
super.localeName = 'vi',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Thông báo';
@override
String get anteMeridiemAbbreviation => 'SÁNG';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Sao chép';
@override
String get cutButtonLabel => 'Cắt';
@override
String get datePickerDateOrderString => 'dmy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour giờ';
@override
String get datePickerHourSemanticsLabelOther => r'$hour giờ';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 phút';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute phút';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Tra cứu';
@override
String get menuDismissLabel => 'Đóng trình đơn';
@override
String get modalBarrierDismissLabel => 'Bỏ qua';
@override
String get noSpellCheckReplacementsLabel => 'Không tìm thấy phương án thay thế';
@override
String get pasteButtonLabel => 'Dán';
@override
String get postMeridiemAbbreviation => 'CHIỀU';
@override
String get searchTextFieldPlaceholderLabel => 'Tìm kiếm';
@override
String get searchWebButtonLabel => 'Tìm kiếm trên web';
@override
String get selectAllButtonLabel => 'Chọn tất cả';
@override
String get shareButtonLabel => 'Chia sẻ...';
@override
String get tabSemanticsLabelRaw => r'Thẻ $tabIndex/$tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'giờ';
@override
String get timerPickerHourLabelOther => 'giờ';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'phút';
@override
String get timerPickerMinuteLabelOther => 'phút';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'giây';
@override
String get timerPickerSecondLabelOther => 'giây';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Hôm nay';
}
/// The translations for Chinese (`zh`).
class CupertinoLocalizationZh extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Chinese.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationZh({
super.localeName = 'zh',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => '提醒';
@override
String get anteMeridiemAbbreviation => '上午';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => '复制';
@override
String get cutButtonLabel => '剪切';
@override
String get datePickerDateOrderString => 'ymd';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour 点';
@override
String get datePickerHourSemanticsLabelOther => r'$hour 点';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 分钟';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute 分钟';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => '查询';
@override
String get menuDismissLabel => '关闭菜单';
@override
String get modalBarrierDismissLabel => '关闭';
@override
String get noSpellCheckReplacementsLabel => '找不到替换文字';
@override
String get pasteButtonLabel => '粘贴';
@override
String get postMeridiemAbbreviation => '下午';
@override
String get searchTextFieldPlaceholderLabel => '搜索';
@override
String get searchWebButtonLabel => '搜索';
@override
String get selectAllButtonLabel => '全选';
@override
String get shareButtonLabel => '共享…';
@override
String get tabSemanticsLabelRaw => r'第 $tabIndex 个标签,共 $tabCount 个';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => '小时';
@override
String get timerPickerHourLabelOther => '小时';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => '分钟';
@override
String get timerPickerMinuteLabelOther => '分钟';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => '秒';
@override
String get timerPickerSecondLabelOther => '秒';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => '今天';
}
/// The translations for Chinese, using the Han script (`zh_Hans`).
class CupertinoLocalizationZhHans extends CupertinoLocalizationZh {
/// Create an instance of the translation bundle for Chinese, using the Han script.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationZhHans({
super.localeName = 'zh_Hans',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
}
/// The translations for Chinese, using the Han script (`zh_Hant`).
class CupertinoLocalizationZhHant extends CupertinoLocalizationZh {
/// Create an instance of the translation bundle for Chinese, using the Han script.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationZhHant({
super.localeName = 'zh_Hant',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => '通知';
@override
String get copyButtonLabel => '複製';
@override
String get cutButtonLabel => '剪下';
@override
String get datePickerDateTimeOrderString => 'date_dayPeriod_time';
@override
String? get datePickerHourSemanticsLabelOne => r'$hour 點';
@override
String get datePickerHourSemanticsLabelOther => r'$hour 點';
@override
String? get datePickerMinuteSemanticsLabelOne => '1 分鐘';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute 分鐘';
@override
String get lookUpButtonLabel => '查詢';
@override
String get menuDismissLabel => '閂選單';
@override
String get modalBarrierDismissLabel => '拒絕';
@override
String get noSpellCheckReplacementsLabel => '找不到替換字詞';
@override
String get pasteButtonLabel => '貼上';
@override
String get searchTextFieldPlaceholderLabel => '搜尋';
@override
String get searchWebButtonLabel => '搜尋';
@override
String get selectAllButtonLabel => '全選';
@override
String get shareButtonLabel => '分享…';
@override
String get tabSemanticsLabelRaw => r'$tabCount 個分頁中嘅第 $tabIndex 個';
@override
String? get timerPickerHourLabelOne => '小時';
@override
String get timerPickerHourLabelOther => '小時';
@override
String? get timerPickerMinuteLabelOne => '分鐘';
@override
String get timerPickerMinuteLabelOther => '分鐘';
}
/// The translations for Chinese, as used in Hong Kong, using the Han script (`zh_Hant_HK`).
class CupertinoLocalizationZhHantHk extends CupertinoLocalizationZhHant {
/// Create an instance of the translation bundle for Chinese, as used in Hong Kong, using the Han script.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationZhHantHk({
super.localeName = 'zh_Hant_HK',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
}
/// The translations for Chinese, as used in Taiwan, using the Han script (`zh_Hant_TW`).
class CupertinoLocalizationZhHantTw extends CupertinoLocalizationZhHant {
/// Create an instance of the translation bundle for Chinese, as used in Taiwan, using the Han script.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationZhHantTw({
super.localeName = 'zh_Hant_TW',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get noSpellCheckReplacementsLabel => '找不到替代文字';
@override
String get menuDismissLabel => '關閉選單';
@override
String get tabSemanticsLabelRaw => r'第 $tabIndex 個分頁標籤,共 $tabCount 個';
@override
String? get datePickerMinuteSemanticsLabelOne => '1 分';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute 分';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String get alertDialogLabel => '快訊';
@override
String? get timerPickerMinuteLabelOne => '分';
@override
String get timerPickerMinuteLabelOther => '分';
@override
String get modalBarrierDismissLabel => '關閉';
}
/// The translations for Zulu (`zu`).
class CupertinoLocalizationZu extends GlobalCupertinoLocalizations {
/// Create an instance of the translation bundle for Zulu.
///
/// For details on the meaning of the arguments, see [GlobalCupertinoLocalizations].
const CupertinoLocalizationZu({
super.localeName = 'zu',
required super.fullYearFormat,
required super.dayFormat,
required super.mediumDateFormat,
required super.singleDigitHourFormat,
required super.singleDigitMinuteFormat,
required super.doubleDigitMinuteFormat,
required super.singleDigitSecondFormat,
required super.decimalFormat,
});
@override
String get alertDialogLabel => 'Isexwayiso';
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get clearButtonLabel => 'Clear';
@override
String get copyButtonLabel => 'Kopisha';
@override
String get cutButtonLabel => 'Sika';
@override
String get datePickerDateOrderString => 'mdy';
@override
String get datePickerDateTimeOrderString => 'date_time_dayPeriod';
@override
String? get datePickerHourSemanticsLabelFew => null;
@override
String? get datePickerHourSemanticsLabelMany => null;
@override
String? get datePickerHourSemanticsLabelOne => r'$hour ezimpondweni';
@override
String get datePickerHourSemanticsLabelOther => r'$hour ezimpondweni';
@override
String? get datePickerHourSemanticsLabelTwo => null;
@override
String? get datePickerHourSemanticsLabelZero => null;
@override
String? get datePickerMinuteSemanticsLabelFew => null;
@override
String? get datePickerMinuteSemanticsLabelMany => null;
@override
String? get datePickerMinuteSemanticsLabelOne => '1 iminithi';
@override
String get datePickerMinuteSemanticsLabelOther => r'$minute amaminithi';
@override
String? get datePickerMinuteSemanticsLabelTwo => null;
@override
String? get datePickerMinuteSemanticsLabelZero => null;
@override
String get lookUpButtonLabel => 'Bheka Phezulu';
@override
String get menuDismissLabel => 'Chitha imenyu';
@override
String get modalBarrierDismissLabel => 'Cashisa';
@override
String get noSpellCheckReplacementsLabel => 'Akukho Okuzofakwa Esikhundleni Okutholakele';
@override
String get pasteButtonLabel => 'Namathisela';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get searchTextFieldPlaceholderLabel => 'Sesha';
@override
String get searchWebButtonLabel => 'Sesha Iwebhu';
@override
String get selectAllButtonLabel => 'Khetha konke';
@override
String get shareButtonLabel => 'Yabelana...';
@override
String get tabSemanticsLabelRaw => r'Ithebhu $tabIndex kwangu-$tabCount';
@override
String? get timerPickerHourLabelFew => null;
@override
String? get timerPickerHourLabelMany => null;
@override
String? get timerPickerHourLabelOne => 'ihora';
@override
String get timerPickerHourLabelOther => 'amahora';
@override
String? get timerPickerHourLabelTwo => null;
@override
String? get timerPickerHourLabelZero => null;
@override
String? get timerPickerMinuteLabelFew => null;
@override
String? get timerPickerMinuteLabelMany => null;
@override
String? get timerPickerMinuteLabelOne => 'iminithi.';
@override
String get timerPickerMinuteLabelOther => 'iminithi.';
@override
String? get timerPickerMinuteLabelTwo => null;
@override
String? get timerPickerMinuteLabelZero => null;
@override
String? get timerPickerSecondLabelFew => null;
@override
String? get timerPickerSecondLabelMany => null;
@override
String? get timerPickerSecondLabelOne => 'isekhondi.';
@override
String get timerPickerSecondLabelOther => 'isekhondi.';
@override
String? get timerPickerSecondLabelTwo => null;
@override
String? get timerPickerSecondLabelZero => null;
@override
String get todayLabel => 'Namuhla';
}
/// The set of supported languages, as language code strings.
///
/// The [GlobalCupertinoLocalizations.delegate] can generate localizations for
/// any [Locale] with a language code from this set, regardless of the region.
/// Some regions have specific support (e.g. `de` covers all forms of German,
/// but there is support for `de-CH` specifically to override some of the
/// translations for Switzerland).
///
/// See also:
///
/// * [getCupertinoTranslation], whose documentation describes these values.
final Set<String> kCupertinoSupportedLanguages = HashSet<String>.from(const <String>[
'af', // Afrikaans
'am', // Amharic
'ar', // Arabic
'as', // Assamese
'az', // Azerbaijani
'be', // Belarusian
'bg', // Bulgarian
'bn', // Bengali Bangla
'bs', // Bosnian
'ca', // Catalan Valencian
'cs', // Czech
'cy', // Welsh
'da', // Danish
'de', // German
'el', // Modern Greek
'en', // English
'es', // Spanish Castilian
'et', // Estonian
'eu', // Basque
'fa', // Persian
'fi', // Finnish
'fil', // Filipino Pilipino
'fr', // French
'gl', // Galician
'gsw', // Swiss German Alemannic Alsatian
'gu', // Gujarati
'he', // Hebrew
'hi', // Hindi
'hr', // Croatian
'hu', // Hungarian
'hy', // Armenian
'id', // Indonesian
'is', // Icelandic
'it', // Italian
'ja', // Japanese
'ka', // Georgian
'kk', // Kazakh
'km', // Khmer Central Khmer
'kn', // Kannada
'ko', // Korean
'ky', // Kirghiz Kyrgyz
'lo', // Lao
'lt', // Lithuanian
'lv', // Latvian
'mk', // Macedonian
'ml', // Malayalam
'mn', // Mongolian
'mr', // Marathi
'ms', // Malay
'my', // Burmese
'nb', // Norwegian Bokmål
'ne', // Nepali
'nl', // Dutch Flemish
'no', // Norwegian
'or', // Oriya
'pa', // Panjabi Punjabi
'pl', // Polish
'pt', // Portuguese
'ro', // Romanian Moldavian Moldovan
'ru', // Russian
'si', // Sinhala Sinhalese
'sk', // Slovak
'sl', // Slovenian
'sq', // Albanian
'sr', // Serbian
'sv', // Swedish
'sw', // Swahili
'ta', // Tamil
'te', // Telugu
'th', // Thai
'tl', // Tagalog
'tr', // Turkish
'uk', // Ukrainian
'ur', // Urdu
'uz', // Uzbek
'vi', // Vietnamese
'zh', // Chinese
'zu', // Zulu
]);
/// Creates a [GlobalCupertinoLocalizations] instance for the given `locale`.
///
/// All of the function's arguments except `locale` will be passed to the [
/// GlobalCupertinoLocalizations] constructor. (The `localeName` argument of that
/// constructor is specified by the actual subclass constructor by this
/// function.)
///
/// The following locales are supported by this package:
///
/// {@template flutter.localizations.cupertino.languages}
/// * `af` - Afrikaans
/// * `am` - Amharic
/// * `ar` - Arabic
/// * `as` - Assamese
/// * `az` - Azerbaijani
/// * `be` - Belarusian
/// * `bg` - Bulgarian
/// * `bn` - Bengali Bangla
/// * `bs` - Bosnian
/// * `ca` - Catalan Valencian
/// * `cs` - Czech
/// * `cy` - Welsh
/// * `da` - Danish
/// * `de` - German (plus one country variation)
/// * `el` - Modern Greek
/// * `en` - English (plus 8 country variations)
/// * `es` - Spanish Castilian (plus 20 country variations)
/// * `et` - Estonian
/// * `eu` - Basque
/// * `fa` - Persian
/// * `fi` - Finnish
/// * `fil` - Filipino Pilipino
/// * `fr` - French (plus one country variation)
/// * `gl` - Galician
/// * `gsw` - Swiss German Alemannic Alsatian
/// * `gu` - Gujarati
/// * `he` - Hebrew
/// * `hi` - Hindi
/// * `hr` - Croatian
/// * `hu` - Hungarian
/// * `hy` - Armenian
/// * `id` - Indonesian
/// * `is` - Icelandic
/// * `it` - Italian
/// * `ja` - Japanese
/// * `ka` - Georgian
/// * `kk` - Kazakh
/// * `km` - Khmer Central Khmer
/// * `kn` - Kannada
/// * `ko` - Korean
/// * `ky` - Kirghiz Kyrgyz
/// * `lo` - Lao
/// * `lt` - Lithuanian
/// * `lv` - Latvian
/// * `mk` - Macedonian
/// * `ml` - Malayalam
/// * `mn` - Mongolian
/// * `mr` - Marathi
/// * `ms` - Malay
/// * `my` - Burmese
/// * `nb` - Norwegian Bokmål
/// * `ne` - Nepali
/// * `nl` - Dutch Flemish
/// * `no` - Norwegian
/// * `or` - Oriya
/// * `pa` - Panjabi Punjabi
/// * `pl` - Polish
/// * `pt` - Portuguese (plus one country variation)
/// * `ro` - Romanian Moldavian Moldovan
/// * `ru` - Russian
/// * `si` - Sinhala Sinhalese
/// * `sk` - Slovak
/// * `sl` - Slovenian
/// * `sq` - Albanian
/// * `sr` - Serbian (plus 2 scripts)
/// * `sv` - Swedish
/// * `sw` - Swahili
/// * `ta` - Tamil
/// * `te` - Telugu
/// * `th` - Thai
/// * `tl` - Tagalog
/// * `tr` - Turkish
/// * `uk` - Ukrainian
/// * `ur` - Urdu
/// * `uz` - Uzbek
/// * `vi` - Vietnamese
/// * `zh` - Chinese (plus 2 country variations and 2 scripts)
/// * `zu` - Zulu
/// {@endtemplate}
///
/// Generally speaking, this method is only intended to be used by
/// [GlobalCupertinoLocalizations.delegate].
GlobalCupertinoLocalizations? getCupertinoTranslation(
Locale locale,
intl.DateFormat fullYearFormat,
intl.DateFormat dayFormat,
intl.DateFormat mediumDateFormat,
intl.DateFormat singleDigitHourFormat,
intl.DateFormat singleDigitMinuteFormat,
intl.DateFormat doubleDigitMinuteFormat,
intl.DateFormat singleDigitSecondFormat,
intl.NumberFormat decimalFormat,
) {
switch (locale.languageCode) {
case 'af':
return CupertinoLocalizationAf(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'am':
return CupertinoLocalizationAm(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'ar':
return CupertinoLocalizationAr(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'as':
return CupertinoLocalizationAs(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'az':
return CupertinoLocalizationAz(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'be':
return CupertinoLocalizationBe(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'bg':
return CupertinoLocalizationBg(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'bn':
return CupertinoLocalizationBn(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'bs':
return CupertinoLocalizationBs(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'ca':
return CupertinoLocalizationCa(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'cs':
return CupertinoLocalizationCs(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'cy':
return CupertinoLocalizationCy(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'da':
return CupertinoLocalizationDa(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'de': {
switch (locale.countryCode) {
case 'CH':
return CupertinoLocalizationDeCh(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
return CupertinoLocalizationDe(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
case 'el':
return CupertinoLocalizationEl(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'en': {
switch (locale.countryCode) {
case 'AU':
return CupertinoLocalizationEnAu(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'CA':
return CupertinoLocalizationEnCa(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'GB':
return CupertinoLocalizationEnGb(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'IE':
return CupertinoLocalizationEnIe(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'IN':
return CupertinoLocalizationEnIn(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'NZ':
return CupertinoLocalizationEnNz(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'SG':
return CupertinoLocalizationEnSg(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'ZA':
return CupertinoLocalizationEnZa(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
return CupertinoLocalizationEn(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
case 'es': {
switch (locale.countryCode) {
case '419':
return CupertinoLocalizationEs419(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'AR':
return CupertinoLocalizationEsAr(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'BO':
return CupertinoLocalizationEsBo(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'CL':
return CupertinoLocalizationEsCl(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'CO':
return CupertinoLocalizationEsCo(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'CR':
return CupertinoLocalizationEsCr(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'DO':
return CupertinoLocalizationEsDo(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'EC':
return CupertinoLocalizationEsEc(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'GT':
return CupertinoLocalizationEsGt(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'HN':
return CupertinoLocalizationEsHn(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'MX':
return CupertinoLocalizationEsMx(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'NI':
return CupertinoLocalizationEsNi(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'PA':
return CupertinoLocalizationEsPa(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'PE':
return CupertinoLocalizationEsPe(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'PR':
return CupertinoLocalizationEsPr(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'PY':
return CupertinoLocalizationEsPy(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'SV':
return CupertinoLocalizationEsSv(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'US':
return CupertinoLocalizationEsUs(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'UY':
return CupertinoLocalizationEsUy(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'VE':
return CupertinoLocalizationEsVe(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
return CupertinoLocalizationEs(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
case 'et':
return CupertinoLocalizationEt(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'eu':
return CupertinoLocalizationEu(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'fa':
return CupertinoLocalizationFa(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'fi':
return CupertinoLocalizationFi(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'fil':
return CupertinoLocalizationFil(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'fr': {
switch (locale.countryCode) {
case 'CA':
return CupertinoLocalizationFrCa(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
return CupertinoLocalizationFr(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
case 'gl':
return CupertinoLocalizationGl(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'gsw':
return CupertinoLocalizationGsw(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'gu':
return CupertinoLocalizationGu(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'he':
return CupertinoLocalizationHe(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'hi':
return CupertinoLocalizationHi(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'hr':
return CupertinoLocalizationHr(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'hu':
return CupertinoLocalizationHu(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'hy':
return CupertinoLocalizationHy(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'id':
return CupertinoLocalizationId(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'is':
return CupertinoLocalizationIs(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'it':
return CupertinoLocalizationIt(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'ja':
return CupertinoLocalizationJa(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'ka':
return CupertinoLocalizationKa(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'kk':
return CupertinoLocalizationKk(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'km':
return CupertinoLocalizationKm(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'kn':
return CupertinoLocalizationKn(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'ko':
return CupertinoLocalizationKo(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'ky':
return CupertinoLocalizationKy(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'lo':
return CupertinoLocalizationLo(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'lt':
return CupertinoLocalizationLt(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'lv':
return CupertinoLocalizationLv(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'mk':
return CupertinoLocalizationMk(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'ml':
return CupertinoLocalizationMl(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'mn':
return CupertinoLocalizationMn(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'mr':
return CupertinoLocalizationMr(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'ms':
return CupertinoLocalizationMs(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'my':
return CupertinoLocalizationMy(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'nb':
return CupertinoLocalizationNb(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'ne':
return CupertinoLocalizationNe(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'nl':
return CupertinoLocalizationNl(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'no':
return CupertinoLocalizationNo(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'or':
return CupertinoLocalizationOr(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'pa':
return CupertinoLocalizationPa(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'pl':
return CupertinoLocalizationPl(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'pt': {
switch (locale.countryCode) {
case 'PT':
return CupertinoLocalizationPtPt(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
return CupertinoLocalizationPt(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
case 'ro':
return CupertinoLocalizationRo(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'ru':
return CupertinoLocalizationRu(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'si':
return CupertinoLocalizationSi(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'sk':
return CupertinoLocalizationSk(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'sl':
return CupertinoLocalizationSl(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'sq':
return CupertinoLocalizationSq(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'sr': {
switch (locale.scriptCode) {
case 'Cyrl': {
return CupertinoLocalizationSrCyrl(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
case 'Latn': {
return CupertinoLocalizationSrLatn(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
}
return CupertinoLocalizationSr(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
case 'sv':
return CupertinoLocalizationSv(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'sw':
return CupertinoLocalizationSw(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'ta':
return CupertinoLocalizationTa(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'te':
return CupertinoLocalizationTe(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'th':
return CupertinoLocalizationTh(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'tl':
return CupertinoLocalizationTl(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'tr':
return CupertinoLocalizationTr(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'uk':
return CupertinoLocalizationUk(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'ur':
return CupertinoLocalizationUr(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'uz':
return CupertinoLocalizationUz(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'vi':
return CupertinoLocalizationVi(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'zh': {
switch (locale.scriptCode) {
case 'Hans': {
return CupertinoLocalizationZhHans(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
case 'Hant': {
switch (locale.countryCode) {
case 'HK':
return CupertinoLocalizationZhHantHk(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'TW':
return CupertinoLocalizationZhHantTw(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
return CupertinoLocalizationZhHant(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
}
switch (locale.countryCode) {
case 'HK':
return CupertinoLocalizationZhHantHk(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
case 'TW':
return CupertinoLocalizationZhHantTw(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
return CupertinoLocalizationZh(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
case 'zu':
return CupertinoLocalizationZu(fullYearFormat: fullYearFormat, dayFormat: dayFormat, mediumDateFormat: mediumDateFormat, singleDigitHourFormat: singleDigitHourFormat, singleDigitMinuteFormat: singleDigitMinuteFormat, doubleDigitMinuteFormat: doubleDigitMinuteFormat, singleDigitSecondFormat: singleDigitSecondFormat, decimalFormat: decimalFormat);
}
assert(false, 'getCupertinoTranslation() called for unsupported locale "$locale"');
return null;
}
| flutter/packages/flutter_localizations/lib/src/l10n/generated_cupertino_localizations.dart/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/generated_cupertino_localizations.dart",
"repo_id": "flutter",
"token_count": 137800
} | 896 |
{
"scriptCategory": "English-like",
"timeOfDayFormat": "HH.mm",
"openAppDrawerTooltip": "Åbn navigationsmenuen",
"backButtonTooltip": "Tilbage",
"closeButtonTooltip": "Luk",
"deleteButtonTooltip": "Slet",
"nextMonthTooltip": "Næste måned",
"previousMonthTooltip": "Forrige måned",
"nextPageTooltip": "Næste side",
"previousPageTooltip": "Forrige side",
"firstPageTooltip": "Første side",
"lastPageTooltip": "Sidste side",
"showMenuTooltip": "Vis menu",
"aboutListTileTitle": "Om $applicationName",
"licensesPageTitle": "Licenser",
"pageRowsInfoTitle": "$firstRow-$lastRow af $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow-$lastRow af ca. $rowCount",
"rowsPerPageTitle": "Rækker pr. side:",
"tabLabel": "Fane $tabIndex af $tabCount",
"selectedRowCountTitleOne": "1 element er valgt",
"selectedRowCountTitleOther": "$selectedRowCount elementer er valgt",
"cancelButtonLabel": "Annuller",
"closeButtonLabel": "Luk",
"continueButtonLabel": "Fortsæt",
"copyButtonLabel": "Kopiér",
"cutButtonLabel": "Klip",
"scanTextButtonLabel": "Scan tekst",
"okButtonLabel": "OK",
"pasteButtonLabel": "Indsæt",
"selectAllButtonLabel": "Markér alt",
"viewLicensesButtonLabel": "Se licenser",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"timePickerHourModeAnnouncement": "Vælg timer",
"timePickerMinuteModeAnnouncement": "Vælg minutter",
"modalBarrierDismissLabel": "Afvis",
"signedInLabel": "Logget ind",
"hideAccountsLabel": "Skjul konti",
"showAccountsLabel": "Vis konti",
"drawerLabel": "Navigationsmenu",
"popupMenuLabel": "Pop op-menu",
"dialogLabel": "Dialogboks",
"alertDialogLabel": "Underretning",
"searchFieldLabel": "Søg",
"reorderItemToStart": "Flyt til først på listen",
"reorderItemToEnd": "Flyt til sidst på listen",
"reorderItemUp": "Flyt op",
"reorderItemDown": "Flyt ned",
"reorderItemLeft": "Flyt til venstre",
"reorderItemRight": "Flyt til højre",
"expandedIconTapHint": "Skjul",
"collapsedIconTapHint": "Udvid",
"remainingTextFieldCharacterCountOne": "Ét tegn tilbage",
"remainingTextFieldCharacterCountOther": "$remainingCount tegn tilbage",
"refreshIndicatorSemanticLabel": "Opdater",
"moreButtonTooltip": "Mere",
"dateSeparator": ".",
"dateHelpText": "dd/mm/åååå",
"selectYearSemanticsLabel": "Vælg år",
"unspecifiedDate": "Dato",
"unspecifiedDateRange": "Datointerval",
"dateInputLabel": "Angiv en dato",
"dateRangeStartLabel": "Startdato",
"dateRangeEndLabel": "Slutdato",
"dateRangeStartDateSemanticLabel": "Startdato $fullDate",
"dateRangeEndDateSemanticLabel": "Slutdato $fullDate",
"invalidDateFormatLabel": "Ugyldigt format.",
"invalidDateRangeLabel": "Ugyldigt interval.",
"dateOutOfRangeLabel": "Uden for rækkevidde.",
"saveButtonLabel": "Gem",
"datePickerHelpText": "Vælg dato",
"dateRangePickerHelpText": "Vælg interval",
"calendarModeButtonLabel": "Skift til kalender",
"inputDateModeButtonLabel": "Skift til input",
"timePickerDialHelpText": "Vælg tidspunkt",
"timePickerInputHelpText": "Angiv tidspunkt",
"timePickerHourLabel": "Time",
"timePickerMinuteLabel": "Minut",
"invalidTimeLabel": "Angiv et gyldigt tidspunkt",
"dialModeButtonLabel": "Skift til urskivevælger",
"inputTimeModeButtonLabel": "Skift til indtastning",
"licensesPackageDetailTextZero": "No licenses",
"licensesPackageDetailTextOne": "1 licens",
"licensesPackageDetailTextOther": "$licenseCount licenser",
"keyboardKeyAlt": "Alt",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyBackspace": "Backspace",
"keyboardKeyCapsLock": "Caps Lock",
"keyboardKeyChannelDown": "Channel Down",
"keyboardKeyChannelUp": "Channel Up",
"keyboardKeyControl": "Ctrl",
"keyboardKeyDelete": "Del",
"keyboardKeyEject": "Skub ud",
"keyboardKeyEnd": "End",
"keyboardKeyEscape": "Esc",
"keyboardKeyFn": "Fn",
"keyboardKeyHome": "Home",
"keyboardKeyInsert": "Insert",
"keyboardKeyMeta": "Meta",
"keyboardKeyNumLock": "Num Lock",
"keyboardKeyNumpad1": "Num 1",
"keyboardKeyNumpad2": "Num 2",
"keyboardKeyNumpad3": "Num 3",
"keyboardKeyNumpad4": "Num 4",
"keyboardKeyNumpad5": "Num 5",
"keyboardKeyNumpad6": "Num 6",
"keyboardKeyNumpad7": "Num 7",
"keyboardKeyNumpad8": "Num 8",
"keyboardKeyNumpad9": "Num 9",
"keyboardKeyNumpad0": "Num 0",
"keyboardKeyNumpadAdd": "Num +",
"keyboardKeyNumpadComma": "Num ,",
"keyboardKeyNumpadDecimal": "Num .",
"keyboardKeyNumpadDivide": "Num /",
"keyboardKeyNumpadEnter": "Num Enter",
"keyboardKeyNumpadEqual": "Num =",
"keyboardKeyNumpadMultiply": "Num *",
"keyboardKeyNumpadParenLeft": "Num (",
"keyboardKeyNumpadParenRight": "Num )",
"keyboardKeyNumpadSubtract": "Num -",
"keyboardKeyPageDown": "PgDn",
"keyboardKeyPageUp": "PgUp",
"keyboardKeyPower": "Strøm",
"keyboardKeyPowerOff": "Sluk",
"keyboardKeyPrintScreen": "Print Screen",
"keyboardKeyScrollLock": "Scroll Lock",
"keyboardKeySelect": "Vælg",
"keyboardKeySpace": "Mellemrumstasten",
"keyboardKeyMetaMacOs": "Command",
"keyboardKeyMetaWindows": "Win",
"menuBarMenuLabel": "Menuen for menulinjen",
"currentDateLabel": "I dag",
"scrimLabel": "Dæmpeskærm",
"bottomSheetLabel": "Felt i bunden",
"scrimOnTapHint": "Luk $modalRouteContentName",
"keyboardKeyShift": "Shift",
"expansionTileExpandedHint": "tryk to gange for at skjule",
"expansionTileCollapsedHint": "tryk to gange for at udvide",
"expansionTileExpandedTapHint": "Skjul",
"expansionTileCollapsedTapHint": "Udvid for at få flere oplysninger",
"expandedHint": "Skjult",
"collapsedHint": "Udvidet",
"menuDismissLabel": "Luk menu",
"lookUpButtonLabel": "Slå op",
"searchWebButtonLabel": "Søg på nettet",
"shareButtonLabel": "Del…",
"clearButtonTooltip": "Clear text",
"selectedDateLabel": "Selected"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_da.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_da.arb",
"repo_id": "flutter",
"token_count": 2222
} | 897 |
{
"searchWebButtonLabel": "Buscar en la Web",
"shareButtonLabel": "Compartir…",
"scanTextButtonLabel": "Analizar texto",
"lookUpButtonLabel": "Mirar hacia arriba",
"menuDismissLabel": "Descartar menú",
"expansionTileExpandedHint": "presiona dos veces para contraer",
"expansionTileCollapsedHint": "presiona dos veces para expandir",
"expansionTileExpandedTapHint": "Contraer",
"expansionTileCollapsedTapHint": "Expandir para ver más detalles",
"expandedHint": "Contraído",
"collapsedHint": "Expandido",
"scrimLabel": "Lámina",
"bottomSheetLabel": "Hoja inferior",
"scrimOnTapHint": "Cerrar $modalRouteContentName",
"currentDateLabel": "Hoy",
"keyboardKeyShift": "Mayúsculas",
"menuBarMenuLabel": "Menú de la barra de menú",
"keyboardKeyNumpad8": "Num 8",
"keyboardKeyChannelDown": "Canal anterior",
"keyboardKeyBackspace": "Retroceso",
"keyboardKeyNumpad4": "Num 4",
"keyboardKeyNumpad5": "Num 5",
"keyboardKeyNumpad6": "Num 6",
"keyboardKeyNumpad7": "Num 7",
"keyboardKeyNumpad2": "Num 2",
"keyboardKeyNumpad0": "Num 0",
"keyboardKeyNumpadAdd": "Num +",
"keyboardKeyNumpadComma": "Num ,",
"keyboardKeyNumpadDecimal": "Num .",
"keyboardKeyNumpadDivide": "Num /",
"keyboardKeyNumpadEqual": "Num =",
"keyboardKeyNumpadMultiply": "Num *",
"keyboardKeyNumpadParenLeft": "Num (",
"keyboardKeyInsert": "Insert",
"keyboardKeyHome": "Inicio",
"keyboardKeyEnd": "Fin",
"keyboardKeyNumpadParenRight": "Num )",
"keyboardKeyFn": "Fn",
"keyboardKeyEscape": "Esc",
"keyboardKeyEject": "Expulsar",
"keyboardKeyDelete": "Supr",
"keyboardKeyControl": "Ctrl",
"keyboardKeyNumpadSubtract": "Num -",
"keyboardKeyChannelUp": "Canal siguiente",
"keyboardKeyCapsLock": "Bloqueo de mayúscula",
"keyboardKeySelect": "Select",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyAlt": "Alt",
"keyboardKeyMeta": "Meta",
"keyboardKeyMetaMacOs": "Comando",
"keyboardKeyMetaWindows": "Win",
"keyboardKeyNumLock": "Bloqueo numérico",
"keyboardKeyNumpad1": "Num 1",
"keyboardKeyPageDown": "AvPág",
"keyboardKeySpace": "Barra espaciadora",
"keyboardKeyNumpad3": "Num 3",
"keyboardKeyScrollLock": "Bloqueo de desplazamiento",
"keyboardKeyNumpad9": "Num 9",
"keyboardKeyPrintScreen": "Imprimir pantalla",
"keyboardKeyPowerOff": "Apagar",
"keyboardKeyPower": "Encender",
"keyboardKeyPageUp": "RePág",
"keyboardKeyNumpadEnter": "Num Enter",
"dialModeButtonLabel": "Cambiar al modo de selección de hora",
"licensesPackageDetailTextOne": "1 licencia",
"timePickerDialHelpText": "Selecciona una hora",
"timePickerInputHelpText": "Ingresa una hora",
"timePickerHourLabel": "Hora",
"timePickerMinuteLabel": "Minuto",
"invalidTimeLabel": "Ingresa una hora válida",
"licensesPackageDetailTextOther": "$licenseCount licencias",
"inputTimeModeButtonLabel": "Cambiar al modo de entrada de texto",
"dateSeparator": "/",
"dateInputLabel": "Ingresar fecha",
"calendarModeButtonLabel": "Cambiar al calendario",
"dateRangePickerHelpText": "Selecciona un período",
"datePickerHelpText": "Selecciona una fecha",
"saveButtonLabel": "Guardar",
"dateOutOfRangeLabel": "Fuera de rango",
"invalidDateRangeLabel": "El rango no es válido.",
"invalidDateFormatLabel": "El formato no es válido.",
"dateRangeEndDateSemanticLabel": "Fecha de finalización: $fullDate",
"dateRangeStartDateSemanticLabel": "Fecha de inicio: $fullDate",
"dateRangeEndLabel": "Fecha de finalización",
"dateRangeStartLabel": "Fecha de inicio",
"inputDateModeButtonLabel": "Cambiar a modo de entrada",
"unspecifiedDateRange": "Período",
"unspecifiedDate": "Fecha",
"selectYearSemanticsLabel": "Seleccionar año",
"dateHelpText": "dd/mm/aaaa",
"moreButtonTooltip": "Más",
"reorderItemDown": "Mover hacia abajo",
"reorderItemLeft": "Mover hacia la izquierda",
"reorderItemToEnd": "Mover al final",
"reorderItemRight": "Mover hacia la derecha",
"reorderItemUp": "Mover hacia arriba",
"reorderItemToStart": "Mover al inicio",
"tabLabel": "Pestaña $tabIndex de $tabCount",
"showAccountsLabel": "Mostrar cuentas",
"modalBarrierDismissLabel": "Descartar",
"hideAccountsLabel": "Ocultar cuentas",
"signedInLabel": "Cuenta con la que accediste",
"scriptCategory": "English-like",
"timeOfDayFormat": "H:mm",
"openAppDrawerTooltip": "Abrir menú de navegación",
"backButtonTooltip": "Atrás",
"closeButtonTooltip": "Cerrar",
"deleteButtonTooltip": "Borrar",
"nextMonthTooltip": "Próximo mes",
"previousMonthTooltip": "Mes anterior",
"nextPageTooltip": "Próxima página",
"previousPageTooltip": "Página anterior",
"firstPageTooltip": "Primera página",
"lastPageTooltip": "Última página",
"showMenuTooltip": "Mostrar menú",
"aboutListTileTitle": "Acerca de $applicationName",
"licensesPageTitle": "Licencias",
"pageRowsInfoTitle": "$firstRow–$lastRow de $rowCount",
"pageRowsInfoTitleApproximate": "$firstRow–$lastRow de aproximadamente $rowCount",
"rowsPerPageTitle": "Filas por página:",
"selectedRowCountTitleOne": "Se seleccionó 1 elemento",
"selectedRowCountTitleOther": "Se seleccionaron $selectedRowCount elementos",
"cancelButtonLabel": "Cancelar",
"closeButtonLabel": "Cerrar",
"continueButtonLabel": "Continuar",
"copyButtonLabel": "Copiar",
"cutButtonLabel": "Cortar",
"okButtonLabel": "ACEPTAR",
"pasteButtonLabel": "Pegar",
"selectAllButtonLabel": "Seleccionar todo",
"viewLicensesButtonLabel": "Ver licencias",
"anteMeridiemAbbreviation": "a.m.",
"postMeridiemAbbreviation": "p.m.",
"timePickerHourModeAnnouncement": "Seleccionar horas",
"timePickerMinuteModeAnnouncement": "Seleccionar minutos",
"drawerLabel": "Menú de navegación",
"popupMenuLabel": "Menú emergente",
"dialogLabel": "Diálogo",
"alertDialogLabel": "Alerta",
"searchFieldLabel": "Buscar",
"expandedIconTapHint": "Contraer",
"collapsedIconTapHint": "Expandir",
"remainingTextFieldCharacterCountOne": "Queda 1 carácter.",
"remainingTextFieldCharacterCountOther": "Quedan $remainingCount caracteres",
"refreshIndicatorSemanticLabel": "Actualizar"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_es_BO.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_es_BO.arb",
"repo_id": "flutter",
"token_count": 2321
} | 898 |
{
"remainingTextFieldCharacterCountFew": "Մնաց $remainingCount նիշ",
"remainingTextFieldCharacterCountMany": "Մնաց $remainingCount նիշ",
"scriptCategory": "English-like",
"timeOfDayFormat": "H:mm",
"selectedRowCountTitleFew": "Ընտրված է $selectedRowCount օբյեկտ",
"selectedRowCountTitleMany": "Ընտրված է $selectedRowCount օբյեկտ",
"openAppDrawerTooltip": "Բացել նավիգացիայի ընտրացանկը",
"backButtonTooltip": "Հետ",
"closeButtonTooltip": "Փակել",
"deleteButtonTooltip": "Ջնջել",
"nextMonthTooltip": "Հաջորդ ամիս",
"previousMonthTooltip": "Նախորդ ամիս",
"nextPageTooltip": "Հաջորդ էջ",
"previousPageTooltip": "Նախորդ էջ",
"firstPageTooltip": "Առաջին էջ",
"lastPageTooltip": "Վերջին էջ",
"showMenuTooltip": "Ցույց տալ ընտրացանկը",
"pageRowsInfoTitle": "$firstRow–$lastRow $rowCount-ից",
"pageRowsInfoTitleApproximate": "$firstRow–$lastRow մոտավորապես $rowCount-ից",
"rowsPerPageTitle": "Մեկ էջի տողերը՝",
"tabLabel": "Ներդիր $tabIndex՝ $tabCount-ից",
"aboutListTileTitle": "$applicationName հավելվածի մասին",
"licensesPageTitle": "Արտոնագրեր",
"selectedRowCountTitleZero": "Տողերը ընտրված չեն",
"selectedRowCountTitleOne": "Ընտրվել է 1 տարր",
"selectedRowCountTitleOther": "Ընտրվել է $selectedRowCount տարր",
"cancelButtonLabel": "Չեղարկել",
"closeButtonLabel": "Փակել",
"continueButtonLabel": "Շարունակել",
"copyButtonLabel": "Պատճենել",
"cutButtonLabel": "Կտրել",
"scanTextButtonLabel": "Սկանավորել տեքստ",
"okButtonLabel": "Եղավ",
"pasteButtonLabel": "Տեղադրել",
"selectAllButtonLabel": "Նշել բոլորը",
"viewLicensesButtonLabel": "Դիտել լիցենզիաները",
"anteMeridiemAbbreviation": "AM",
"postMeridiemAbbreviation": "PM",
"timePickerHourModeAnnouncement": "Ընտրեք ժամը",
"timePickerMinuteModeAnnouncement": "Ընտրեք րոպեները",
"signedInLabel": "Դուք մուտք եք գործել",
"hideAccountsLabel": "Թաքցնել հաշիվները",
"showAccountsLabel": "Ցույց տալ հաշիվները",
"modalBarrierDismissLabel": "Փակել",
"drawerLabel": "Նավիգացիայի ընտրացանկ",
"popupMenuLabel": "Ելնող ընտրացանկ",
"dialogLabel": "Երկխոսության պատուհան",
"alertDialogLabel": "Ծանուցում",
"searchFieldLabel": "Որոնել",
"reorderItemToStart": "Տեղափոխել սկիզբ",
"reorderItemToEnd": "Տեղափոխել վերջ",
"reorderItemUp": "Տեղափոխել վերև",
"reorderItemDown": "Տեղափոխել ներքև",
"reorderItemLeft": "Տեղափոխել ձախ",
"reorderItemRight": "Տեղափոխել աջ",
"expandedIconTapHint": "Ծալել",
"collapsedIconTapHint": "Ծավալել",
"remainingTextFieldCharacterCountZero": "Նիշի հնարավորություն չկա",
"remainingTextFieldCharacterCountOne": "Մնացել է 1 նիշ",
"remainingTextFieldCharacterCountOther": "Մնացել է $remainingCount նիշ",
"refreshIndicatorSemanticLabel": "Թարմացնել",
"moreButtonTooltip": "Այլ",
"dateSeparator": ".",
"dateHelpText": "օօ.աա.տտտտ",
"selectYearSemanticsLabel": "Ընտրել տարին",
"unspecifiedDate": "Ամսաթիվ",
"unspecifiedDateRange": "Ժամանակահատված",
"dateInputLabel": "Մուտքագրել ամսաթիվ",
"dateRangeStartLabel": "Մեկնարկի ամսաթիվը",
"dateRangeEndLabel": "Ավարտի ամսաթիվը",
"dateRangeStartDateSemanticLabel": "Մեկնարկի ամսաթիվը՝ $fullDate",
"dateRangeEndDateSemanticLabel": "Ավարտի ամսաթիվը՝ $fullDate",
"invalidDateFormatLabel": "Ձևաչափն անվավեր է։",
"invalidDateRangeLabel": "Ժամանակահատվածն անվավեր է:",
"dateOutOfRangeLabel": "Թույլատրելի ընդգրկույթից դուրս է։",
"saveButtonLabel": "Պահել",
"datePickerHelpText": "Ընտրեք ամսաթիվը",
"dateRangePickerHelpText": "Ընտրեք ժամանակահատվածը",
"calendarModeButtonLabel": "Անցնել օրացույցին",
"inputDateModeButtonLabel": "Անցնել ներածման ռեժիմին",
"timePickerDialHelpText": "Ընտրեք ժամը",
"timePickerInputHelpText": "Մուտքագրեք ժամը",
"timePickerHourLabel": "Ժամ",
"timePickerMinuteLabel": "Րոպե",
"invalidTimeLabel": "Մուտքագրեք վավեր ժամ",
"dialModeButtonLabel": "Անցնել թվերի ընտրման ռեժիմին",
"inputTimeModeButtonLabel": "Անցնել տեքստի մուտքագրման ռեժիմին",
"licensesPackageDetailTextZero": "No licenses",
"licensesPackageDetailTextOne": "1 լիցենզիա",
"licensesPackageDetailTextOther": "$licenseCount լիցենզիա",
"keyboardKeyAlt": "Alt",
"keyboardKeyAltGraph": "AltGr",
"keyboardKeyBackspace": "Backspace",
"keyboardKeyCapsLock": "Caps Lock",
"keyboardKeyChannelDown": "Հաջորդ ալիքը",
"keyboardKeyChannelUp": "Նախորդ ալիքը",
"keyboardKeyControl": "Ctrl",
"keyboardKeyDelete": "Del",
"keyboardKeyEject": "Eject",
"keyboardKeyEnd": "End",
"keyboardKeyEscape": "Esc",
"keyboardKeyFn": "Fn",
"keyboardKeyHome": "Home",
"keyboardKeyInsert": "Insert",
"keyboardKeyMeta": "Meta",
"keyboardKeyNumLock": "Num Lock",
"keyboardKeyNumpad1": "Num 1",
"keyboardKeyNumpad2": "Num 2",
"keyboardKeyNumpad3": "Num 3",
"keyboardKeyNumpad4": "Num 4",
"keyboardKeyNumpad5": "Num 5",
"keyboardKeyNumpad6": "Num 6",
"keyboardKeyNumpad7": "Num 7",
"keyboardKeyNumpad8": "Num 8",
"keyboardKeyNumpad9": "Num 9",
"keyboardKeyNumpad0": "Num 0",
"keyboardKeyNumpadAdd": "Num +",
"keyboardKeyNumpadComma": "Num ,",
"keyboardKeyNumpadDecimal": "Num .",
"keyboardKeyNumpadDivide": "Num /",
"keyboardKeyNumpadEnter": "Num Enter",
"keyboardKeyNumpadEqual": "Num =",
"keyboardKeyNumpadMultiply": "Num *",
"keyboardKeyNumpadParenLeft": "Num (",
"keyboardKeyNumpadParenRight": "Num )",
"keyboardKeyNumpadSubtract": "Num -",
"keyboardKeyPageDown": "PgDown",
"keyboardKeyPageUp": "PgUp",
"keyboardKeyPower": "Սնուցում",
"keyboardKeyPowerOff": "Անջատել",
"keyboardKeyPrintScreen": "Print Screen",
"keyboardKeyScrollLock": "Scroll Lock",
"keyboardKeySelect": "Ընտրել",
"keyboardKeySpace": "Բացատ",
"keyboardKeyMetaMacOs": "Command",
"keyboardKeyMetaWindows": "Win",
"menuBarMenuLabel": "Ընտրացանկի գոտու ընտրացանկ",
"currentDateLabel": "Այսօր",
"scrimLabel": "Դիմակ",
"bottomSheetLabel": "Ներքևի էկրան",
"scrimOnTapHint": "Փակել՝ $modalRouteContentName",
"keyboardKeyShift": "Shift",
"expansionTileExpandedHint": "կրկնակի հպեք ծալելու համար",
"expansionTileCollapsedHint": "կրկնակի հպեք ծավալելու համար",
"expansionTileExpandedTapHint": "Ծալել",
"expansionTileCollapsedTapHint": "ծավալեք՝ մանրամասները տեսնելու համար",
"expandedHint": "Ծալված է",
"collapsedHint": "Ծավալված է",
"menuDismissLabel": "Փակել ընտրացանկը",
"lookUpButtonLabel": "Փնտրել",
"searchWebButtonLabel": "Որոնել համացանցում",
"shareButtonLabel": "Կիսվել...",
"clearButtonTooltip": "Clear text",
"selectedDateLabel": "Selected"
}
| flutter/packages/flutter_localizations/lib/src/l10n/material_hy.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/material_hy.arb",
"repo_id": "flutter",
"token_count": 4505
} | 899 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.