Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- novelforge-project/flutter.tar.xzAdded+3
- novelforge-project/flutter/packages/flutter/coverage/lcov.base.infoAdded
- novelforge-project/flutter/packages/flutter/coverage/lcov.infoAdded
- novelforge-project/flutter/packages/flutter/lib/analysis_options.yamlAdded+6
- novelforge-project/flutter/packages/flutter/lib/animation.dartAdded+173
- novelforge-project/flutter/packages/flutter/lib/cupertino.dartAdded+73
- novelforge-project/flutter/packages/flutter/lib/foundation.dartAdded+49
- novelforge-project/flutter/packages/flutter/lib/gestures.dartAdded+35
- novelforge-project/flutter/packages/flutter/lib/material.dartAdded+196
- novelforge-project/flutter/packages/flutter/lib/painting.dartAdded+65
- novelforge-project/flutter/packages/flutter/lib/physics.dartAdded+17
- novelforge-project/flutter/packages/flutter/lib/rendering.dartAdded+78
- novelforge-project/flutter/packages/flutter/lib/scheduler.dartAdded+20
- novelforge-project/flutter/packages/flutter/lib/semantics.dartAdded+22
- novelforge-project/flutter/packages/flutter/lib/services.dartAdded+58
- novelforge-project/flutter/packages/flutter/lib/widgets.dartAdded+167
- novelforge-project/flutter/packages/flutter/test/_goldens_io.dartAdded+5
- novelforge-project/flutter/packages/flutter/test/_goldens_web.dartAdded+8
- novelforge-project/flutter/packages/flutter/test/analysis_options.yamlAdded+9
- novelforge-project/flutter/packages/flutter/test/animation/animation_controller_listener_test.dartAdded+52
- novelforge-project/flutter/packages/flutter/test/animation/animation_controller_test.dartAdded+1106
- novelforge-project/flutter/packages/flutter/test/animation/animation_from_listener_test.dartAdded+83
- novelforge-project/flutter/packages/flutter/test/animation/animation_sheet_test.dartAdded+185
- novelforge-project/flutter/packages/flutter/test/animation/animation_style_test.dartAdded+92
- novelforge-project/flutter/packages/flutter/test/animation/animations_test.dartAdded+501
- novelforge-project/flutter/packages/flutter/test/animation/curves_test.dartAdded+616
- novelforge-project/flutter/packages/flutter/test/animation/futures_test.dartAdded+189
- novelforge-project/flutter/packages/flutter/test/animation/iteration_patterns_test.dartAdded+129
- novelforge-project/flutter/packages/flutter/test/animation/listener_helpers_test.dartAdded+54
- novelforge-project/flutter/packages/flutter/test/animation/live_binding_test.dartAdded+140
- novelforge-project/flutter/packages/flutter/test/animation/tween_test.dartAdded+222
- novelforge-project/flutter/packages/flutter/test/cupertino/action_sheet_test.dartAdded+1144
- novelforge-project/flutter/packages/flutter/test/cupertino/activity_indicator_test.dartAdded+195
- novelforge-project/flutter/packages/flutter/test/cupertino/adaptive_text_selection_toolbar_test.dartAdded+282
- novelforge-project/flutter/packages/flutter/test/cupertino/app_test.dartAdded+556
- novelforge-project/flutter/packages/flutter/test/cupertino/bottom_tab_bar_test.dartAdded+661
- novelforge-project/flutter/packages/flutter/test/cupertino/button_test.dartAdded+496
- novelforge-project/flutter/packages/flutter/test/cupertino/checkbox_test.dartAdded+413
- novelforge-project/flutter/packages/flutter/test/cupertino/colors_test.dartAdded+599
- novelforge-project/flutter/packages/flutter/test/cupertino/context_menu_action_test.dartAdded+168
- novelforge-project/flutter/packages/flutter/test/cupertino/context_menu_test.dartAdded+889
- novelforge-project/flutter/packages/flutter/test/cupertino/date_picker_test.dartAdded+1982
- novelforge-project/flutter/packages/flutter/test/cupertino/debug_test.dartAdded+32
- novelforge-project/flutter/packages/flutter/test/cupertino/desktop_text_selection_toolbar_button_test.dartAdded+133
- novelforge-project/flutter/packages/flutter/test/cupertino/desktop_text_selection_toolbar_test.dartAdded+146
- novelforge-project/flutter/packages/flutter/test/cupertino/dialog_test.dartAdded+1644
- novelforge-project/flutter/packages/flutter/test/cupertino/form_row_test.dartAdded+208
- novelforge-project/flutter/packages/flutter/test/cupertino/form_section_test.dartAdded+223
- novelforge-project/flutter/packages/flutter/test/cupertino/icon_theme_data_test.dartAdded+47
- novelforge-project/flutter/packages/flutter/test/cupertino/list_section_test.dartAdded+265
123version https://git-lfs.github.com/spec/v1oid sha256:07319621db51f3d9a4ec6da903190efb147cd7f4994b2fc333a5a42c2d774879size 134123456include: ../analysis_options.yaml
linter: rules: # diagnostic_describe_all_properties: true # blocked on https://github.com/dart-lang/sdk/issues/47418 prefer_relative_imports: false # doesn't really work when you have subpackages like we do here123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173// 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.
/// The Flutter animation system.////// To use, import `package:flutter/animation.dart`.////// This library provides basic building blocks for implementing animations in/// Flutter. Other layers of the framework use these building blocks to provide/// advanced animation support for applications. For example, the widget library/// includes [ImplicitlyAnimatedWidget]s and [AnimatedWidget]s that make it easy/// to animate certain properties of a [Widget]. If those animated widgets are/// not sufficient for a given use case, the basic building blocks provided by/// this library can be used to implement custom animated effects.////// This library depends only on core Dart libraries and the `physics.dart`/// library.///////// ### Foundations: the Animation class////// Flutter represents an animation as a value that changes over a given/// duration, and that value may be of any type. For example, it could be a/// [double] indicating the current opacity of a [Widget] as it fades out. Or,/// it could be the current background [Color] of a widget that transitions/// smoothly from one color to another. The current value of an animation is/// represented by an [Animation] object, which is the central class of the/// animation library. In addition to the current animation value, the/// [Animation] object also stores the current [AnimationStatus]. The status/// indicates whether the animation is currently conceptually running from the/// beginning to the end or the other way around. It may also indicate that the/// animation is currently stopped at the beginning or the end.////// Other objects can register listeners on an [Animation] to be informed/// whenever the animation value and/or the animation status changes. A [Widget]/// may register such a *value* listener via [Animation.addListener] to rebuild/// itself with the current animation value whenever that value changes. For/// example, a widget might listen to an animation to update its opacity to the/// animation's value every time that value changes. Likewise, registering a/// *status* listener via [Animation.addStatusListener] may be useful to trigger/// another action when the current animation has ended.////// As an example, the following video shows the changes over time in the/// current animation status and animation value for the opacity animation of a/// widget. This [Animation] is driven by an [AnimationController] (see next/// section). Before the animation triggers, the animation status is "dismissed"/// and the value is 0.0. As the value runs from 0.0 to 1.0 to fade in the/// widget, the status changes to "forward". When the widget is fully faded in/// at an animation value of 1.0 the status is "completed". When the animation/// triggers again to fade the widget back out, the animation status changes to/// "reverse" and the animation value runs back to 0.0. At that point the widget/// is fully faded out and the animation status switches back to "dismissed"/// until the animation is triggered again.////// {@animation 420 100 https://flutter.github.io/assets-for-api-docs/assets/animation/animation_status_value.mp4}////// Although you can't instantiate [Animation] directly (it is an abstract/// class), you can create one using an [AnimationController].///////// ### Powering animations: AnimationController////// An [AnimationController] is a special kind of [Animation] that advances its/// animation value whenever the device running the application is ready to/// display a new frame (typically, this rate is around 60 values per second)./// An [AnimationController] can be used wherever an [Animation] is expected. As/// the name implies, an [AnimationController] also provides control over its/// [Animation]: It implements methods to stop the animation at any time and to/// run it forward as well as in the reverse direction.////// By default, an [AnimationController] increases its animation value linearly/// over the given duration from 0.0 to 1.0 when run in the forward direction./// For many use cases you might want the value to be of a different type,/// change the range of the animation values, or change how the animation moves/// between values. This is achieved by wrapping the animation: Wrapping it in/// an [Animatable] (see below) changes the range of animation values to a/// different range or type (for example to animate [Color]s or [Rect]s)./// Furthermore, a [Curve] can be applied to the animation by wrapping it in a/// [CurvedAnimation]. Instead of linearly increasing the animation value, a/// curved animation changes its value according to the provided curve. The/// framework ships with many built-in curves (see [Curves]). As an example,/// [Curves.easeOutCubic] increases the animation value quickly at the beginning/// of the animation and then slows down until the target value is reached:////// {@animation 464 192 https://flutter.github.io/assets-for-api-docs/assets/animation/curve_ease_out_cubic.mp4}///////// ### Animating different types: Animatable////// An `Animatable<T>` is an object that takes an `Animation<double>` as input/// and produces a value of type `T`. Objects of these types can be used to/// translate the animation value range of an [AnimationController] (or any/// other [Animation] of type [double]) to a different range. That new range/// doesn't even have to be of type double anymore. With the help of an/// [Animatable] like a [Tween] or a [TweenSequence] (see sections below) an/// [AnimationController] can be used to smoothly transition [Color]s, [Rect]s,/// [Size]s and many more types from one value to another over a given duration.///////// ### Interpolating values: Tweens////// A [Tween] is applied to an [Animation] of type [double] to change the/// range and type of the animation value. For example, to transition the/// background of a [Widget] smoothly between two [Color]s, a [ColorTween] can/// be used. Each [Tween] specifies a start and an end value. As the animation/// value of the [Animation] powering the [Tween] progresses from 0.0 to 1.0 it/// produces interpolated values between its start and end value. The values/// produced by the [Tween] usually move closer and closer to its end value as/// the animation value of the powering [Animation] approaches 1.0.////// The following video shows example values produced by an [IntTween], a/// `Tween<double>`, and a [ColorTween] as the animation value runs from 0.0 to/// 1.0 and back to 0.0:////// {@animation 530 150 https://flutter.github.io/assets-for-api-docs/assets/animation/tweens.mp4}////// An [Animation] or [AnimationController] can power multiple [Tween]s. For/// example, to animate the size and the color of a widget in parallel, create/// one [AnimationController] that powers a [SizeTween] and a [ColorTween].////// The framework ships with many [Tween] subclasses ([IntTween], [SizeTween],/// [RectTween], etc.) to animate common properties.///////// ### Staggered animations: TweenSequences////// A [TweenSequence] can help animate a given property smoothly in stages. Each/// [Tween] in the sequence is responsible for a different stage and has an/// associated weight. When the animation runs, the stages execute one after/// another. For example, let's say you want to animate the background of a/// widget from yellow to green and then, after a short pause, to red. For this/// you can specify three tweens within a tween sequence: One [ColorTween]/// animating from yellow to green, one [ConstantTween] that just holds the color/// green, and another [ColorTween] animating from green to red. For each/// tween you need to pick a weight indicating the ratio of time spent on that/// tween compared to all other tweens. If we assign a weight of 2 to both of/// the [ColorTween]s and a weight of 1 to the [ConstantTween] the transition/// described by the [ColorTween]s would take twice as long as the/// [ConstantTween]. A [TweenSequence] is driven by an [Animation] just like a/// regular [Tween]: As the powering [Animation] runs from 0.0 to 1.0 the/// [TweenSequence] runs through all of its stages.////// The following video shows the animation described in the previous paragraph:////// {@animation 646 250 https://flutter.github.io/assets-for-api-docs/assets/animation/tween_sequence.mp4}///////// See also:////// * [Introduction to animations](https://flutter.dev/docs/development/ui/animations)/// on flutter.dev./// * [Animations tutorial](https://flutter.dev/docs/development/ui/animations/tutorial)/// on flutter.dev./// * [Sample app](https://github.com/flutter/samples/tree/master/animations),/// which showcases Flutter's animation features./// * [ImplicitlyAnimatedWidget] and its subclasses, which are [Widget]s that/// implicitly animate changes to their properties./// * [AnimatedWidget] and its subclasses, which are [Widget]s that take an/// explicit [Animation] to animate their properties.library animation;
// AnimationController can throw TickerCanceledexport 'package:flutter/scheduler.dart' show TickerCanceled;
export 'src/animation/animation.dart';export 'src/animation/animation_controller.dart';export 'src/animation/animation_style.dart';export 'src/animation/animations.dart';export 'src/animation/curves.dart';export 'src/animation/listener_helpers.dart';export 'src/animation/tween.dart';export 'src/animation/tween_sequence.dart';12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273// 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.
/// Flutter widgets implementing the current iOS design language.////// To use, import `package:flutter/cupertino.dart`.////// This library is designed for apps that run on iOS. For apps that may also/// run on other operating systems, we encourage use of other widgets, for/// example the [Material/// Design](https://flutter.dev/docs/development/ui/widgets/material) set.////// {@youtube 560 315 https://www.youtube.com/watch?v=3PdUaidHc-E}////// See also:////// * [flutter.dev/widgets/cupertino](https://flutter.dev/docs/development/ui/widgets/cupertino)/// for a catalog of all Cupertino widgets./// * [flutter.dev/widgets](https://flutter.dev/widgets/)/// for a catalog of commonly-used Flutter widgets.
library cupertino;
export 'src/cupertino/activity_indicator.dart';export 'src/cupertino/adaptive_text_selection_toolbar.dart';export 'src/cupertino/app.dart';export 'src/cupertino/bottom_tab_bar.dart';export 'src/cupertino/button.dart';export 'src/cupertino/checkbox.dart';export 'src/cupertino/colors.dart';export 'src/cupertino/constants.dart';export 'src/cupertino/context_menu.dart';export 'src/cupertino/context_menu_action.dart';export 'src/cupertino/date_picker.dart';export 'src/cupertino/debug.dart';export 'src/cupertino/desktop_text_selection.dart';export 'src/cupertino/desktop_text_selection_toolbar.dart';export 'src/cupertino/desktop_text_selection_toolbar_button.dart';export 'src/cupertino/dialog.dart';export 'src/cupertino/form_row.dart';export 'src/cupertino/form_section.dart';export 'src/cupertino/icon_theme_data.dart';export 'src/cupertino/icons.dart';export 'src/cupertino/interface_level.dart';export 'src/cupertino/list_section.dart';export 'src/cupertino/list_tile.dart';export 'src/cupertino/localizations.dart';export 'src/cupertino/magnifier.dart';export 'src/cupertino/nav_bar.dart';export 'src/cupertino/page_scaffold.dart';export 'src/cupertino/picker.dart';export 'src/cupertino/radio.dart';export 'src/cupertino/refresh.dart';export 'src/cupertino/route.dart';export 'src/cupertino/scrollbar.dart';export 'src/cupertino/search_field.dart';export 'src/cupertino/segmented_control.dart';export 'src/cupertino/slider.dart';export 'src/cupertino/sliding_segmented_control.dart';export 'src/cupertino/spell_check_suggestions_toolbar.dart';export 'src/cupertino/switch.dart';export 'src/cupertino/tab_scaffold.dart';export 'src/cupertino/tab_view.dart';export 'src/cupertino/text_field.dart';export 'src/cupertino/text_form_field_row.dart';export 'src/cupertino/text_selection.dart';export 'src/cupertino/text_selection_toolbar.dart';export 'src/cupertino/text_selection_toolbar_button.dart';export 'src/cupertino/text_theme.dart';export 'src/cupertino/theme.dart';export 'src/cupertino/thumb_painter.dart';export 'widgets.dart';12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849// 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.
/// Core Flutter framework primitives.////// The features defined in this library are the lowest-level utility/// classes and functions used by all the other layers of the Flutter/// framework.library foundation;
export 'package:meta/meta.dart' show factory, immutable, mustCallSuper, nonVirtual, optionalTypeArgs, protected, required, visibleForTesting;
export 'src/foundation/annotations.dart';export 'src/foundation/assertions.dart';export 'src/foundation/basic_types.dart';export 'src/foundation/binding.dart';export 'src/foundation/bitfield.dart';export 'src/foundation/capabilities.dart';export 'src/foundation/change_notifier.dart';export 'src/foundation/collections.dart';export 'src/foundation/consolidate_response.dart';export 'src/foundation/constants.dart';export 'src/foundation/debug.dart';export 'src/foundation/diagnostics.dart';export 'src/foundation/isolates.dart';export 'src/foundation/key.dart';export 'src/foundation/licenses.dart';export 'src/foundation/memory_allocations.dart';export 'src/foundation/node.dart';export 'src/foundation/object.dart';export 'src/foundation/observer_list.dart';export 'src/foundation/persistent_hash_map.dart';export 'src/foundation/platform.dart';export 'src/foundation/print.dart';export 'src/foundation/serialization.dart';export 'src/foundation/service_extensions.dart';export 'src/foundation/stack_frame.dart';export 'src/foundation/synchronous_future.dart';export 'src/foundation/timeline.dart';export 'src/foundation/unicode.dart';1234567891011121314151617181920212223242526272829303132333435// 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.
/// The Flutter gesture recognizers.////// To use, import `package:flutter/gestures.dart`.library gestures;
export 'src/gestures/arena.dart';export 'src/gestures/binding.dart';export 'src/gestures/constants.dart';export 'src/gestures/converter.dart';export 'src/gestures/debug.dart';export 'src/gestures/drag.dart';export 'src/gestures/drag_details.dart';export 'src/gestures/eager.dart';export 'src/gestures/events.dart';export 'src/gestures/force_press.dart';export 'src/gestures/gesture_settings.dart';export 'src/gestures/hit_test.dart';export 'src/gestures/long_press.dart';export 'src/gestures/lsq_solver.dart';export 'src/gestures/monodrag.dart';export 'src/gestures/multidrag.dart';export 'src/gestures/multitap.dart';export 'src/gestures/pointer_router.dart';export 'src/gestures/pointer_signal_resolver.dart';export 'src/gestures/recognizer.dart';export 'src/gestures/resampler.dart';export 'src/gestures/scale.dart';export 'src/gestures/tap.dart';export 'src/gestures/tap_and_drag.dart';export 'src/gestures/team.dart';export 'src/gestures/velocity_tracker.dart';123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196// 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.
/// Flutter widgets implementing Material Design.////// To use, import `package:flutter/material.dart`.////// {@youtube 560 315 https://www.youtube.com/watch?v=DL0Ix1lnC4w}////// See also:////// * [docs.flutter.dev/ui/widgets/material](https://docs.flutter.dev/ui/widgets/material)/// for a catalog of commonly-used Material component widgets./// * [m3.material.io](https://m3.material.io/) for the Material 3 specification/// * [m2.material.io](https://m2.material.io/) for the Material 2 specificationlibrary material;
export 'src/material/about.dart';export 'src/material/action_buttons.dart';export 'src/material/action_chip.dart';export 'src/material/action_icons_theme.dart';export 'src/material/adaptive_text_selection_toolbar.dart';export 'src/material/animated_icons.dart';export 'src/material/app.dart';export 'src/material/app_bar.dart';export 'src/material/app_bar_theme.dart';export 'src/material/arc.dart';export 'src/material/autocomplete.dart';export 'src/material/badge.dart';export 'src/material/badge_theme.dart';export 'src/material/banner.dart';export 'src/material/banner_theme.dart';export 'src/material/bottom_app_bar.dart';export 'src/material/bottom_app_bar_theme.dart';export 'src/material/bottom_navigation_bar.dart';export 'src/material/bottom_navigation_bar_theme.dart';export 'src/material/bottom_sheet.dart';export 'src/material/bottom_sheet_theme.dart';export 'src/material/button.dart';export 'src/material/button_bar.dart';export 'src/material/button_bar_theme.dart';export 'src/material/button_style.dart';export 'src/material/button_style_button.dart';export 'src/material/button_theme.dart';export 'src/material/calendar_date_picker.dart';export 'src/material/card.dart';export 'src/material/card_theme.dart';export 'src/material/checkbox.dart';export 'src/material/checkbox_list_tile.dart';export 'src/material/checkbox_theme.dart';export 'src/material/chip.dart';export 'src/material/chip_theme.dart';export 'src/material/choice_chip.dart';export 'src/material/circle_avatar.dart';export 'src/material/color_scheme.dart';export 'src/material/colors.dart';export 'src/material/constants.dart';export 'src/material/curves.dart';export 'src/material/data_table.dart';export 'src/material/data_table_source.dart';export 'src/material/data_table_theme.dart';export 'src/material/date.dart';export 'src/material/date_picker.dart';export 'src/material/date_picker_theme.dart';export 'src/material/debug.dart';export 'src/material/desktop_text_selection.dart';export 'src/material/desktop_text_selection_toolbar.dart';export 'src/material/desktop_text_selection_toolbar_button.dart';export 'src/material/dialog.dart';export 'src/material/dialog_theme.dart';export 'src/material/divider.dart';export 'src/material/divider_theme.dart';export 'src/material/drawer.dart';export 'src/material/drawer_header.dart';export 'src/material/drawer_theme.dart';export 'src/material/dropdown.dart';export 'src/material/dropdown_menu.dart';export 'src/material/dropdown_menu_theme.dart';export 'src/material/elevated_button.dart';export 'src/material/elevated_button_theme.dart';export 'src/material/elevation_overlay.dart';export 'src/material/expand_icon.dart';export 'src/material/expansion_panel.dart';export 'src/material/expansion_tile.dart';export 'src/material/expansion_tile_theme.dart';export 'src/material/feedback.dart';export 'src/material/filled_button.dart';export 'src/material/filled_button_theme.dart';export 'src/material/filter_chip.dart';export 'src/material/flexible_space_bar.dart';export 'src/material/floating_action_button.dart';export 'src/material/floating_action_button_location.dart';export 'src/material/floating_action_button_theme.dart';export 'src/material/flutter_logo.dart';export 'src/material/grid_tile.dart';export 'src/material/grid_tile_bar.dart';export 'src/material/icon_button.dart';export 'src/material/icon_button_theme.dart';export 'src/material/icons.dart';export 'src/material/ink_decoration.dart';export 'src/material/ink_highlight.dart';export 'src/material/ink_ripple.dart';export 'src/material/ink_sparkle.dart';export 'src/material/ink_splash.dart';export 'src/material/ink_well.dart';export 'src/material/input_border.dart';export 'src/material/input_chip.dart';export 'src/material/input_date_picker_form_field.dart';export 'src/material/input_decorator.dart';export 'src/material/list_tile.dart';export 'src/material/list_tile_theme.dart';export 'src/material/magnifier.dart';export 'src/material/material.dart';export 'src/material/material_button.dart';export 'src/material/material_localizations.dart';export 'src/material/material_state.dart';export 'src/material/material_state_mixin.dart';export 'src/material/menu_anchor.dart';export 'src/material/menu_bar_theme.dart';export 'src/material/menu_button_theme.dart';export 'src/material/menu_style.dart';export 'src/material/menu_theme.dart';export 'src/material/mergeable_material.dart';export 'src/material/motion.dart';export 'src/material/navigation_bar.dart';export 'src/material/navigation_bar_theme.dart';export 'src/material/navigation_drawer.dart';export 'src/material/navigation_drawer_theme.dart';export 'src/material/navigation_rail.dart';export 'src/material/navigation_rail_theme.dart';export 'src/material/no_splash.dart';export 'src/material/outlined_button.dart';export 'src/material/outlined_button_theme.dart';export 'src/material/page.dart';export 'src/material/page_transitions_theme.dart';export 'src/material/paginated_data_table.dart';export 'src/material/popup_menu.dart';export 'src/material/popup_menu_theme.dart';export 'src/material/progress_indicator.dart';export 'src/material/progress_indicator_theme.dart';export 'src/material/radio.dart';export 'src/material/radio_list_tile.dart';export 'src/material/radio_theme.dart';export 'src/material/range_slider.dart';export 'src/material/refresh_indicator.dart';export 'src/material/reorderable_list.dart';export 'src/material/scaffold.dart';export 'src/material/scrollbar.dart';export 'src/material/scrollbar_theme.dart';export 'src/material/search.dart';export 'src/material/search_anchor.dart';export 'src/material/search_bar_theme.dart';export 'src/material/search_view_theme.dart';export 'src/material/segmented_button.dart';export 'src/material/segmented_button_theme.dart';export 'src/material/selectable_text.dart';export 'src/material/selection_area.dart';export 'src/material/shadows.dart';export 'src/material/slider.dart';export 'src/material/slider_theme.dart';export 'src/material/snack_bar.dart';export 'src/material/snack_bar_theme.dart';export 'src/material/spell_check_suggestions_toolbar.dart';export 'src/material/spell_check_suggestions_toolbar_layout_delegate.dart';export 'src/material/stepper.dart';export 'src/material/switch.dart';export 'src/material/switch_list_tile.dart';export 'src/material/switch_theme.dart';export 'src/material/tab_bar_theme.dart';export 'src/material/tab_controller.dart';export 'src/material/tab_indicator.dart';export 'src/material/tabs.dart';export 'src/material/text_button.dart';export 'src/material/text_button_theme.dart';export 'src/material/text_field.dart';export 'src/material/text_form_field.dart';export 'src/material/text_selection.dart';export 'src/material/text_selection_theme.dart';export 'src/material/text_selection_toolbar.dart';export 'src/material/text_selection_toolbar_text_button.dart';export 'src/material/text_theme.dart';export 'src/material/theme.dart';export 'src/material/theme_data.dart';export 'src/material/time.dart';export 'src/material/time_picker.dart';export 'src/material/time_picker_theme.dart';export 'src/material/toggle_buttons.dart';export 'src/material/toggle_buttons_theme.dart';export 'src/material/toggleable.dart';export 'src/material/tooltip.dart';export 'src/material/tooltip_theme.dart';export 'src/material/tooltip_visibility.dart';export 'src/material/typography.dart';export 'src/material/user_accounts_drawer_header.dart';export 'widgets.dart';1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465// 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.
/// The Flutter painting library.////// To use, import `package:flutter/painting.dart`.////// This library includes a variety of classes that wrap the Flutter/// engine's painting API for more specialized purposes, such as painting scaled/// images, interpolating between shadows, painting borders around boxes, etc.////// In particular:////// * Use the [TextPainter] class for painting text./// * Use [Decoration] (and more concretely [BoxDecoration]) for/// painting boxes.library painting;
export 'dart:ui' show PlaceholderAlignment, Shadow, TextHeightBehavior, TextLeadingDistribution;
export 'src/painting/alignment.dart';export 'src/painting/basic_types.dart';export 'src/painting/beveled_rectangle_border.dart';export 'src/painting/binding.dart';export 'src/painting/border_radius.dart';export 'src/painting/borders.dart';export 'src/painting/box_border.dart';export 'src/painting/box_decoration.dart';export 'src/painting/box_fit.dart';export 'src/painting/box_shadow.dart';export 'src/painting/circle_border.dart';export 'src/painting/clip.dart';export 'src/painting/colors.dart';export 'src/painting/continuous_rectangle_border.dart';export 'src/painting/debug.dart';export 'src/painting/decoration.dart';export 'src/painting/decoration_image.dart';export 'src/painting/edge_insets.dart';export 'src/painting/flutter_logo.dart';export 'src/painting/fractional_offset.dart';export 'src/painting/geometry.dart';export 'src/painting/gradient.dart';export 'src/painting/image_cache.dart';export 'src/painting/image_decoder.dart';export 'src/painting/image_provider.dart';export 'src/painting/image_resolution.dart';export 'src/painting/image_stream.dart';export 'src/painting/inline_span.dart';export 'src/painting/linear_border.dart';export 'src/painting/matrix_utils.dart';export 'src/painting/notched_shapes.dart';export 'src/painting/oval_border.dart';export 'src/painting/paint_utilities.dart';export 'src/painting/placeholder_span.dart';export 'src/painting/rounded_rectangle_border.dart';export 'src/painting/shader_warm_up.dart';export 'src/painting/shape_decoration.dart';export 'src/painting/stadium_border.dart';export 'src/painting/star_border.dart';export 'src/painting/strut_style.dart';export 'src/painting/text_painter.dart';export 'src/painting/text_scaler.dart';export 'src/painting/text_span.dart';export 'src/painting/text_style.dart';1234567891011121314151617// 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.
/// Simple one-dimensional physics simulations, such as springs, friction, and/// gravity, for use in user interface animations.////// To use, import `package:flutter/physics.dart`.library physics;
export 'src/physics/clamped_simulation.dart';export 'src/physics/friction_simulation.dart';export 'src/physics/gravity_simulation.dart';export 'src/physics/simulation.dart';export 'src/physics/spring_simulation.dart';export 'src/physics/tolerance.dart';export 'src/physics/utils.dart';123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778// 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.
/// The Flutter rendering tree.////// To use, import `package:flutter/rendering.dart`.////// The [RenderObject] hierarchy is used by the Flutter Widgets library to/// implement its layout and painting back-end. Generally, while you may use/// custom [RenderBox] classes for specific effects in your applications, most/// of the time your only interaction with the [RenderObject] hierarchy will be/// in debugging layout issues.////// If you are developing your own library or application directly on top of the/// rendering library, then you will want to have a binding (see [BindingBase])./// You can use [RenderingFlutterBinding], or you can create your own binding./// If you create your own binding, it needs to import at least/// [ServicesBinding], [GestureBinding], [SchedulerBinding], [PaintingBinding],/// and [RendererBinding]. The rendering library does not automatically create a/// binding, but relies on one being initialized with those features.library rendering;
export 'package:flutter/foundation.dart' show DiagnosticLevel, ValueChanged, ValueGetter, ValueSetter, VoidCallback;export 'package:flutter/semantics.dart';export 'package:vector_math/vector_math_64.dart' show Matrix4;
export 'src/rendering/animated_size.dart';export 'src/rendering/binding.dart';export 'src/rendering/box.dart';export 'src/rendering/custom_layout.dart';export 'src/rendering/custom_paint.dart';export 'src/rendering/debug.dart';export 'src/rendering/debug_overflow_indicator.dart';export 'src/rendering/decorated_sliver.dart';export 'src/rendering/editable.dart';export 'src/rendering/error.dart';export 'src/rendering/flex.dart';export 'src/rendering/flow.dart';export 'src/rendering/image.dart';export 'src/rendering/layer.dart';export 'src/rendering/layout_helper.dart';export 'src/rendering/list_body.dart';export 'src/rendering/list_wheel_viewport.dart';export 'src/rendering/mouse_tracker.dart';export 'src/rendering/object.dart';export 'src/rendering/paragraph.dart';export 'src/rendering/performance_overlay.dart';export 'src/rendering/platform_view.dart';export 'src/rendering/proxy_box.dart';export 'src/rendering/proxy_sliver.dart';export 'src/rendering/rotated_box.dart';export 'src/rendering/selection.dart';export 'src/rendering/service_extensions.dart';export 'src/rendering/shifted_box.dart';export 'src/rendering/sliver.dart';export 'src/rendering/sliver_fill.dart';export 'src/rendering/sliver_fixed_extent_list.dart';export 'src/rendering/sliver_grid.dart';export 'src/rendering/sliver_group.dart';export 'src/rendering/sliver_list.dart';export 'src/rendering/sliver_multi_box_adaptor.dart';export 'src/rendering/sliver_padding.dart';export 'src/rendering/sliver_persistent_header.dart';export 'src/rendering/stack.dart';export 'src/rendering/table.dart';export 'src/rendering/table_border.dart';export 'src/rendering/texture.dart';export 'src/rendering/tweens.dart';export 'src/rendering/view.dart';export 'src/rendering/viewport.dart';export 'src/rendering/viewport_offset.dart';export 'src/rendering/wrap.dart';1234567891011121314151617181920// 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.
/// The Flutter Scheduler library.////// To use, import `package:flutter/scheduler.dart`.////// This library is responsible for scheduler frame callbacks, and tasks at/// given priorities.////// The library makes sure that tasks are only run when appropriate./// For example, an idle-task is only executed when no animation is running.library scheduler;
export 'src/scheduler/binding.dart';export 'src/scheduler/debug.dart';export 'src/scheduler/priority.dart';export 'src/scheduler/service_extensions.dart';export 'src/scheduler/ticker.dart';12345678910111213141516171819202122// 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.
/// The Flutter semantics package.////// To use, import `package:flutter/semantics.dart`.////// The [SemanticsEvent] classes define the protocol for sending semantic events/// to the platform.////// The [SemanticsNode] hierarchy represents the semantic structure of the UI/// and is used by the platform-specific accessibility services.library semantics;
export 'dart:ui' show LocaleStringAttribute, SpellOutStringAttribute;
export 'src/semantics/binding.dart';export 'src/semantics/debug.dart';export 'src/semantics/semantics.dart';export 'src/semantics/semantics_event.dart';export 'src/semantics/semantics_service.dart';12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758// 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.
/// Platform services exposed to Flutter apps.////// To use, import `package:flutter/services.dart`.////// This library depends only on core Dart libraries and the `foundation`/// library.library services;
export 'src/services/asset_bundle.dart';export 'src/services/asset_manifest.dart';export 'src/services/autofill.dart';export 'src/services/binary_messenger.dart';export 'src/services/binding.dart';export 'src/services/browser_context_menu.dart';export 'src/services/clipboard.dart';export 'src/services/debug.dart';export 'src/services/deferred_component.dart';export 'src/services/flavor.dart';export 'src/services/font_loader.dart';export 'src/services/haptic_feedback.dart';export 'src/services/hardware_keyboard.dart';export 'src/services/keyboard_inserted_content.dart';export 'src/services/keyboard_key.g.dart';export 'src/services/keyboard_maps.g.dart';export 'src/services/live_text.dart';export 'src/services/message_codec.dart';export 'src/services/message_codecs.dart';export 'src/services/mouse_cursor.dart';export 'src/services/mouse_tracking.dart';export 'src/services/platform_channel.dart';export 'src/services/platform_views.dart';export 'src/services/process_text.dart';export 'src/services/raw_keyboard.dart';export 'src/services/raw_keyboard_android.dart';export 'src/services/raw_keyboard_fuchsia.dart';export 'src/services/raw_keyboard_ios.dart';export 'src/services/raw_keyboard_linux.dart';export 'src/services/raw_keyboard_macos.dart';export 'src/services/raw_keyboard_web.dart';export 'src/services/raw_keyboard_windows.dart';export 'src/services/restoration.dart';export 'src/services/service_extensions.dart';export 'src/services/spell_check.dart';export 'src/services/system_channels.dart';export 'src/services/system_chrome.dart';export 'src/services/system_navigator.dart';export 'src/services/system_sound.dart';export 'src/services/text_boundary.dart';export 'src/services/text_editing.dart';export 'src/services/text_editing_delta.dart';export 'src/services/text_formatter.dart';export 'src/services/text_input.dart';export 'src/services/text_layout_metrics.dart';export 'src/services/undo_manager.dart';123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167// 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.
/// The Flutter widgets framework.////// To use, import `package:flutter/widgets.dart`.////// See also:////// * [flutter.dev/widgets](https://flutter.dev/widgets/)/// for a catalog of commonly-used Flutter widgets.library widgets;
export 'package:characters/characters.dart';export 'package:vector_math/vector_math_64.dart' show Matrix4;
export 'foundation.dart' show UniqueKey;export 'rendering.dart' show TextSelectionHandleType;export 'src/widgets/actions.dart';export 'src/widgets/adapter.dart';export 'src/widgets/animated_cross_fade.dart';export 'src/widgets/animated_scroll_view.dart';export 'src/widgets/animated_size.dart';export 'src/widgets/animated_switcher.dart';export 'src/widgets/annotated_region.dart';export 'src/widgets/app.dart';export 'src/widgets/app_lifecycle_listener.dart';export 'src/widgets/async.dart';export 'src/widgets/autocomplete.dart';export 'src/widgets/autofill.dart';export 'src/widgets/automatic_keep_alive.dart';export 'src/widgets/banner.dart';export 'src/widgets/basic.dart';export 'src/widgets/binding.dart';export 'src/widgets/bottom_navigation_bar_item.dart';export 'src/widgets/color_filter.dart';export 'src/widgets/container.dart';export 'src/widgets/context_menu_button_item.dart';export 'src/widgets/context_menu_controller.dart';export 'src/widgets/debug.dart';export 'src/widgets/decorated_sliver.dart';export 'src/widgets/default_selection_style.dart';export 'src/widgets/default_text_editing_shortcuts.dart';export 'src/widgets/desktop_text_selection_toolbar_layout_delegate.dart';export 'src/widgets/dismissible.dart';export 'src/widgets/display_feature_sub_screen.dart';export 'src/widgets/disposable_build_context.dart';export 'src/widgets/drag_target.dart';export 'src/widgets/draggable_scrollable_sheet.dart';export 'src/widgets/dual_transition_builder.dart';export 'src/widgets/editable_text.dart';export 'src/widgets/fade_in_image.dart';export 'src/widgets/focus_manager.dart';export 'src/widgets/focus_scope.dart';export 'src/widgets/focus_traversal.dart';export 'src/widgets/form.dart';export 'src/widgets/framework.dart';export 'src/widgets/gesture_detector.dart';export 'src/widgets/grid_paper.dart';export 'src/widgets/heroes.dart';export 'src/widgets/icon.dart';export 'src/widgets/icon_data.dart';export 'src/widgets/icon_theme.dart';export 'src/widgets/icon_theme_data.dart';export 'src/widgets/image.dart';export 'src/widgets/image_filter.dart';export 'src/widgets/image_icon.dart';export 'src/widgets/implicit_animations.dart';export 'src/widgets/inherited_model.dart';export 'src/widgets/inherited_notifier.dart';export 'src/widgets/inherited_theme.dart';export 'src/widgets/interactive_viewer.dart';export 'src/widgets/keyboard_listener.dart';export 'src/widgets/layout_builder.dart';export 'src/widgets/list_wheel_scroll_view.dart';export 'src/widgets/localizations.dart';export 'src/widgets/lookup_boundary.dart';export 'src/widgets/magnifier.dart';export 'src/widgets/media_query.dart';export 'src/widgets/modal_barrier.dart';export 'src/widgets/navigation_toolbar.dart';export 'src/widgets/navigator.dart';export 'src/widgets/navigator_pop_handler.dart';export 'src/widgets/nested_scroll_view.dart';export 'src/widgets/notification_listener.dart';export 'src/widgets/orientation_builder.dart';export 'src/widgets/overflow_bar.dart';export 'src/widgets/overlay.dart';export 'src/widgets/overscroll_indicator.dart';export 'src/widgets/page_storage.dart';export 'src/widgets/page_view.dart';export 'src/widgets/pages.dart';export 'src/widgets/performance_overlay.dart';export 'src/widgets/placeholder.dart';export 'src/widgets/platform_menu_bar.dart';export 'src/widgets/platform_selectable_region_context_menu.dart';export 'src/widgets/platform_view.dart';export 'src/widgets/pop_scope.dart';export 'src/widgets/preferred_size.dart';export 'src/widgets/primary_scroll_controller.dart';export 'src/widgets/raw_keyboard_listener.dart';export 'src/widgets/reorderable_list.dart';export 'src/widgets/restoration.dart';export 'src/widgets/restoration_properties.dart';export 'src/widgets/router.dart';export 'src/widgets/routes.dart';export 'src/widgets/safe_area.dart';export 'src/widgets/scroll_activity.dart';export 'src/widgets/scroll_aware_image_provider.dart';export 'src/widgets/scroll_configuration.dart';export 'src/widgets/scroll_context.dart';export 'src/widgets/scroll_controller.dart';export 'src/widgets/scroll_delegate.dart';export 'src/widgets/scroll_metrics.dart';export 'src/widgets/scroll_notification.dart';export 'src/widgets/scroll_notification_observer.dart';export 'src/widgets/scroll_physics.dart';export 'src/widgets/scroll_position.dart';export 'src/widgets/scroll_position_with_single_context.dart';export 'src/widgets/scroll_simulation.dart';export 'src/widgets/scroll_view.dart';export 'src/widgets/scrollable.dart';export 'src/widgets/scrollable_helpers.dart';export 'src/widgets/scrollbar.dart';export 'src/widgets/selectable_region.dart';export 'src/widgets/selection_container.dart';export 'src/widgets/semantics_debugger.dart';export 'src/widgets/service_extensions.dart';export 'src/widgets/shared_app_data.dart';export 'src/widgets/shortcuts.dart';export 'src/widgets/single_child_scroll_view.dart';export 'src/widgets/size_changed_layout_notifier.dart';export 'src/widgets/sliver.dart';export 'src/widgets/sliver_fill.dart';export 'src/widgets/sliver_layout_builder.dart';export 'src/widgets/sliver_persistent_header.dart';export 'src/widgets/sliver_prototype_extent_list.dart';export 'src/widgets/sliver_varied_extent_list.dart';export 'src/widgets/slotted_render_object_widget.dart';export 'src/widgets/snapshot_widget.dart';export 'src/widgets/spacer.dart';export 'src/widgets/spell_check.dart';export 'src/widgets/status_transitions.dart';export 'src/widgets/table.dart';export 'src/widgets/tap_region.dart';export 'src/widgets/text.dart';export 'src/widgets/text_editing_intents.dart';export 'src/widgets/text_selection.dart';export 'src/widgets/text_selection_toolbar_anchors.dart';export 'src/widgets/text_selection_toolbar_layout_delegate.dart';export 'src/widgets/texture.dart';export 'src/widgets/ticker_provider.dart';export 'src/widgets/title.dart';export 'src/widgets/transitions.dart';export 'src/widgets/tween_animation_builder.dart';export 'src/widgets/two_dimensional_scroll_view.dart';export 'src/widgets/two_dimensional_viewport.dart';export 'src/widgets/undo_history.dart';export 'src/widgets/unique_widget.dart';export 'src/widgets/value_listenable_builder.dart';export 'src/widgets/view.dart';export 'src/widgets/viewport.dart';export 'src/widgets/visibility.dart';export 'src/widgets/widget_inspector.dart';export 'src/widgets/widget_span.dart';export 'src/widgets/will_pop_scope.dart';12345// 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.
export 'package:flutter_goldens/flutter_goldens.dart' show testExecutable;12345678// 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';
// package:flutter_goldens is not used as part of the test process for web.Future<void> testExecutable(FutureOr<void> Function() testMain) async => testMain();123456789include: ../analysis_options.yaml
linter: rules: # Tests try to throw and catch things in exciting ways all the time, so # we disable these lints for the tests. only_throw_errors: false avoid_catches_without_on_clauses: false avoid_catching_errors: false12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152// 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_test/flutter_test.dart';
void main() { test('Disposing controller removes listeners to avoid memory leaks', () { final _TestAnimationController controller = _TestAnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); int statusListener = 0; int listener = 0; controller.addListener(() { listener++; }); controller.addStatusListener((AnimationStatus _) { statusListener++; }); expect(statusListener, 0); expect(listener, 0);
controller.publicNotifyListeners(); controller.publicNotifyStatusListeners(AnimationStatus.completed); expect(statusListener, 1); expect(listener, 1);
controller.dispose(); controller.publicNotifyListeners(); controller.publicNotifyStatusListeners(AnimationStatus.completed); expect(statusListener, 1); expect(listener, 1); });}
class _TestAnimationController extends AnimationController { _TestAnimationController({ super.duration, required super.vsync, });
void publicNotifyListeners() { super.notifyListeners(); }
void publicNotifyStatusListeners(AnimationStatus status) { super.notifyStatusListeners(status); }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106// 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/physics.dart';import 'package:flutter/scheduler.dart';import 'package:flutter/semantics.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 '../scheduler/scheduler_tester.dart';
void main() { setUp(() { WidgetsFlutterBinding.ensureInitialized(); WidgetsBinding.instance ..resetEpoch() ..platformDispatcher.onBeginFrame = null ..platformDispatcher.onDrawFrame = null; });
test('AnimationController dispatches memory events', () async { await expectLater( await memoryEvents( () => AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ).dispose(), AnimationController, ), areCreateAndDispose, ); });
test('Can set value during status callback', () { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); bool didComplete = false; bool didDismiss = false; controller.addStatusListener((AnimationStatus status) { if (status == AnimationStatus.completed) { didComplete = true; controller.value = 0.0; controller.forward(); } else if (status == AnimationStatus.dismissed) { didDismiss = true; controller.value = 0.0; controller.forward(); } });
controller.forward(); expect(didComplete, isFalse); expect(didDismiss, isFalse); tick(const Duration(seconds: 1)); expect(didComplete, isFalse); expect(didDismiss, isFalse); tick(const Duration(seconds: 2)); expect(didComplete, isTrue); expect(didDismiss, isTrue);
controller.stop(); controller.dispose(); });
test('Receives status callbacks for forward and reverse', () { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); final List<double> valueLog = <double>[]; final List<AnimationStatus> log = <AnimationStatus>[]; controller ..addStatusListener(log.add) ..addListener(() { valueLog.add(controller.value); });
expect(log, equals(<AnimationStatus>[])); expect(valueLog, equals(<AnimationStatus>[]));
controller.forward();
expect(log, equals(<AnimationStatus>[AnimationStatus.forward])); expect(valueLog, equals(<AnimationStatus>[]));
controller.reverse();
expect(log, equals(<AnimationStatus>[AnimationStatus.forward, AnimationStatus.dismissed])); expect(valueLog, equals(<AnimationStatus>[]));
controller.reverse();
expect(log, equals(<AnimationStatus>[AnimationStatus.forward, AnimationStatus.dismissed])); expect(valueLog, equals(<AnimationStatus>[]));
log.clear(); controller.forward();
expect(log, equals(<AnimationStatus>[AnimationStatus.forward])); expect(valueLog, equals(<AnimationStatus>[]));
controller.forward();
expect(log, equals(<AnimationStatus>[AnimationStatus.forward])); expect(valueLog, equals(<AnimationStatus>[]));
controller.reverse(); log.clear();
tick(const Duration(seconds: 10)); expect(log, equals(<AnimationStatus>[])); expect(valueLog, equals(<AnimationStatus>[])); tick(const Duration(seconds: 20)); expect(log, equals(<AnimationStatus>[])); expect(valueLog, equals(<AnimationStatus>[])); tick(const Duration(seconds: 30)); expect(log, equals(<AnimationStatus>[])); expect(valueLog, equals(<AnimationStatus>[])); tick(const Duration(seconds: 40)); expect(log, equals(<AnimationStatus>[])); expect(valueLog, equals(<AnimationStatus>[]));
controller.stop(); controller.dispose(); });
test('Forward and reverse from values', () { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); final List<double> valueLog = <double>[]; final List<AnimationStatus> statusLog = <AnimationStatus>[]; controller ..addStatusListener(statusLog.add) ..addListener(() { valueLog.add(controller.value); });
controller.reverse(from: 0.2); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.reverse ])); expect(valueLog, equals(<double>[ 0.2 ])); expect(controller.value, equals(0.2)); statusLog.clear(); valueLog.clear();
controller.forward(from: 0.0); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.dismissed, AnimationStatus.forward ])); expect(valueLog, equals(<double>[ 0.0 ])); expect(controller.value, equals(0.0)); controller.dispose(); });
test('Forward and reverse with different durations', () { AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), reverseDuration: const Duration(milliseconds: 50), vsync: const TestVSync(), );
controller.forward(); tick(const Duration(milliseconds: 10)); tick(const Duration(milliseconds: 30)); expect(controller.value, moreOrLessEquals(0.2)); tick(const Duration(milliseconds: 60)); expect(controller.value, moreOrLessEquals(0.5)); tick(const Duration(milliseconds: 90)); expect(controller.value, moreOrLessEquals(0.8)); tick(const Duration(milliseconds: 120)); expect(controller.value, moreOrLessEquals(1.0)); controller.stop();
controller.reverse(); tick(const Duration(milliseconds: 210)); tick(const Duration(milliseconds: 220)); expect(controller.value, moreOrLessEquals(0.8)); tick(const Duration(milliseconds: 230)); expect(controller.value, moreOrLessEquals(0.6)); tick(const Duration(milliseconds: 240)); expect(controller.value, moreOrLessEquals(0.4)); tick(const Duration(milliseconds: 260)); expect(controller.value, moreOrLessEquals(0.0)); controller.stop();
// Swap which duration is longer. controller = AnimationController( duration: const Duration(milliseconds: 50), reverseDuration: const Duration(milliseconds: 100), vsync: const TestVSync(), );
controller.forward(); tick(const Duration(milliseconds: 10)); tick(const Duration(milliseconds: 30)); expect(controller.value, moreOrLessEquals(0.4)); tick(const Duration(milliseconds: 60)); expect(controller.value, moreOrLessEquals(1.0)); tick(const Duration(milliseconds: 90)); expect(controller.value, moreOrLessEquals(1.0)); controller.stop();
controller.reverse(); tick(const Duration(milliseconds: 210)); tick(const Duration(milliseconds: 220)); expect(controller.value, moreOrLessEquals(0.9)); tick(const Duration(milliseconds: 230)); expect(controller.value, moreOrLessEquals(0.8)); tick(const Duration(milliseconds: 240)); expect(controller.value, moreOrLessEquals(0.7)); tick(const Duration(milliseconds: 260)); expect(controller.value, moreOrLessEquals(0.5)); tick(const Duration(milliseconds: 310)); expect(controller.value, moreOrLessEquals(0.0)); controller.stop(); controller.dispose(); });
test('Forward only from value', () { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); final List<double> valueLog = <double>[]; final List<AnimationStatus> statusLog = <AnimationStatus>[]; controller ..addStatusListener(statusLog.add) ..addListener(() { valueLog.add(controller.value); });
controller.forward(from: 0.2); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.forward ])); expect(valueLog, equals(<double>[ 0.2 ])); expect(controller.value, equals(0.2)); controller.dispose(); });
test('Can fling to upper and lower bounds', () { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), );
controller.fling(); tick(const Duration(seconds: 1)); tick(const Duration(seconds: 2)); expect(controller.value, 1.0); controller.stop();
final AnimationController largeRangeController = AnimationController( duration: const Duration(milliseconds: 100), lowerBound: -30.0, upperBound: 45.0, vsync: const TestVSync(), );
largeRangeController.fling(); tick(const Duration(seconds: 3)); tick(const Duration(seconds: 4)); expect(largeRangeController.value, 45.0); largeRangeController.fling(velocity: -1.0); tick(const Duration(seconds: 5)); tick(const Duration(seconds: 6)); expect(largeRangeController.value, -30.0); largeRangeController.stop(); controller.dispose(); largeRangeController.dispose(); });
test('Custom springDescription can be applied', () { final AnimationController controller = AnimationController( vsync: const TestVSync(), ); final AnimationController customSpringController = AnimationController( vsync: const TestVSync(), );
controller.fling(); // Will produce longer and smoother animation than the default. customSpringController.fling( springDescription: SpringDescription.withDampingRatio( mass: 0.01, stiffness: 10.0, ratio: 2.0, ), ); tick(Duration.zero); tick(const Duration(milliseconds: 50));
expect(customSpringController.value < controller.value, true); controller.dispose(); customSpringController.dispose(); });
test('lastElapsedDuration control test', () { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); controller.forward(); tick(const Duration(milliseconds: 20)); tick(const Duration(milliseconds: 30)); tick(const Duration(milliseconds: 40)); expect(controller.lastElapsedDuration, equals(const Duration(milliseconds: 20))); controller.stop(); controller.dispose(); });
test('toString control test', () { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); expect(controller, hasOneLineDescription); controller.forward(); tick(const Duration(milliseconds: 10)); tick(const Duration(milliseconds: 20)); expect(controller, hasOneLineDescription); tick(const Duration(milliseconds: 30)); expect(controller, hasOneLineDescription); controller.reverse(); tick(const Duration(milliseconds: 40)); tick(const Duration(milliseconds: 50)); expect(controller, hasOneLineDescription); controller.stop(); controller.dispose(); });
test('velocity test - linear', () { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 1000), vsync: const TestVSync(), );
// mid-flight controller.forward(); tick(Duration.zero); tick(const Duration(milliseconds: 500)); expect(controller.velocity, inInclusiveRange(0.9, 1.1));
// edges controller.forward(); expect(controller.velocity, inInclusiveRange(0.4, 0.6)); tick(Duration.zero); expect(controller.velocity, inInclusiveRange(0.4, 0.6)); tick(const Duration(milliseconds: 5)); expect(controller.velocity, inInclusiveRange(0.9, 1.1));
controller.forward(from: 0.5); expect(controller.velocity, inInclusiveRange(0.4, 0.6)); tick(Duration.zero); expect(controller.velocity, inInclusiveRange(0.4, 0.6)); tick(const Duration(milliseconds: 5)); expect(controller.velocity, inInclusiveRange(0.9, 1.1));
// stopped controller.forward(from: 1.0); expect(controller.velocity, 0.0); tick(Duration.zero); expect(controller.velocity, 0.0); tick(const Duration(milliseconds: 500)); expect(controller.velocity, 0.0);
controller.forward(); tick(Duration.zero); tick(const Duration(milliseconds: 1000)); expect(controller.velocity, 0.0);
controller.stop(); controller.dispose(); });
test('Disposed AnimationController toString works', () { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); controller.dispose(); expect(controller, hasOneLineDescription); });
test('AnimationController error handling', () { final AnimationController controller = AnimationController( vsync: const TestVSync(), );
expect(controller.forward, throwsFlutterError); expect(controller.reverse, throwsFlutterError); expect(() { controller.animateTo(0.5); }, throwsFlutterError); expect(controller.repeat, throwsFlutterError);
controller.dispose(); FlutterError? result; try { controller.dispose(); } on FlutterError catch (e) { result = e; } expect(result, isNotNull); expect( result!.toStringDeep(), equalsIgnoringHashCodes( 'FlutterError\n' ' AnimationController.dispose() called more than once.\n' ' A given AnimationController cannot be disposed more than once.\n' ' The following AnimationController object was disposed multiple\n' ' times:\n' ' AnimationController#00000(⏮ 0.000; paused; DISPOSED)\n', ), ); final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder(); result.debugFillProperties(builder); final DiagnosticsNode controllerProperty = builder.properties.last; expect(controllerProperty.name, 'The following AnimationController object was disposed multiple times'); expect(controllerProperty.value, controller); });
test('AnimationController repeat() throws if period is not specified', () { final AnimationController controller = AnimationController( vsync: const TestVSync(), ); expect(() { controller.repeat(); }, throwsFlutterError); expect(() { controller.repeat(); }, throwsFlutterError); controller.dispose(); });
test('Do not animate if already at target', () { final List<AnimationStatus> statusLog = <AnimationStatus>[];
final AnimationController controller = AnimationController( value: 0.5, vsync: const TestVSync(), )..addStatusListener(statusLog.add);
expect(controller.value, equals(0.5)); controller.animateTo(0.5, duration: const Duration(milliseconds: 100)); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.completed ])); expect(controller.value, equals(0.5)); controller.dispose(); });
test('Do not animate to upperBound if already at upperBound', () { final List<AnimationStatus> statusLog = <AnimationStatus>[];
final AnimationController controller = AnimationController( value: 1.0, vsync: const TestVSync(), )..addStatusListener(statusLog.add);
expect(controller.value, equals(1.0)); controller.animateTo(1.0, duration: const Duration(milliseconds: 100)); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.completed ])); expect(controller.value, equals(1.0)); controller.dispose(); });
test('Do not animate to lowerBound if already at lowerBound', () { final List<AnimationStatus> statusLog = <AnimationStatus>[];
final AnimationController controller = AnimationController( value: 0.0, vsync: const TestVSync(), )..addStatusListener(statusLog.add);
expect(controller.value, equals(0.0)); controller.animateTo(0.0, duration: const Duration(milliseconds: 100)); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.completed ])); expect(controller.value, equals(0.0)); controller.dispose(); });
test('Do not animate if already at target mid-flight (forward)', () { final List<AnimationStatus> statusLog = <AnimationStatus>[]; final AnimationController controller = AnimationController( value: 0.0, duration: const Duration(milliseconds: 1000), vsync: const TestVSync(), )..addStatusListener(statusLog.add);
expect(controller.value, equals(0.0));
controller.forward(); tick(Duration.zero); tick(const Duration(milliseconds: 500)); expect(controller.value, inInclusiveRange(0.4, 0.6)); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.forward ]));
final double currentValue = controller.value; controller.animateTo(currentValue, duration: const Duration(milliseconds: 100)); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.forward, AnimationStatus.completed ])); expect(controller.value, currentValue); controller.dispose(); });
test('Do not animate if already at target mid-flight (reverse)', () { final List<AnimationStatus> statusLog = <AnimationStatus>[]; final AnimationController controller = AnimationController( value: 1.0, duration: const Duration(milliseconds: 1000), vsync: const TestVSync(), )..addStatusListener(statusLog.add);
expect(controller.value, equals(1.0));
controller.reverse(); tick(Duration.zero); tick(const Duration(milliseconds: 500)); expect(controller.value, inInclusiveRange(0.4, 0.6)); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.reverse ]));
final double currentValue = controller.value; controller.animateTo(currentValue, duration: const Duration(milliseconds: 100)); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.reverse, AnimationStatus.completed ])); expect(controller.value, currentValue); controller.dispose(); });
test('animateTo can deal with duration == Duration.zero', () { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), );
controller.forward(from: 0.2); expect(controller.value, 0.2); controller.animateTo(1.0, duration: Duration.zero); expect(SchedulerBinding.instance.transientCallbackCount, equals(0), reason: 'Expected no animation.'); expect(controller.value, 1.0); controller.dispose(); });
test('resetting animation works at all phases', () { final List<AnimationStatus> statusLog = <AnimationStatus>[]; final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), value: 0.0, vsync: const TestVSync(), )..addStatusListener(statusLog.add);
expect(controller.value, 0.0); expect(controller.status, AnimationStatus.dismissed);
controller.reset();
expect(controller.value, 0.0); expect(controller.status, AnimationStatus.dismissed);
statusLog.clear(); controller.forward(); tick(Duration.zero); tick(const Duration(milliseconds: 50)); expect(controller.status, AnimationStatus.forward); controller.reset();
expect(controller.value, 0.0); expect(controller.status, AnimationStatus.dismissed); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.forward, AnimationStatus.dismissed ]));
controller.value = 1.0; statusLog.clear(); controller.reverse(); tick(Duration.zero); tick(const Duration(milliseconds: 50)); expect(controller.status, AnimationStatus.reverse); controller.reset();
expect(controller.value, 0.0); expect(controller.status, AnimationStatus.dismissed); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.reverse, AnimationStatus.dismissed ]));
statusLog.clear(); controller.forward(); tick(Duration.zero); tick(const Duration(milliseconds: 150)); expect(controller.status, AnimationStatus.completed); controller.reset();
expect(controller.value, 0.0); expect(controller.status, AnimationStatus.dismissed); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.forward, AnimationStatus.completed, AnimationStatus.dismissed ])); controller.dispose(); });
test('setting value directly sets correct status', () { final AnimationController controller = AnimationController( value: 0.0, vsync: const TestVSync(), );
expect(controller.value, 0.0); expect(controller.status, AnimationStatus.dismissed);
controller.value = 0.5; expect(controller.value, 0.5); expect(controller.status, AnimationStatus.forward);
controller.value = 1.0; expect(controller.value, 1.0); expect(controller.status, AnimationStatus.completed);
controller.value = 0.5; expect(controller.value, 0.5); expect(controller.status, AnimationStatus.forward);
controller.value = 0.0; expect(controller.value, 0.0); expect(controller.status, AnimationStatus.dismissed); controller.dispose(); });
test('animateTo sets correct status', () { final List<AnimationStatus> statusLog = <AnimationStatus>[]; final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), value: 0.0, vsync: const TestVSync(), )..addStatusListener(statusLog.add);
expect(controller.value, 0.0); expect(controller.status, AnimationStatus.dismissed);
// Animate from 0.0 to 0.5 controller.animateTo(0.5); tick(Duration.zero); tick(const Duration(milliseconds: 150)); expect(controller.value, 0.5); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.forward, AnimationStatus.completed ])); statusLog.clear();
// Animate from 0.5 to 1.0 controller.animateTo(1.0); tick(Duration.zero); tick(const Duration(milliseconds: 150)); expect(controller.value, 1.0); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.forward, AnimationStatus.completed ])); statusLog.clear();
// Animate from 1.0 to 0.5 controller.animateTo(0.5); tick(Duration.zero); tick(const Duration(milliseconds: 150)); expect(controller.value, 0.5); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.forward, AnimationStatus.completed ])); statusLog.clear();
// Animate from 0.5 to 1.0 controller.animateTo(0.0); tick(Duration.zero); tick(const Duration(milliseconds: 150)); expect(controller.value, 0.0); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.forward, AnimationStatus.completed ])); statusLog.clear(); controller.dispose(); });
test('after a reverse call animateTo sets correct status', () { final List<AnimationStatus> statusLog = <AnimationStatus>[]; final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), value: 1.0, vsync: const TestVSync(), )..addStatusListener(statusLog.add);
expect(controller.value, 1.0); expect(controller.status, AnimationStatus.completed);
controller.reverse(); tick(Duration.zero); tick(const Duration(milliseconds: 150)); expect(controller.value, 0.0); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.reverse, AnimationStatus.dismissed ])); statusLog.clear();
controller.animateTo(0.5); tick(Duration.zero); tick(const Duration(milliseconds: 150)); expect(controller.value, 0.5); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.forward, AnimationStatus.completed ])); statusLog.clear(); controller.dispose(); });
test('after a forward call animateTo sets correct status', () { final List<AnimationStatus> statusLog = <AnimationStatus>[]; final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), value: 0.0, vsync: const TestVSync(), )..addStatusListener(statusLog.add);
expect(controller.value, 0.0); expect(controller.status, AnimationStatus.dismissed);
controller.forward(); tick(Duration.zero); tick(const Duration(milliseconds: 150)); expect(controller.value, 1.0); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.forward, AnimationStatus.completed ])); statusLog.clear();
controller.animateTo(0.5); tick(Duration.zero); tick(const Duration(milliseconds: 150)); expect(controller.value, 0.5); expect(statusLog, equals(<AnimationStatus>[ AnimationStatus.forward, AnimationStatus.completed ])); statusLog.clear(); controller.dispose(); });
test( 'calling repeat with reverse set to true makes the animation alternate ' 'between lowerBound and upperBound values on each repeat', () { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), value: 0.0, vsync: const TestVSync(), );
expect(controller.value, 0.0);
controller.repeat(reverse: true); tick(Duration.zero); tick(const Duration(milliseconds: 25)); expect(controller.value, 0.25);
tick(Duration.zero); tick(const Duration(milliseconds: 125)); expect(controller.value, 0.75);
controller.reset(); controller.value = 1.0; expect(controller.value, 1.0);
controller.repeat(reverse: true); tick(Duration.zero); tick(const Duration(milliseconds: 25)); expect(controller.value, 0.75);
tick(Duration.zero); tick(const Duration(milliseconds: 125)); expect(controller.value, 0.25);
controller.reset(); controller.value = 0.5; expect(controller.value, 0.5);
controller.repeat(reverse: true); tick(Duration.zero); tick(const Duration(milliseconds: 50)); expect(controller.value, 1.0);
tick(Duration.zero); tick(const Duration(milliseconds: 150)); expect(controller.value, 0.0); controller.dispose(); }, );
test( 'calling repeat with specified min and max values makes the animation ' 'alternate between min and max values on each repeat', () { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), value: 0.0, vsync: const TestVSync(), );
expect(controller.value, 0.0);
controller.repeat(reverse: true, min: 0.5, max: 1.0); tick(Duration.zero); tick(const Duration(milliseconds: 50)); expect(controller.value, 0.75);
tick(Duration.zero); tick(const Duration(milliseconds: 100)); expect(controller.value, 1.00);
tick(Duration.zero); tick(const Duration(milliseconds: 200)); expect(controller.value, 0.5);
controller.reset(); controller.value = 0.0; expect(controller.value, 0.0);
controller.repeat(reverse: true, min: 1.0, max: 1.0); tick(Duration.zero); tick(const Duration(milliseconds: 25)); expect(controller.value, 1.0);
tick(Duration.zero); tick(const Duration(milliseconds: 125)); expect(controller.value, 1.0); controller.dispose(); }, );
group('AnimationBehavior', () { test('Default values for constructor', () { final AnimationController controller = AnimationController(vsync: const TestVSync()); expect(controller.animationBehavior, AnimationBehavior.normal);
final AnimationController repeating = AnimationController.unbounded(vsync: const TestVSync()); expect(repeating.animationBehavior, AnimationBehavior.preserve); controller.dispose(); repeating.dispose(); });
test('AnimationBehavior.preserve runs at normal speed when animatingTo', () { debugSemanticsDisableAnimations = true; final AnimationController controller = AnimationController( vsync: const TestVSync(), animationBehavior: AnimationBehavior.preserve, );
expect(controller.value, 0.0); expect(controller.status, AnimationStatus.dismissed);
controller.animateTo(1.0, duration: const Duration(milliseconds: 100)); tick(Duration.zero); tick(const Duration(milliseconds: 50));
expect(controller.value, 0.5); expect(controller.status, AnimationStatus.forward);
tick(Duration.zero); tick(const Duration(milliseconds: 150));
expect(controller.value, 1.0); expect(controller.status, AnimationStatus.completed); debugSemanticsDisableAnimations = false; controller.dispose(); });
test('AnimationBehavior.normal runs at 20x speed when animatingTo', () { debugSemanticsDisableAnimations = true; final AnimationController controller = AnimationController( vsync: const TestVSync(), );
expect(controller.value, 0.0); expect(controller.status, AnimationStatus.dismissed);
controller.animateTo(1.0, duration: const Duration(milliseconds: 100)); tick(Duration.zero); tick(const Duration(microseconds: 2500));
expect(controller.value, 0.5); expect(controller.status, AnimationStatus.forward);
tick(Duration.zero); tick(const Duration(milliseconds: 5, microseconds: 1000));
expect(controller.value, 1.0); expect(controller.status, AnimationStatus.completed); debugSemanticsDisableAnimations = null; controller.dispose(); });
test('AnimationBehavior.normal runs "faster" than AnimationBehavior.preserve', () { debugSemanticsDisableAnimations = true; final AnimationController controller = AnimationController( vsync: const TestVSync(), ); final AnimationController fastController = AnimationController( vsync: const TestVSync(), );
controller.fling(animationBehavior: AnimationBehavior.preserve); fastController.fling(animationBehavior: AnimationBehavior.normal); tick(Duration.zero); tick(const Duration(milliseconds: 50));
// We don't assert a specific faction that normal animation. expect(controller.value < fastController.value, true); debugSemanticsDisableAnimations = null; controller.dispose(); fastController.dispose(); }); });
test('AnimationController methods assert _ticker is not null', () { final AnimationController controller = AnimationController( vsync: const TestVSync(), );
controller.dispose();
expect(() => controller.animateBack(0), throwsAssertionError); expect(() => controller.animateTo(0), throwsAssertionError); expect(() => controller.animateWith(GravitySimulation(0, 0, 0, 0)), throwsAssertionError); expect(() => controller.stop(), throwsAssertionError); expect(() => controller.forward(), throwsAssertionError); expect(() => controller.reverse(), throwsAssertionError); });
test('Simulations run forward', () { final List<AnimationStatus> statuses = <AnimationStatus>[]; final AnimationController controller = AnimationController( vsync: const TestVSync(), duration: const Duration(seconds: 1), )..addStatusListener((AnimationStatus status) { statuses.add(status); });
controller.animateWith(TestSimulation()); tick(Duration.zero); tick(const Duration(seconds: 2)); expect(statuses, <AnimationStatus>[AnimationStatus.forward]); controller.dispose(); });
test('Simulations run forward even after a reverse run', () { final List<AnimationStatus> statuses = <AnimationStatus>[]; final AnimationController controller = AnimationController( vsync: const TestVSync(), duration: const Duration(seconds: 1), )..addStatusListener((AnimationStatus status) { statuses.add(status); }); controller.reverse(from: 1.0); tick(Duration.zero); tick(const Duration(seconds: 2)); expect(statuses, <AnimationStatus>[AnimationStatus.completed, AnimationStatus.reverse, AnimationStatus.dismissed]); statuses.clear();
controller.animateWith(TestSimulation()); tick(Duration.zero); tick(const Duration(seconds: 2)); expect(statuses, <AnimationStatus>[AnimationStatus.forward]); controller.dispose(); });
test('Repeating animation with reverse: true report as forward and reverse', () { final List<AnimationStatus> statuses = <AnimationStatus>[]; final AnimationController controller = AnimationController( vsync: const TestVSync(), duration: const Duration(seconds: 1), )..addStatusListener((AnimationStatus status) { statuses.add(status); });
controller.repeat(reverse: true); tick(Duration.zero); tick(const Duration(milliseconds: 999)); expect(statuses, <AnimationStatus>[AnimationStatus.forward]); statuses.clear(); tick(const Duration(seconds: 1)); expect(statuses, <AnimationStatus>[AnimationStatus.reverse]); controller.dispose(); });
test('AnimateBack can runs successfully with just "reverseDuration" property set', () { final List<AnimationStatus> statuses = <AnimationStatus>[]; final AnimationController controller = AnimationController( reverseDuration: const Duration(seconds: 2), vsync: const TestVSync(), )..addStatusListener((AnimationStatus status) { statuses.add(status); });
controller.animateBack(0.8);
expect(statuses, <AnimationStatus>[AnimationStatus.reverse]); statuses.clear(); tick(Duration.zero); tick(const Duration(seconds: 2)); expect(statuses, <AnimationStatus>[AnimationStatus.dismissed]);
controller.dispose(); });
group('AnimationController "duration" error test', () { test('AnimationController forward() will throw an error if there is no default duration', () { final AnimationController controller = AnimationController( vsync: const TestVSync(), );
late FlutterError error; try { controller.forward(); } on FlutterError catch (e) { error = e; }
expect(error, isNotNull); expect( error.toStringDeep(), 'FlutterError\n' ' AnimationController.forward() called with no default duration.\n' ' The "duration" property should be set, either in the constructor\n' ' or later, before calling the forward() function.\n', );
controller.dispose(); });
test( 'AnimationController animateTo() will throw an error if there is no explicit duration ' 'and default duration', () { final AnimationController controller = AnimationController( vsync: const TestVSync(), );
late FlutterError error; try { controller.animateTo(0.8); } on FlutterError catch (e) { error = e; }
expect(error, isNotNull); expect( error.toStringDeep(), 'FlutterError\n' ' AnimationController.animateTo() called with no explicit duration\n' ' and no default duration.\n' ' Either the "duration" argument to the animateTo() method should\n' ' be provided, or the "duration" property should be set, either in\n' ' the constructor or later, before calling the animateTo()\n' ' function.\n', );
controller.dispose(); }, );
test('AnimationController reverse() will throw an error if there is no default duration or reverseDuration', () { final AnimationController controller = AnimationController( vsync: const TestVSync(), );
late FlutterError error; try { controller.reverse(); } on FlutterError catch (e) { error = e; }
expect(error, isNotNull); expect( error.toStringDeep(), 'FlutterError\n' ' AnimationController.reverse() called with no default duration or\n' ' reverseDuration.\n' ' The "duration" or "reverseDuration" property should be set,\n' ' either in the constructor or later, before calling the reverse()\n' ' function.\n', );
controller.dispose(); });
test( 'AnimationController animateBack() will throw an error if there is no explicit duration and ' 'no default duration or reverseDuration', () { final AnimationController controller = AnimationController( vsync: const TestVSync(), );
late FlutterError error; try { controller.animateBack(0.8); } on FlutterError catch (e) { error = e; }
expect(error, isNotNull); expect( error.toStringDeep(), 'FlutterError\n' ' AnimationController.animateBack() called with no explicit\n' ' duration and no default duration or reverseDuration.\n' ' Either the "duration" argument to the animateBack() method should\n' ' be provided, or the "duration" or "reverseDuration" property\n' ' should be set, either in the constructor or later, before calling\n' ' the animateBack() function.\n', );
controller.dispose(); }, ); });
}
class TestSimulation extends Simulation { @override double dx(double time) => time;
@override bool isDone(double time) => false;
@override double x(double time) => time;}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283// 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() { test('Animation created from ValueListenable', () { final ValueNotifier<double> listenable = ValueNotifier<double>(0.0); final Animation<double> animation = Animation<double>.fromValueListenable(listenable);
expect(animation.status, AnimationStatus.forward); expect(animation.value, 0.0);
listenable.value = 1.0;
expect(animation.value, 1.0);
bool listenerCalled = false; void listener() { listenerCalled = true; }
animation.addListener(listener);
listenable.value = 0.5;
expect(listenerCalled, true); listenerCalled = false;
animation.removeListener(listener);
listenable.value = 0.2; expect(listenerCalled, false); });
test('Animation created from ValueListenable can transform value', () { final ValueNotifier<double> listenable = ValueNotifier<double>(0.0); final Animation<double> animation = Animation<double>.fromValueListenable(listenable, transformer: (double input) { return input / 10; });
expect(animation.status, AnimationStatus.forward); expect(animation.value, 0.0);
listenable.value = 10.0;
expect(animation.value, 1.0); });
test('Animation created from ValueListenable can be transformed via drive', () { final ValueNotifier<double> listenable = ValueNotifier<double>(0.0); final Animation<double> animation = Animation<double>.fromValueListenable(listenable); final Animation<Offset> offset = animation.drive(Animatable<Offset>.fromCallback((double value) { return Offset(0.0, value); }));
expect(offset.value, Offset.zero); expect(offset.status, AnimationStatus.forward);
listenable.value = 10;
expect(offset.value, const Offset(0.0, 10.0));
bool listenerCalled = false; void listener() { listenerCalled = true; }
offset.addListener(listener);
listenable.value = 0.5;
expect(listenerCalled, true); listenerCalled = false;
offset.removeListener(listener);
listenable.value = 0.2; expect(listenerCalled, false); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185// 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/material.dart';import 'package:flutter_test/flutter_test.dart';
void main() { /* * Here lies tests for packages/flutter_test/lib/src/animation_sheet.dart * because [matchesGoldenFile] does not use Skia Gold in its native package. */
testWidgets('recording disposes images', (WidgetTester tester) async { final AnimationSheetBuilder builder = AnimationSheetBuilder(frameSize: _DecuplePixels.size); addTearDown(builder.dispose);
await tester.pumpFrames( builder.record( const _DecuplePixels(Duration(seconds: 1)), ), const Duration(milliseconds: 200), const Duration(milliseconds: 100), ); }, skip: isBrowser, // [intended] https://github.com/flutter/flutter/issues/56001 );
testWidgets('correctly records frames using collate', (WidgetTester tester) async { final AnimationSheetBuilder builder = AnimationSheetBuilder(frameSize: _DecuplePixels.size); addTearDown(builder.dispose);
await tester.pumpFrames( builder.record( const _DecuplePixels(Duration(seconds: 1)), ), const Duration(milliseconds: 200), const Duration(milliseconds: 100), );
await tester.pumpFrames( builder.record( const _DecuplePixels(Duration(seconds: 1)), recording: false, ), const Duration(milliseconds: 200), const Duration(milliseconds: 100), );
await tester.pumpFrames( builder.record( const _DecuplePixels(Duration(seconds: 1)), ), const Duration(milliseconds: 400), const Duration(milliseconds: 100), );
await expectLater( builder.collate(5), matchesGoldenFile('test.animation_sheet_builder.collate.png'), ); }, skip: isBrowser, // [intended] https://github.com/flutter/flutter/issues/56001 ); // https://github.com/flutter/flutter/issues/56001
testWidgets('use allLayers to record out-of-subtree contents', (WidgetTester tester) async { final AnimationSheetBuilder builder = AnimationSheetBuilder( frameSize: const Size(8, 2), allLayers: true, ); addTearDown(builder.dispose);
// The `record` (sized 8, 2) is placed on top of `_DecuplePixels` // (sized 12, 3), aligned at its top left. await tester.pumpFrames( Directionality( textDirection: TextDirection.ltr, child: Stack( children: <Widget>[ const _DecuplePixels(Duration(seconds: 1)), Align( alignment: Alignment.topLeft, child: builder.record(Container()), ), ], ), ), const Duration(milliseconds: 600), const Duration(milliseconds: 100), );
await expectLater( builder.collate(5), matchesGoldenFile('test.animation_sheet_builder.out_of_tree.png'), ); }, skip: isBrowser, // [intended] https://github.com/flutter/flutter/issues/56001 );}
// An animation of a yellow pixel moving from left to right, in a container of// (10, 1) with a 1-pixel-wide black border.class _DecuplePixels extends StatefulWidget { const _DecuplePixels(this.duration);
static const Size size = Size(12, 3);
final Duration duration;
@override State<StatefulWidget> createState() => _DecuplePixelsState();}
class _DecuplePixelsState extends State<_DecuplePixels> with SingleTickerProviderStateMixin<_DecuplePixels> { late AnimationController _controller;
@override void initState() { super.initState(); _controller = AnimationController( duration: widget.duration, vsync: this, ); _controller.repeat(); }
@override void dispose() { _controller.dispose(); super.dispose(); }
@override Widget build(BuildContext context) { return AnimatedBuilder( animation: _controller.view, builder: (BuildContext context, Widget? child) { return CustomPaint( painter: _PaintDecuplePixels(_controller.value), ); }, ); }}
class _PaintDecuplePixels extends CustomPainter { _PaintDecuplePixels(this.value);
final double value;
@override bool shouldRepaint(_PaintDecuplePixels oldDelegate) { return oldDelegate.value != value; }
@override void paint(Canvas canvas, Size size) { canvas.save(); final Rect rect = RectTween( begin: const Rect.fromLTWH(1, 1, 1, 1), end: const Rect.fromLTWH(11, 1, 1, 1), ).transform(value)!; canvas.drawRect(rect, Paint()..color = Colors.yellow); final Paint black = Paint()..color = Colors.black; canvas // Top border ..drawRect(const Rect.fromLTRB(0, 0, 12, 1), black) // Bottom border ..drawRect(const Rect.fromLTRB(0, 2, 12, 3), black) // Left border ..drawRect(const Rect.fromLTRB(0, 0, 1, 3), black) // Right border ..drawRect(const Rect.fromLTRB(11, 0, 12, 3), black);
canvas.restore(); }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192// 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' ]); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501// 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 '../scheduler/scheduler_tester.dart';
class BogusCurve extends Curve { const BogusCurve();
@override double transform(double t) => 100.0;}
void main() { setUp(() { WidgetsFlutterBinding.ensureInitialized(); WidgetsBinding.instance ..resetEpoch() ..platformDispatcher.onBeginFrame = null ..platformDispatcher.onDrawFrame = null; });
test('toString control test', () { expect(kAlwaysCompleteAnimation, hasOneLineDescription); expect(kAlwaysDismissedAnimation, hasOneLineDescription); expect(const AlwaysStoppedAnimation<double>(0.5), hasOneLineDescription); CurvedAnimation curvedAnimation = CurvedAnimation( parent: kAlwaysDismissedAnimation, curve: Curves.ease, ); expect(curvedAnimation, hasOneLineDescription); curvedAnimation.reverseCurve = Curves.elasticOut; expect(curvedAnimation, hasOneLineDescription); final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 500), vsync: const TestVSync(), ); controller ..value = 0.5 ..reverse(); curvedAnimation = CurvedAnimation( parent: controller, curve: Curves.ease, reverseCurve: Curves.elasticOut, ); expect(curvedAnimation, hasOneLineDescription); controller.stop(); });
test('ProxyAnimation.toString control test', () { final ProxyAnimation animation = ProxyAnimation(); expect(animation.value, 0.0); expect(animation.status, AnimationStatus.dismissed); expect(animation, hasOneLineDescription); animation.parent = kAlwaysDismissedAnimation; expect(animation, hasOneLineDescription); });
test('ProxyAnimation set parent generates value changed', () { final AnimationController controller = AnimationController( vsync: const TestVSync(), ); controller.value = 0.5; bool didReceiveCallback = false; final ProxyAnimation animation = ProxyAnimation() ..addListener(() { didReceiveCallback = true; }); expect(didReceiveCallback, isFalse); animation.parent = controller; expect(didReceiveCallback, isTrue); didReceiveCallback = false; expect(didReceiveCallback, isFalse); controller.value = 0.6; expect(didReceiveCallback, isTrue); });
test('ReverseAnimation calls listeners', () { final AnimationController controller = AnimationController( vsync: const TestVSync(), ); controller.value = 0.5; bool didReceiveCallback = false; void listener() { didReceiveCallback = true; } final ReverseAnimation animation = ReverseAnimation(controller) ..addListener(listener); expect(didReceiveCallback, isFalse); controller.value = 0.6; expect(didReceiveCallback, isTrue); didReceiveCallback = false; animation.removeListener(listener); expect(didReceiveCallback, isFalse); controller.value = 0.7; expect(didReceiveCallback, isFalse); expect(animation, hasOneLineDescription); });
test('TrainHoppingAnimation', () { final AnimationController currentTrain = AnimationController( vsync: const TestVSync(), ); final AnimationController nextTrain = AnimationController( vsync: const TestVSync(), ); currentTrain.value = 0.5; nextTrain.value = 0.75; bool didSwitchTrains = false; final TrainHoppingAnimation animation = TrainHoppingAnimation( currentTrain, nextTrain, onSwitchedTrain: () { didSwitchTrains = true; }, ); expect(didSwitchTrains, isFalse); expect(animation.value, 0.5); expect(animation, hasOneLineDescription); nextTrain.value = 0.25; expect(didSwitchTrains, isTrue); expect(animation.value, 0.25); expect(animation, hasOneLineDescription); expect(animation.toString(), contains('no next')); });
test('AnimationMean control test', () { final AnimationController left = AnimationController( value: 0.5, vsync: const TestVSync(), ); final AnimationController right = AnimationController( vsync: const TestVSync(), );
final AnimationMean mean = AnimationMean(left: left, right: right);
expect(mean, hasOneLineDescription); expect(mean.value, equals(0.25));
final List<double> log = <double>[]; void logValue() { log.add(mean.value); }
mean.addListener(logValue);
right.value = 1.0;
expect(mean.value, equals(0.75)); expect(log, equals(<double>[0.75])); log.clear();
mean.removeListener(logValue);
left.value = 0.0;
expect(mean.value, equals(0.50)); expect(log, isEmpty); });
test('AnimationMax control test', () { final AnimationController first = AnimationController( value: 0.5, vsync: const TestVSync(), ); final AnimationController second = AnimationController( vsync: const TestVSync(), );
final AnimationMax<double> max = AnimationMax<double>(first, second);
expect(max, hasOneLineDescription); expect(max.value, equals(0.5));
final List<double> log = <double>[]; void logValue() { log.add(max.value); }
max.addListener(logValue);
second.value = 1.0;
expect(max.value, equals(1.0)); expect(log, equals(<double>[1.0])); log.clear();
max.removeListener(logValue);
first.value = 0.0;
expect(max.value, equals(1.0)); expect(log, isEmpty); });
test('AnimationMin control test', () { final AnimationController first = AnimationController( value: 0.5, vsync: const TestVSync(), ); final AnimationController second = AnimationController( vsync: const TestVSync(), );
final AnimationMin<double> min = AnimationMin<double>(first, second);
expect(min, hasOneLineDescription); expect(min.value, equals(0.0));
final List<double> log = <double>[]; void logValue() { log.add(min.value); }
min.addListener(logValue);
second.value = 1.0;
expect(min.value, equals(0.5)); expect(log, equals(<double>[0.5])); log.clear();
min.removeListener(logValue);
first.value = 0.25;
expect(min.value, equals(0.25)); expect(log, isEmpty); });
test('CurvedAnimation with bogus curve', () { final AnimationController controller = AnimationController( vsync: const TestVSync(), ); final CurvedAnimation curved = CurvedAnimation(parent: controller, curve: const BogusCurve()); FlutterError? error; try { curved.value; } on FlutterError catch (e) { error = e; } expect(error, isNotNull); expect( error!.toStringDeep(), // RegExp matcher is required here due to flutter web and flutter mobile generating // slightly different floating point numbers // in Flutter web 0.0 sometimes just appears as 0. or 0 matches(RegExp(r'''FlutterError Invalid curve endpoint at \d+(\.\d*)?\. Curves must map 0\.0 to near zero and 1\.0 to near one but BogusCurve mapped \d+(\.\d*)? to \d+(\.\d*)?, which is near \d+(\.\d*)?\.''', multiLine: true)), ); });
test('CurvedAnimation running with different forward and reverse durations.', () { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), reverseDuration: const Duration(milliseconds: 50), vsync: const TestVSync(), ); final CurvedAnimation curved = CurvedAnimation(parent: controller, curve: Curves.linear, reverseCurve: Curves.linear);
controller.forward(); tick(Duration.zero); tick(const Duration(milliseconds: 10)); expect(curved.value, moreOrLessEquals(0.1)); tick(const Duration(milliseconds: 20)); expect(curved.value, moreOrLessEquals(0.2)); tick(const Duration(milliseconds: 30)); expect(curved.value, moreOrLessEquals(0.3)); tick(const Duration(milliseconds: 40)); expect(curved.value, moreOrLessEquals(0.4)); tick(const Duration(milliseconds: 50)); expect(curved.value, moreOrLessEquals(0.5)); tick(const Duration(milliseconds: 60)); expect(curved.value, moreOrLessEquals(0.6)); tick(const Duration(milliseconds: 70)); expect(curved.value, moreOrLessEquals(0.7)); tick(const Duration(milliseconds: 80)); expect(curved.value, moreOrLessEquals(0.8)); tick(const Duration(milliseconds: 90)); expect(curved.value, moreOrLessEquals(0.9)); tick(const Duration(milliseconds: 100)); expect(curved.value, moreOrLessEquals(1.0)); controller.reverse(); tick(const Duration(milliseconds: 110)); expect(curved.value, moreOrLessEquals(1.0)); tick(const Duration(milliseconds: 120)); expect(curved.value, moreOrLessEquals(0.8)); tick(const Duration(milliseconds: 130)); expect(curved.value, moreOrLessEquals(0.6)); tick(const Duration(milliseconds: 140)); expect(curved.value, moreOrLessEquals(0.4)); tick(const Duration(milliseconds: 150)); expect(curved.value, moreOrLessEquals(0.2)); tick(const Duration(milliseconds: 160)); expect(curved.value, moreOrLessEquals(0.0)); });
test('CurvedAnimation stops listening to parent when disposed.', () async { const Interval forwardCurve = Interval(0.0, 0.5); const Interval reverseCurve = Interval(0.5, 1.0);
final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), reverseDuration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); final CurvedAnimation curved = CurvedAnimation( parent: controller, curve: forwardCurve, reverseCurve: reverseCurve);
expect(forwardCurve.transform(0.5), 1.0); expect(reverseCurve.transform(0.5), 0.0);
controller.forward(from: 0.5); expect(controller.status, equals(AnimationStatus.forward)); expect(curved.value, equals(1.0));
controller.value = 1.0; expect(controller.status, equals(AnimationStatus.completed));
controller.reverse(from: 0.5); expect(controller.status, equals(AnimationStatus.reverse)); expect(curved.value, equals(0.0));
expect(curved.isDisposed, isFalse); curved.dispose(); expect(curved.isDisposed, isTrue);
controller.value = 0.0; expect(controller.status, equals(AnimationStatus.dismissed));
controller.forward(from: 0.5); expect(controller.status, equals(AnimationStatus.forward)); expect(curved.value, equals(0.0)); });
test('ReverseAnimation running with different forward and reverse durations.', () { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), reverseDuration: const Duration(milliseconds: 50), vsync: const TestVSync(), ); final ReverseAnimation reversed = ReverseAnimation( CurvedAnimation( parent: controller, curve: Curves.linear, reverseCurve: Curves.linear, ), );
controller.forward(); tick(Duration.zero); tick(const Duration(milliseconds: 10)); expect(reversed.value, moreOrLessEquals(0.9)); tick(const Duration(milliseconds: 20)); expect(reversed.value, moreOrLessEquals(0.8)); tick(const Duration(milliseconds: 30)); expect(reversed.value, moreOrLessEquals(0.7)); tick(const Duration(milliseconds: 40)); expect(reversed.value, moreOrLessEquals(0.6)); tick(const Duration(milliseconds: 50)); expect(reversed.value, moreOrLessEquals(0.5)); tick(const Duration(milliseconds: 60)); expect(reversed.value, moreOrLessEquals(0.4)); tick(const Duration(milliseconds: 70)); expect(reversed.value, moreOrLessEquals(0.3)); tick(const Duration(milliseconds: 80)); expect(reversed.value, moreOrLessEquals(0.2)); tick(const Duration(milliseconds: 90)); expect(reversed.value, moreOrLessEquals(0.1)); tick(const Duration(milliseconds: 100)); expect(reversed.value, moreOrLessEquals(0.0)); controller.reverse(); tick(const Duration(milliseconds: 110)); expect(reversed.value, moreOrLessEquals(0.0)); tick(const Duration(milliseconds: 120)); expect(reversed.value, moreOrLessEquals(0.2)); tick(const Duration(milliseconds: 130)); expect(reversed.value, moreOrLessEquals(0.4)); tick(const Duration(milliseconds: 140)); expect(reversed.value, moreOrLessEquals(0.6)); tick(const Duration(milliseconds: 150)); expect(reversed.value, moreOrLessEquals(0.8)); tick(const Duration(milliseconds: 160)); expect(reversed.value, moreOrLessEquals(1.0)); });
test('TweenSequence', () { final AnimationController controller = AnimationController( vsync: const TestVSync(), );
final Animation<double> animation = TweenSequence<double>( <TweenSequenceItem<double>>[ TweenSequenceItem<double>( tween: Tween<double>(begin: 5.0, end: 10.0), weight: 4.0, ), TweenSequenceItem<double>( tween: ConstantTween<double>(10.0), weight: 2.0, ), TweenSequenceItem<double>( tween: Tween<double>(begin: 10.0, end: 5.0), weight: 4.0, ), ], ).animate(controller);
expect(animation.value, 5.0);
controller.value = 0.2; expect(animation.value, 7.5);
controller.value = 0.4; expect(animation.value, 10.0);
controller.value = 0.6; expect(animation.value, 10.0);
controller.value = 0.8; expect(animation.value, 7.5);
controller.value = 1.0; expect(animation.value, 5.0); });
test('TweenSequence with curves', () { final AnimationController controller = AnimationController( vsync: const TestVSync(), );
final Animation<double> animation = TweenSequence<double>( <TweenSequenceItem<double>>[ TweenSequenceItem<double>( tween: Tween<double>(begin: 5.0, end: 10.0) .chain(CurveTween(curve: const Interval(0.5, 1.0))), weight: 4.0, ), TweenSequenceItem<double>( tween: ConstantTween<double>(10.0) .chain(CurveTween(curve: Curves.linear)), // linear is a no-op weight: 2.0, ), TweenSequenceItem<double>( tween: Tween<double>(begin: 10.0, end: 5.0) .chain(CurveTween(curve: const Interval(0.0, 0.5))), weight: 4.0, ), ], ).animate(controller);
expect(animation.value, 5.0);
controller.value = 0.2; expect(animation.value, 5.0);
controller.value = 0.4; expect(animation.value, 10.0);
controller.value = 0.6; expect(animation.value, 10.0);
controller.value = 0.8; expect(animation.value, 5.0);
controller.value = 1.0; expect(animation.value, 5.0); });
test('TweenSequence, one tween', () { final AnimationController controller = AnimationController( vsync: const TestVSync(), );
final Animation<double> animation = TweenSequence<double>( <TweenSequenceItem<double>>[ TweenSequenceItem<double>( tween: Tween<double>(begin: 5.0, end: 10.0), weight: 1.0, ), ], ).animate(controller);
expect(animation.value, 5.0);
controller.value = 0.5; expect(animation.value, 7.5);
controller.value = 1.0; expect(animation.value, 10.0); });
}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616// 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 'package:flutter_test/flutter_test.dart';
void main() { test('toString control test', () { expect(Curves.linear, hasOneLineDescription); expect(const SawTooth(3), hasOneLineDescription); expect(const Interval(0.25, 0.75), hasOneLineDescription); expect(const Interval(0.25, 0.75, curve: Curves.ease), hasOneLineDescription); });
test('Curve flipped control test', () { const Curve ease = Curves.ease; final Curve flippedEase = ease.flipped; expect(flippedEase.transform(0.0), lessThan(0.001)); expect(flippedEase.transform(0.5), lessThan(ease.transform(0.5))); expect(flippedEase.transform(1.0), greaterThan(0.999)); expect(flippedEase, hasOneLineDescription); });
test('Threshold has a threshold', () { const Curve step = Threshold(0.25); expect(step.transform(0.0), 0.0); expect(step.transform(0.24), 0.0); expect(step.transform(0.25), 1.0); expect(step.transform(0.26), 1.0); expect(step.transform(1.0), 1.0); });
void assertMaximumSlope(Curve curve, double maximumSlope) { const double delta = 0.005; for (double x = 0.0; x < 1.0 - delta; x += delta) { final double deltaY = curve.transform(x) - curve.transform(x + delta); assert(deltaY.abs() < delta * maximumSlope, '$curve discontinuous at $x'); } }
test('Curve is continuous', () { assertMaximumSlope(Curves.linear, 20.0); assertMaximumSlope(Curves.decelerate, 20.0); assertMaximumSlope(Curves.fastOutSlowIn, 20.0); assertMaximumSlope(Curves.slowMiddle, 20.0); assertMaximumSlope(Curves.bounceIn, 20.0); assertMaximumSlope(Curves.bounceOut, 20.0); assertMaximumSlope(Curves.bounceInOut, 20.0); assertMaximumSlope(Curves.elasticOut, 20.0); assertMaximumSlope(Curves.elasticInOut, 20.0); assertMaximumSlope(Curves.ease, 20.0);
assertMaximumSlope(Curves.easeIn, 20.0); assertMaximumSlope(Curves.easeInSine, 20.0); assertMaximumSlope(Curves.easeInQuad, 20.0); assertMaximumSlope(Curves.easeInCubic, 20.0); assertMaximumSlope(Curves.easeInQuart, 20.0); assertMaximumSlope(Curves.easeInQuint, 20.0); assertMaximumSlope(Curves.easeInExpo, 20.0); assertMaximumSlope(Curves.easeInCirc, 20.0);
assertMaximumSlope(Curves.easeOut, 20.0); assertMaximumSlope(Curves.easeOutSine, 20.0); assertMaximumSlope(Curves.easeOutQuad, 20.0); assertMaximumSlope(Curves.easeOutCubic, 20.0); assertMaximumSlope(Curves.easeInOutCubicEmphasized, 20.0); assertMaximumSlope(Curves.easeOutQuart, 20.0); assertMaximumSlope(Curves.easeOutQuint, 20.0); assertMaximumSlope(Curves.easeOutExpo, 20.0); assertMaximumSlope(Curves.easeOutCirc, 20.0);
// Curves.easeInOutExpo is discontinuous at its midpoint, so not included // here
assertMaximumSlope(Curves.easeInOut, 20.0); assertMaximumSlope(Curves.easeInOutSine, 20.0); assertMaximumSlope(Curves.easeInOutQuad, 20.0); assertMaximumSlope(Curves.easeInOutCubic, 20.0); assertMaximumSlope(Curves.easeInOutQuart, 20.0); assertMaximumSlope(Curves.easeInOutQuint, 20.0); assertMaximumSlope(Curves.easeInOutCirc, 20.0); });
void expectStaysInBounds(Curve curve) { expect(curve.transform(0.0), inInclusiveRange(0.0, 1.0)); expect(curve.transform(0.1), inInclusiveRange(0.0, 1.0)); expect(curve.transform(0.2), inInclusiveRange(0.0, 1.0)); expect(curve.transform(0.3), inInclusiveRange(0.0, 1.0)); expect(curve.transform(0.4), inInclusiveRange(0.0, 1.0)); expect(curve.transform(0.5), inInclusiveRange(0.0, 1.0)); expect(curve.transform(0.6), inInclusiveRange(0.0, 1.0)); expect(curve.transform(0.7), inInclusiveRange(0.0, 1.0)); expect(curve.transform(0.8), inInclusiveRange(0.0, 1.0)); expect(curve.transform(0.9), inInclusiveRange(0.0, 1.0)); expect(curve.transform(1.0), inInclusiveRange(0.0, 1.0)); }
test('Bounce stays in bounds', () { expectStaysInBounds(Curves.bounceIn); expectStaysInBounds(Curves.bounceOut); expectStaysInBounds(Curves.bounceInOut); });
List<double> estimateBounds(Curve curve) { final List<double> values = <double>[ curve.transform(0.0), curve.transform(0.1), curve.transform(0.2), curve.transform(0.3), curve.transform(0.4), curve.transform(0.5), curve.transform(0.6), curve.transform(0.7), curve.transform(0.8), curve.transform(0.9), curve.transform(1.0), ];
return <double>[ values.reduce(math.min), values.reduce(math.max), ]; }
test('Elastic overshoots its bounds', () { expect(Curves.elasticIn, hasOneLineDescription); expect(Curves.elasticOut, hasOneLineDescription); expect(Curves.elasticInOut, hasOneLineDescription);
List<double> bounds; bounds = estimateBounds(Curves.elasticIn); expect(bounds[0], lessThan(0.0)); expect(bounds[1], lessThanOrEqualTo(1.0)); bounds = estimateBounds(Curves.elasticOut); expect(bounds[0], greaterThanOrEqualTo(0.0)); expect(bounds[1], greaterThan(1.0)); bounds = estimateBounds(Curves.elasticInOut); expect(bounds[0], lessThan(0.0)); expect(bounds[1], greaterThan(1.0)); });
test('Back overshoots its bounds', () { expect(Curves.easeInBack, hasOneLineDescription); expect(Curves.easeOutBack, hasOneLineDescription); expect(Curves.easeInOutBack, hasOneLineDescription);
List<double> bounds; bounds = estimateBounds(Curves.easeInBack); expect(bounds[0], lessThan(0.0)); expect(bounds[1], lessThanOrEqualTo(1.0)); bounds = estimateBounds(Curves.easeOutBack); expect(bounds[0], greaterThanOrEqualTo(0.0)); expect(bounds[1], greaterThan(1.0)); bounds = estimateBounds(Curves.easeInOutBack); expect(bounds[0], lessThan(0.0)); expect(bounds[1], greaterThan(1.0)); });
test('Decelerate does so', () { expect(Curves.decelerate, hasOneLineDescription);
final List<double> bounds = estimateBounds(Curves.decelerate); expect(bounds[0], greaterThanOrEqualTo(0.0)); expect(bounds[1], lessThanOrEqualTo(1.0));
final double d1 = Curves.decelerate.transform(0.2) - Curves.decelerate.transform(0.0); final double d2 = Curves.decelerate.transform(1.0) - Curves.decelerate.transform(0.8); expect(d2, lessThan(d1)); });
test('ThreePointCubic interpolates midpoint', () { const ThreePointCubic test = ThreePointCubic( Offset(0.05, 0), Offset(0.133333, 0.06), Offset(0.166666, 0.4), Offset(0.208333, 0.82), Offset(0.25, 1), ); expect(test.transform(0.166666), equals(0.4)); });
test('Invalid transform parameter should assert', () { expect(() => const SawTooth(2).transform(-0.0001), throwsAssertionError); expect(() => const SawTooth(2).transform(1.0001), throwsAssertionError);
expect(() => const Interval(0.0, 1.0).transform(-0.0001), throwsAssertionError); expect(() => const Interval(0.0, 1.0).transform(1.0001), throwsAssertionError);
expect(() => const Threshold(0.5).transform(-0.0001), throwsAssertionError); expect(() => const Threshold(0.5).transform(1.0001), throwsAssertionError);
expect(() => const ElasticInCurve().transform(-0.0001), throwsAssertionError); expect(() => const ElasticInCurve().transform(1.0001), throwsAssertionError);
expect(() => const ElasticOutCurve().transform(-0.0001), throwsAssertionError); expect(() => const ElasticOutCurve().transform(1.0001), throwsAssertionError);
expect(() => const Cubic(0.42, 0.0, 0.58, 1.0).transform(-0.0001), throwsAssertionError); expect(() => const Cubic(0.42, 0.0, 0.58, 1.0).transform(1.0001), throwsAssertionError);
expect(() => Curves.easeInOutCubicEmphasized.transform(-0.0001), throwsAssertionError); expect(() => Curves.easeInOutCubicEmphasized.transform(1.0001), throwsAssertionError);
expect(() => Curves.decelerate.transform(-0.0001), throwsAssertionError); expect(() => Curves.decelerate.transform(1.0001), throwsAssertionError);
expect(() => Curves.bounceIn.transform(-0.0001), throwsAssertionError); expect(() => Curves.bounceIn.transform(1.0001), throwsAssertionError);
expect(() => Curves.bounceOut.transform(-0.0001), throwsAssertionError); expect(() => Curves.bounceOut.transform(1.0001), throwsAssertionError);
expect(() => Curves.bounceInOut.transform(-0.0001), throwsAssertionError); expect(() => Curves.bounceInOut.transform(1.0001), throwsAssertionError); });
test('Curve transform method should return 0.0 for t=0.0 and 1.0 for t=1.0', () { expect(const SawTooth(2).transform(0), 0); expect(const SawTooth(2).transform(1), 1);
expect(const Interval(0, 1).transform(0), 0); expect(const Interval(0, 1).transform(1), 1);
expect(const Threshold(0.5).transform(0), 0); expect(const Threshold(0.5).transform(1), 1);
expect(const ElasticInCurve().transform(0), 0); expect(const ElasticInCurve().transform(1), 1);
expect(const ElasticOutCurve().transform(0), 0); expect(const ElasticOutCurve().transform(1), 1);
expect(const ElasticInOutCurve().transform(0), 0); expect(const ElasticInOutCurve().transform(1), 1);
expect(Curves.linear.transform(0), 0); expect(Curves.linear.transform(1), 1);
expect(Curves.easeInOutExpo.transform(0), 0); expect(Curves.easeInOutExpo.transform(1), 1);
expect(Curves.easeInOutCubicEmphasized.transform(0), 0); expect(Curves.easeInOutCubicEmphasized.transform(1), 1);
expect(const FlippedCurve(Curves.easeInOutExpo).transform(0), 0); expect(const FlippedCurve(Curves.easeInOutExpo).transform(1), 1);
expect(Curves.decelerate.transform(0), 0); expect(Curves.decelerate.transform(1), 1);
expect(Curves.bounceIn.transform(0), 0); expect(Curves.bounceIn.transform(1), 1);
expect(Curves.bounceOut.transform(0), 0); expect(Curves.bounceOut.transform(1), 1);
expect(Curves.bounceInOut.transform(0), 0); expect(Curves.bounceInOut.transform(1), 1); });
test('CatmullRomSpline interpolates values properly', () { final CatmullRomSpline curve = CatmullRomSpline( const <Offset>[ Offset.zero, Offset(0.01, 0.25), Offset(0.2, 0.25), Offset(0.33, 0.25), Offset(0.5, 1.0), Offset(0.66, 0.75), Offset(1.0, 1.0), ], startHandle: const Offset(0.0, -0.3), endHandle: const Offset(1.3, 1.3), ); const double tolerance = 1e-6; expect(curve.transform(0.0).dx, moreOrLessEquals(0.0, epsilon: tolerance)); expect(curve.transform(0.0).dy, moreOrLessEquals(0.0, epsilon: tolerance)); expect(curve.transform(0.25).dx, moreOrLessEquals(0.0966945, epsilon: tolerance)); expect(curve.transform(0.25).dy, moreOrLessEquals(0.2626806, epsilon: tolerance)); expect(curve.transform(0.5).dx, moreOrLessEquals(0.33, epsilon: tolerance)); expect(curve.transform(0.5).dy, moreOrLessEquals(0.25, epsilon: tolerance)); expect(curve.transform(0.75).dx, moreOrLessEquals(0.570260, epsilon: tolerance)); expect(curve.transform(0.75).dy, moreOrLessEquals(0.883085, epsilon: tolerance)); expect(curve.transform(1.0).dx, moreOrLessEquals(1.0, epsilon: tolerance)); expect(curve.transform(1.0).dy, moreOrLessEquals(1.0, epsilon: tolerance)); });
test('CatmullRomSpline enforces contract', () { expect(() { CatmullRomSpline(const <Offset>[]); }, throwsAssertionError); expect(() { CatmullRomSpline(const <Offset>[Offset.zero]); }, throwsAssertionError); expect(() { CatmullRomSpline(const <Offset>[Offset.zero, Offset.zero]); }, throwsAssertionError); expect(() { CatmullRomSpline(const <Offset>[Offset.zero, Offset.zero, Offset.zero]); }, throwsAssertionError); expect(() { CatmullRomSpline(const <Offset>[Offset.zero, Offset.zero, Offset.zero, Offset.zero], tension: -1.0); }, throwsAssertionError); expect(() { CatmullRomSpline(const <Offset>[Offset.zero, Offset.zero, Offset.zero, Offset.zero], tension: 2.0); }, throwsAssertionError); expect(() { CatmullRomSpline( const <Offset>[Offset(double.infinity, 0.0), Offset.zero, Offset.zero, Offset.zero], ).generateSamples(); }, throwsAssertionError); expect(() { CatmullRomSpline( const <Offset>[Offset(0.0, double.infinity), Offset.zero, Offset.zero, Offset.zero], ).generateSamples(); }, throwsAssertionError); expect(() { CatmullRomSpline( startHandle: const Offset(0.0, double.infinity), const <Offset>[Offset.zero, Offset.zero, Offset.zero, Offset.zero], ).generateSamples(); }, throwsAssertionError); expect(() { CatmullRomSpline( endHandle: const Offset(0.0, double.infinity), const <Offset>[Offset.zero, Offset.zero, Offset.zero, Offset.zero], ).generateSamples(); }, throwsAssertionError); });
test('CatmullRomSpline interpolates values properly when precomputed', () { final CatmullRomSpline curve = CatmullRomSpline.precompute( const <Offset>[ Offset.zero, Offset(0.01, 0.25), Offset(0.2, 0.25), Offset(0.33, 0.25), Offset(0.5, 1.0), Offset(0.66, 0.75), Offset(1.0, 1.0), ], startHandle: const Offset(0.0, -0.3), endHandle: const Offset(1.3, 1.3), ); const double tolerance = 1e-6; expect(curve.transform(0.0).dx, moreOrLessEquals(0.0, epsilon: tolerance)); expect(curve.transform(0.0).dy, moreOrLessEquals(0.0, epsilon: tolerance)); expect(curve.transform(0.25).dx, moreOrLessEquals(0.0966945, epsilon: tolerance)); expect(curve.transform(0.25).dy, moreOrLessEquals(0.2626806, epsilon: tolerance)); expect(curve.transform(0.5).dx, moreOrLessEquals(0.33, epsilon: tolerance)); expect(curve.transform(0.5).dy, moreOrLessEquals(0.25, epsilon: tolerance)); expect(curve.transform(0.75).dx, moreOrLessEquals(0.570260, epsilon: tolerance)); expect(curve.transform(0.75).dy, moreOrLessEquals(0.883085, epsilon: tolerance)); expect(curve.transform(1.0).dx, moreOrLessEquals(1.0, epsilon: tolerance)); expect(curve.transform(1.0).dy, moreOrLessEquals(1.0, epsilon: tolerance)); });
test('CatmullRomSpline enforces contract when precomputed', () { expect(() { CatmullRomSpline.precompute(const <Offset>[]); }, throwsAssertionError); expect(() { CatmullRomSpline.precompute(const <Offset>[Offset.zero]); }, throwsAssertionError); expect(() { CatmullRomSpline.precompute(const <Offset>[Offset.zero, Offset.zero]); }, throwsAssertionError); expect(() { CatmullRomSpline.precompute(const <Offset>[Offset.zero, Offset.zero, Offset.zero]); }, throwsAssertionError); expect(() { CatmullRomSpline.precompute(const <Offset>[Offset.zero, Offset.zero, Offset.zero, Offset.zero], tension: -1.0); }, throwsAssertionError); expect(() { CatmullRomSpline.precompute(const <Offset>[Offset.zero, Offset.zero, Offset.zero, Offset.zero], tension: 2.0); }, throwsAssertionError); expect(() { CatmullRomSpline.precompute(const <Offset>[Offset(double.infinity, 0.0), Offset.zero, Offset.zero, Offset.zero]); }, throwsAssertionError); expect(() { CatmullRomSpline.precompute(const <Offset>[Offset(0.0, double.infinity), Offset.zero, Offset.zero, Offset.zero]); }, throwsAssertionError); expect(() { CatmullRomSpline.precompute( startHandle: const Offset(0.0, double.infinity), const <Offset>[Offset.zero, Offset.zero, Offset.zero, Offset.zero], ); }, throwsAssertionError); expect(() { CatmullRomSpline.precompute( endHandle: const Offset(0.0, double.infinity), const <Offset>[Offset.zero, Offset.zero, Offset.zero, Offset.zero], ); }, throwsAssertionError); });
test('CatmullRomCurve interpolates given points correctly', () { final CatmullRomCurve curve = CatmullRomCurve( const <Offset>[ Offset(0.2, 0.25), Offset(0.33, 0.25), Offset(0.5, 1.0), Offset(0.8, 0.75), ], );
// These values are approximations. const double tolerance = 1e-6; expect(curve.transform(0.0), moreOrLessEquals(0.0, epsilon: tolerance)); expect(curve.transform(0.01), moreOrLessEquals(0.012874734350170863, epsilon: tolerance)); expect(curve.transform(0.2), moreOrLessEquals(0.24989646045277542, epsilon: tolerance)); expect(curve.transform(0.33), moreOrLessEquals(0.250037698527661, epsilon: tolerance)); expect(curve.transform(0.5), moreOrLessEquals(0.9999057323235939, epsilon: tolerance)); expect(curve.transform(0.6), moreOrLessEquals(0.9357294964536621, epsilon: tolerance)); expect(curve.transform(0.8), moreOrLessEquals(0.7500423402378034, epsilon: tolerance)); expect(curve.transform(1.0), moreOrLessEquals(1.0, epsilon: tolerance)); });
test('CatmullRomCurve interpolates given points correctly when precomputed', () { final CatmullRomCurve curve = CatmullRomCurve.precompute( const <Offset>[ Offset(0.2, 0.25), Offset(0.33, 0.25), Offset(0.5, 1.0), Offset(0.8, 0.75), ], );
// These values are approximations. const double tolerance = 1e-6; expect(curve.transform(0.0), moreOrLessEquals(0.0, epsilon: tolerance)); expect(curve.transform(0.01), moreOrLessEquals(0.012874734350170863, epsilon: tolerance)); expect(curve.transform(0.2), moreOrLessEquals(0.24989646045277542, epsilon: tolerance)); expect(curve.transform(0.33), moreOrLessEquals(0.250037698527661, epsilon: tolerance)); expect(curve.transform(0.5), moreOrLessEquals(0.9999057323235939, epsilon: tolerance)); expect(curve.transform(0.6), moreOrLessEquals(0.9357294964536621, epsilon: tolerance)); expect(curve.transform(0.8), moreOrLessEquals(0.7500423402378034, epsilon: tolerance)); expect(curve.transform(1.0), moreOrLessEquals(1.0, epsilon: tolerance)); });
test('CatmullRomCurve enforces contract', () { expect(() { CatmullRomCurve(const <Offset>[]); }, throwsAssertionError); expect(() { CatmullRomCurve(const <Offset>[Offset.zero]); }, throwsAssertionError); expect(() { CatmullRomCurve(const <Offset>[Offset.zero, Offset.zero]); }, throwsAssertionError);
// Monotonically increasing in X. expect( CatmullRomCurve.validateControlPoints( const <Offset>[ Offset(0.2, 0.25), Offset(0.01, 0.25), ], ), isFalse, ); expect(() { CatmullRomCurve( const <Offset>[ Offset(0.2, 0.25), Offset(0.01, 0.25), ], ); }, throwsAssertionError);
// X within range (0.0, 1.0). expect( CatmullRomCurve.validateControlPoints( const <Offset>[ Offset(0.2, 0.25), Offset(1.01, 0.25), ], ), isFalse, ); expect(() { CatmullRomCurve( const <Offset>[ Offset(0.2, 0.25), Offset(1.01, 0.25), ], ); }, throwsAssertionError);
// Not multi-valued in Y at x=0.0. expect( CatmullRomCurve.validateControlPoints( const <Offset>[ Offset(0.05, 0.50), Offset(0.50, 0.50), Offset(0.75, 0.75), ], ), isFalse, ); expect(() { CatmullRomCurve( const <Offset>[ Offset(0.05, 0.50), Offset(0.50, 0.50), Offset(0.75, 0.75), ], ); }, throwsAssertionError);
// Not multi-valued in Y at x=1.0. expect( CatmullRomCurve.validateControlPoints( const <Offset>[ Offset(0.25, 0.25), Offset(0.50, 0.50), Offset(0.95, 0.51), ], ), isFalse, ); expect(() { CatmullRomCurve( const <Offset>[ Offset(0.25, 0.25), Offset(0.50, 0.50), Offset(0.95, 0.51), ], ); }, throwsAssertionError);
// Not multi-valued in Y in between x = 0.0 and x = 1.0. expect( CatmullRomCurve.validateControlPoints( const <Offset>[ Offset(0.5, 0.05), Offset(0.5, 0.95), ], ), isFalse, ); expect(() { CatmullRomCurve( const <Offset>[ Offset(0.5, 0.05), Offset(0.5, 0.95), ], ); }, throwsAssertionError); });
test('CatmullRomCurve enforces contract when precomputed', () { expect(() { CatmullRomCurve.precompute(const <Offset>[]); }, throwsAssertionError); expect(() { CatmullRomCurve.precompute(const <Offset>[Offset.zero]); }, throwsAssertionError); expect(() { CatmullRomCurve.precompute(const <Offset>[Offset.zero, Offset.zero]); }, throwsAssertionError);
// Monotonically increasing in X. expect(() { CatmullRomCurve.precompute( const <Offset>[ Offset(0.2, 0.25), Offset(0.01, 0.25), ], ); }, throwsAssertionError);
// X within range (0.0, 1.0). expect(() { CatmullRomCurve.precompute( const <Offset>[ Offset(0.2, 0.25), Offset(1.01, 0.25), ], ); }, throwsAssertionError);
// Not multi-valued in Y at x=0.0. expect(() { CatmullRomCurve.precompute( const <Offset>[ Offset(0.05, 0.50), Offset(0.50, 0.50), Offset(0.75, 0.75), ], ); }, throwsAssertionError);
// Not multi-valued in Y at x=1.0. expect(() { CatmullRomCurve.precompute( const <Offset>[ Offset(0.25, 0.25), Offset(0.50, 0.50), Offset(0.95, 0.51), ], ); }, throwsAssertionError);
// Not multi-valued in Y in between x = 0.0 and x = 1.0. expect(() { CatmullRomCurve.precompute( const <Offset>[ Offset(0.5, 0.05), Offset(0.5, 0.95), ], ); }, throwsAssertionError); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189// 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/widgets.dart';import 'package:flutter_test/flutter_test.dart';
void main() { testWidgets('awaiting animation controllers - using direct future', (WidgetTester tester) async { final AnimationController controller1 = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); addTearDown(controller1.dispose); final AnimationController controller2 = AnimationController( duration: const Duration(milliseconds: 600), vsync: const TestVSync(), ); addTearDown(controller2.dispose); final AnimationController controller3 = AnimationController( duration: const Duration(milliseconds: 300), vsync: const TestVSync(), ); addTearDown(controller3.dispose); final List<String> log = <String>[]; Future<void> runTest() async { log.add('a'); // t=0 await controller1.forward(); // starts at t=0 again log.add('b'); // wants to end at t=100 but missed frames until t=150 await controller2.forward(); // starts at t=150 log.add('c'); // wants to end at t=750 but missed frames until t=799 await controller3.forward(); // starts at t=799 log.add('d'); // wants to end at t=1099 but missed frames until t=1200 } log.add('start'); runTest().then((void value) { log.add('end'); }); await tester.pump(); // t=0 expect(log, <String>['start', 'a']); await tester.pump(); // t=0 again expect(log, <String>['start', 'a']); await tester.pump(const Duration(milliseconds: 50)); // t=50 expect(log, <String>['start', 'a']); await tester.pump(const Duration(milliseconds: 100)); // t=150 expect(log, <String>['start', 'a', 'b']); await tester.pump(const Duration(milliseconds: 50)); // t=200 expect(log, <String>['start', 'a', 'b']); await tester.pump(const Duration(milliseconds: 400)); // t=600 expect(log, <String>['start', 'a', 'b']); await tester.pump(const Duration(milliseconds: 199)); // t=799 expect(log, <String>['start', 'a', 'b', 'c']); await tester.pump(const Duration(milliseconds: 51)); // t=850 expect(log, <String>['start', 'a', 'b', 'c']); await tester.pump(const Duration(milliseconds: 400)); // t=1200 expect(log, <String>['start', 'a', 'b', 'c', 'd', 'end']); await tester.pump(const Duration(milliseconds: 400)); // t=1600 expect(log, <String>['start', 'a', 'b', 'c', 'd', 'end']); });
testWidgets('awaiting animation controllers - using orCancel', (WidgetTester tester) async { final AnimationController controller1 = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); addTearDown(controller1.dispose); final AnimationController controller2 = AnimationController( duration: const Duration(milliseconds: 600), vsync: const TestVSync(), ); addTearDown(controller2.dispose); final AnimationController controller3 = AnimationController( duration: const Duration(milliseconds: 300), vsync: const TestVSync(), ); addTearDown(controller3.dispose); final List<String> log = <String>[]; Future<void> runTest() async { log.add('a'); // t=0 await controller1.forward().orCancel; // starts at t=0 again log.add('b'); // wants to end at t=100 but missed frames until t=150 await controller2.forward().orCancel; // starts at t=150 log.add('c'); // wants to end at t=750 but missed frames until t=799 await controller3.forward().orCancel; // starts at t=799 log.add('d'); // wants to end at t=1099 but missed frames until t=1200 } log.add('start'); runTest().then((void value) { log.add('end'); }); await tester.pump(); // t=0 expect(log, <String>['start', 'a']); await tester.pump(); // t=0 again expect(log, <String>['start', 'a']); await tester.pump(const Duration(milliseconds: 50)); // t=50 expect(log, <String>['start', 'a']); await tester.pump(const Duration(milliseconds: 100)); // t=150 expect(log, <String>['start', 'a', 'b']); await tester.pump(const Duration(milliseconds: 50)); // t=200 expect(log, <String>['start', 'a', 'b']); await tester.pump(const Duration(milliseconds: 400)); // t=600 expect(log, <String>['start', 'a', 'b']); await tester.pump(const Duration(milliseconds: 199)); // t=799 expect(log, <String>['start', 'a', 'b', 'c']); await tester.pump(const Duration(milliseconds: 51)); // t=850 expect(log, <String>['start', 'a', 'b', 'c']); await tester.pump(const Duration(milliseconds: 400)); // t=1200 expect(log, <String>['start', 'a', 'b', 'c', 'd', 'end']); await tester.pump(const Duration(milliseconds: 400)); // t=1600 expect(log, <String>['start', 'a', 'b', 'c', 'd', 'end']); });
testWidgets('awaiting animation controllers and failing', (WidgetTester tester) async { final AnimationController controller1 = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); final List<String> log = <String>[]; Future<void> runTest() async { try { log.add('start'); await controller1.forward().orCancel; log.add('fail'); } on TickerCanceled { log.add('caught'); } } runTest().then((void value) { log.add('end'); }); await tester.pump(); // start ticker expect(log, <String>['start']); await tester.pump(const Duration(milliseconds: 50)); expect(log, <String>['start']); controller1.dispose(); expect(log, <String>['start']); await tester.idle(); expect(log, <String>['start', 'caught', 'end']); });
testWidgets('creating orCancel future later', (WidgetTester tester) async { final AnimationController controller1 = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); addTearDown(controller1.dispose); final TickerFuture f = controller1.forward(); await tester.pump(); // start ticker await tester.pump(const Duration(milliseconds: 200)); // end ticker await f; // should be a no-op await f.orCancel; // should create a resolved future expect(true, isTrue); // should reach here });
testWidgets('creating orCancel future later', (WidgetTester tester) async { final AnimationController controller1 = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); addTearDown(controller1.dispose); final TickerFuture f = controller1.forward(); await tester.pump(); // start ticker controller1.stop(); // cancel ticker bool ok = false; try { await f.orCancel; // should create a resolved future } on TickerCanceled { ok = true; } expect(ok, isTrue); // should reach here });
testWidgets('TickerFuture is a Future', (WidgetTester tester) async { final AnimationController controller1 = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); addTearDown(controller1.dispose); final TickerFuture f = controller1.forward(); await tester.pump(); // start ticker await tester.pump(const Duration(milliseconds: 200)); // end ticker expect(f.asStream().single, isA<Future<void>>()); await f.catchError((dynamic e) { throw 'do not reach'; }); expect(await f.then<bool>((_) => true), isTrue); expect(f.whenComplete(() => false), isA<Future<void>>()); expect(f.timeout(const Duration(seconds: 5)), isA<Future<void>>()); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129// 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() { setUp(() { WidgetsFlutterBinding.ensureInitialized(); WidgetsBinding.instance.resetEpoch(); });
test('AnimationController with mutating listener', () { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); final List<String> log = <String>[];
void listener1() { log.add('listener1'); } void listener3() { log.add('listener3'); } void listener4() { log.add('listener4'); } void listener2() { log.add('listener2'); controller.removeListener(listener1); controller.removeListener(listener3); controller.addListener(listener4); }
controller.addListener(listener1); controller.addListener(listener2); controller.addListener(listener3); controller.value = 0.2; expect(log, <String>['listener1', 'listener2']); log.clear();
controller.value = 0.3; expect(log, <String>['listener2', 'listener4']); log.clear();
controller.value = 0.4; expect(log, <String>['listener2', 'listener4', 'listener4']); log.clear(); });
test('AnimationController with mutating status listener', () { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); final List<String> log = <String>[];
void listener1(AnimationStatus status) { log.add('listener1'); } void listener3(AnimationStatus status) { log.add('listener3'); } void listener4(AnimationStatus status) { log.add('listener4'); } void listener2(AnimationStatus status) { log.add('listener2'); controller.removeStatusListener(listener1); controller.removeStatusListener(listener3); controller.addStatusListener(listener4); }
controller.addStatusListener(listener1); controller.addStatusListener(listener2); controller.addStatusListener(listener3); controller.forward(); expect(log, <String>['listener1', 'listener2']); log.clear();
controller.reverse(); expect(log, <String>['listener2', 'listener4']); log.clear();
controller.forward(); expect(log, <String>['listener2', 'listener4', 'listener4']); log.clear();
controller.dispose(); });
testWidgets('AnimationController with throwing listener', (WidgetTester tester) async { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); addTearDown(controller.dispose); final List<String> log = <String>[];
void listener1() { log.add('listener1'); } void badListener() { log.add('badListener'); throw ArgumentError(); } void listener2() { log.add('listener2'); }
controller.addListener(listener1); controller.addListener(badListener); controller.addListener(listener2); controller.value = 0.2; expect(log, <String>['listener1', 'badListener', 'listener2']); expect(tester.takeException(), isArgumentError); log.clear(); });
testWidgets('AnimationController with throwing status listener', (WidgetTester tester) async { final AnimationController controller = AnimationController( duration: const Duration(milliseconds: 100), vsync: const TestVSync(), ); final List<String> log = <String>[];
void listener1(AnimationStatus status) { log.add('listener1'); } void badListener(AnimationStatus status) { log.add('badListener'); throw ArgumentError(); } void listener2(AnimationStatus status) { log.add('listener2'); }
controller.addStatusListener(listener1); controller.addStatusListener(badListener); controller.addStatusListener(listener2); controller.forward(); expect(log, <String>['listener1', 'badListener', 'listener2']); expect(tester.takeException(), isArgumentError); log.clear(); controller.dispose(); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354// 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() { test('AnimationLocalStatusListenersMixin with AnimationLazyListenerMixin - removing unregistered listener is no-op', () { final _TestAnimationLocalStatusListeners uut = _TestAnimationLocalStatusListeners(); void fakeListener(AnimationStatus status) { } uut.removeStatusListener(fakeListener); expect(uut.callsToStart, 0); expect(uut.callsToStop, 0); });
test('AnimationLocalListenersMixin with AnimationLazyListenerMixin - removing unregistered listener is no-op', () { final _TestAnimationLocalListeners uut = _TestAnimationLocalListeners(); void fakeListener() { } uut.removeListener(fakeListener); expect(uut.callsToStart, 0); expect(uut.callsToStop, 0); });}
class _TestAnimationLocalStatusListeners with AnimationLocalStatusListenersMixin, AnimationLazyListenerMixin { int callsToStart = 0; int callsToStop = 0;
@override void didStartListening() { callsToStart += 1; }
@override void didStopListening() { callsToStop += 1; }}
class _TestAnimationLocalListeners with AnimationLocalListenersMixin, AnimationLazyListenerMixin { int callsToStart = 0; int callsToStop = 0;
@override void didStartListening() { callsToStart += 1; }
@override void didStopListening() { callsToStop += 1; }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140// 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/material.dart';import 'package:flutter_test/flutter_test.dart';
void main() { /* * Here lies golden tests for packages/flutter_test/lib/src/binding.dart * because [matchesGoldenFile] does not use Skia Gold in its native package. */
LiveTestWidgetsFlutterBinding().framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.onlyPumps;
testWidgets('Should show event indicator for pointer events', (WidgetTester tester) async { final AnimationSheetBuilder animationSheet = AnimationSheetBuilder(frameSize: const Size(200, 200), allLayers: true); addTearDown(animationSheet.dispose); final List<Offset> taps = <Offset>[]; Widget target({bool recording = true}) => Container( padding: const EdgeInsets.fromLTRB(20, 10, 25, 20), child: animationSheet.record( MaterialApp( home: Container( decoration: BoxDecoration( color: const Color.fromARGB(255, 128, 128, 128), border: Border.all(), ), child: Center( child: Container( width: 40, height: 40, color: Colors.black, child: GestureDetector( onTapDown: (TapDownDetails details) { taps.add(details.globalPosition); }, ), ), ), ), ), recording: recording, ), );
await tester.pumpWidget(target(recording: false));
await tester.pumpFrames(target(), const Duration(milliseconds: 50));
final TestGesture gesture1 = await tester.createGesture(pointer: 1); await gesture1.down(tester.getCenter(find.byType(GestureDetector)) + const Offset(10, 10)); expect(taps, equals(const <Offset>[Offset(130, 120)])); taps.clear();
await tester.pumpFrames(target(), const Duration(milliseconds: 100));
final TestGesture gesture2 = await tester.createGesture(pointer: 2); await gesture2.down(tester.getTopLeft(find.byType(GestureDetector)) + const Offset(30, -10)); await gesture1.moveBy(const Offset(50, 50));
await tester.pumpFrames(target(), const Duration(milliseconds: 100)); await gesture1.up(); await gesture2.up(); await tester.pumpFrames(target(), const Duration(milliseconds: 50)); expect(taps, isEmpty);
await expectLater( animationSheet.collate(6), matchesGoldenFile('LiveBinding.press.animation.png'), ); // Currently skipped due to daily flake: https://github.com/flutter/flutter/issues/87588 }, skip: true); // Typically skip: isBrowser https://github.com/flutter/flutter/issues/42767
testWidgets('Should show event indicator for pointer events with setSurfaceSize', (WidgetTester tester) async { final AnimationSheetBuilder animationSheet = AnimationSheetBuilder(frameSize: const Size(200, 200), allLayers: true); addTearDown(animationSheet.dispose); final List<Offset> taps = <Offset>[]; Widget target({bool recording = true}) => Container( padding: const EdgeInsets.fromLTRB(20, 10, 25, 20), child: animationSheet.record( MaterialApp( home: Container( decoration: BoxDecoration( color: const Color.fromARGB(255, 128, 128, 128), border: Border.all(), ), child: Center( child: Container( width: 40, height: 40, color: Colors.black, child: GestureDetector( onTapDown: (TapDownDetails details) { taps.add(details.globalPosition); }, ), ), ), ), ), recording: recording, ), );
await tester.binding.setSurfaceSize(const Size(300, 300)); await tester.pumpWidget(target(recording: false));
await tester.pumpFrames(target(), const Duration(milliseconds: 50));
final TestGesture gesture1 = await tester.createGesture(pointer: 1); await gesture1.down(tester.getCenter(find.byType(GestureDetector)) + const Offset(10, 10)); expect(taps, equals(const <Offset>[Offset(130, 120)])); taps.clear();
await tester.pumpFrames(target(), const Duration(milliseconds: 100));
final TestGesture gesture2 = await tester.createGesture(pointer: 2); await gesture2.down(tester.getTopLeft(find.byType(GestureDetector)) + const Offset(30, -10)); await gesture1.moveBy(const Offset(50, 50));
await tester.pumpFrames(target(), const Duration(milliseconds: 100)); await gesture1.up(); await gesture2.up(); await tester.pumpFrames(target(), const Duration(milliseconds: 50)); expect(taps, isEmpty);
await expectLater( animationSheet.collate(6), matchesGoldenFile('LiveBinding.press.animation.2.png'), ); }, skip: isBrowser, // [intended] https://github.com/flutter/flutter/issues/56001 );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222// 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 String kApiDocsLink = 'See "Types with special considerations" at https://api.flutter.dev/flutter/animation/Tween-class.html for more information.';
void main() { test('throws flutter error when tweening types that do not fully satisfy tween requirements - Object', () { final Tween<Object> objectTween = Tween<Object>( begin: Object(), end: Object(), );
expect( () => objectTween.transform(0.1), throwsA(isA<FlutterError>().having( (FlutterError error) => error.diagnostics.map((DiagnosticsNode node) => node.toString()), 'diagnostics', <String>[ 'Cannot lerp between "Instance of \'Object\'" and "Instance of \'Object\'".', 'The type Object might not fully implement `+`, `-`, and/or `*`. $kApiDocsLink', 'There may be a dedicated "ObjectTween" for this type, or you may need to create one.', ], )), ); });
test('throws flutter error when tweening types that do not fully satisfy tween requirements - Color', () { final Tween<Color> colorTween = Tween<Color>( begin: const Color(0xFF000000), end: const Color(0xFFFFFFFF), );
expect( () => colorTween.transform(0.1), throwsA(isA<FlutterError>().having( (FlutterError error) => error.diagnostics.map((DiagnosticsNode node) => node.toString()), 'diagnostics', <String>[ 'Cannot lerp between "Color(0xff000000)" and "Color(0xffffffff)".', 'The type Color might not fully implement `+`, `-`, and/or `*`. $kApiDocsLink', 'To lerp colors, consider ColorTween instead.', ], )), ); });
test('throws flutter error when tweening types that do not fully satisfy tween requirements - Rect', () { final Tween<Rect> rectTween = Tween<Rect>( begin: const Rect.fromLTWH(0, 0, 10, 10), end: const Rect.fromLTWH(2, 2, 2, 2), );
expect( () => rectTween.transform(0.1), throwsA(isA<FlutterError>().having( (FlutterError error) => error.diagnostics.map((DiagnosticsNode node) => node.toString()), 'diagnostics', <String>[ 'Cannot lerp between "Rect.fromLTRB(0.0, 0.0, 10.0, 10.0)" and "Rect.fromLTRB(2.0, 2.0, 4.0, 4.0)".', 'The type Rect might not fully implement `+`, `-`, and/or `*`. $kApiDocsLink', 'To lerp rects, consider RectTween instead.', ], )), ); });
test('throws flutter error when tweening types that do not fully satisfy tween requirements - int', () { final Tween<int> colorTween = Tween<int>( begin: 0, end: 1, );
expect( () => colorTween.transform(0.1), throwsA(isA<FlutterError>().having( (FlutterError error) => error.diagnostics.map((DiagnosticsNode node) => node.toString()), 'diagnostics', <String>[ 'Cannot lerp between "0" and "1".', 'The type int returned a double after multiplication with a double value. $kApiDocsLink', 'To lerp int values, consider IntTween or StepTween instead.', ], )), ); });
test('Can chain tweens', () { final Tween<double> tween = Tween<double>(begin: 0.30, end: 0.50); expect(tween, hasOneLineDescription); final Animatable<double> chain = tween.chain(Tween<double>(begin: 0.50, end: 1.0)); final AnimationController controller = AnimationController( vsync: const TestVSync(), ); expect(chain.evaluate(controller), 0.40); expect(chain, hasOneLineDescription); });
test('Can animate tweens', () { final Tween<double> tween = Tween<double>(begin: 0.30, end: 0.50); final AnimationController controller = AnimationController( vsync: const TestVSync(), ); final Animation<double> animation = tween.animate(controller); controller.value = 0.50; expect(animation.value, 0.40); expect(animation, hasOneLineDescription); expect(animation.toStringDetails(), hasOneLineDescription); });
test('Can drive tweens', () { final Tween<double> tween = Tween<double>(begin: 0.30, end: 0.50); final AnimationController controller = AnimationController( vsync: const TestVSync(), ); final Animation<double> animation = controller.drive(tween); controller.value = 0.50; expect(animation.value, 0.40); expect(animation, hasOneLineDescription); expect(animation.toStringDetails(), hasOneLineDescription); });
test('BorderTween nullable test', () { BorderTween tween = BorderTween(); expect(tween.lerp(0.0), null); expect(tween.lerp(1.0), null);
tween = BorderTween(end: const Border(top: BorderSide())); expect(tween.lerp(0.0), const Border()); expect(tween.lerp(0.5), const Border(top: BorderSide(width: 0.5))); expect(tween.lerp(1.0), const Border(top: BorderSide())); });
test('SizeTween', () { final SizeTween tween = SizeTween(begin: Size.zero, end: const Size(20.0, 30.0)); expect(tween.lerp(0.5), equals(const Size(10.0, 15.0))); expect(tween, hasOneLineDescription); });
test('IntTween', () { final IntTween tween = IntTween(begin: 5, end: 9); expect(tween.lerp(0.5), 7); expect(tween.lerp(0.7), 8); });
test('RectTween', () { const Rect a = Rect.fromLTWH(5.0, 3.0, 7.0, 11.0); const Rect b = Rect.fromLTWH(8.0, 12.0, 14.0, 18.0); final RectTween tween = RectTween(begin: a, end: b); expect(tween.lerp(0.5), equals(Rect.lerp(a, b, 0.5))); expect(tween, hasOneLineDescription); });
test('Matrix4Tween', () { final Matrix4 a = Matrix4.identity(); final Matrix4 b = a.clone()..translate(6.0, -8.0)..scale(0.5, 1.0, 5.0); final Matrix4Tween tween = Matrix4Tween(begin: a, end: b); expect(tween.lerp(0.0), equals(a)); expect(tween.lerp(1.0), equals(b)); expect( tween.lerp(0.5), equals(a.clone()..translate(3.0, -4.0)..scale(0.75, 1.0, 3.0)), ); final Matrix4 c = a.clone()..rotateZ(1.0); final Matrix4Tween rotationTween = Matrix4Tween(begin: a, end: c); expect(rotationTween.lerp(0.0), equals(a)); expect(rotationTween.lerp(1.0), equals(c)); expect( rotationTween.lerp(0.5).absoluteError(a.clone()..rotateZ(0.5)), moreOrLessEquals(0.0), ); });
test('ConstantTween', () { final ConstantTween<double> tween = ConstantTween<double>(100.0); expect(tween.begin, 100.0); expect(tween.end, 100.0); expect(tween.lerp(0.0), 100.0); expect(tween.lerp(0.5), 100.0); expect(tween.lerp(1.0), 100.0); });
test('ReverseTween', () { final ReverseTween<int> tween = ReverseTween<int>(IntTween(begin: 5, end: 9)); expect(tween.lerp(0.5), 7); expect(tween.lerp(0.7), 6); });
test('ColorTween', () { final ColorTween tween = ColorTween( begin: const Color(0xff000000), end: const Color(0xffffffff), ); expect(tween.lerp(0.0), const Color(0xff000000)); expect(tween.lerp(0.5), const Color(0xff7f7f7f)); expect(tween.lerp(0.7), const Color(0xffb2b2b2)); expect(tween.lerp(1.0), const Color(0xffffffff)); });
test('StepTween', () { final StepTween tween = StepTween(begin: 5, end: 9); expect(tween.lerp(0.5), 7); expect(tween.lerp(0.7), 7); });
test('CurveTween', () { final CurveTween tween = CurveTween(curve: Curves.easeIn); expect(tween.transform(0.0), 0.0); expect(tween.transform(0.5), 0.31640625); expect(tween.transform(1.0), 1.0); });
test('BorderRadiusTween nullable test', () { final BorderRadiusTween tween = BorderRadiusTween(); expect(tween.transform(0.0), null); expect(tween.transform(1.0), null); expect(tween.lerp(0.0), null); });}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144// 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/foundation.dart';import 'package:flutter/gestures.dart';import 'package:flutter/material.dart';import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
void main() { testWidgets('Verify that a tap on modal barrier dismisses an action sheet', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( const CupertinoActionSheet( title: Text('Action Sheet'), ), ), );
await tester.tap(find.text('Go')); await tester.pump();
expect(find.text('Action Sheet'), findsOneWidget);
await tester.tapAt(const Offset(20.0, 20.0)); await tester.pump(); expect(find.text('Action Sheet'), findsNothing); });
testWidgets('Verify that a tap on title section (not buttons) does not dismiss an action sheet', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( const CupertinoActionSheet( title: Text('Action Sheet'), ), ), );
await tester.tap(find.text('Go')); await tester.pump(); await tester.pump(const Duration(seconds: 5));
expect(find.text('Action Sheet'), findsOneWidget);
await tester.tap(find.text('Action Sheet')); await tester.pump(); expect(find.text('Action Sheet'), findsOneWidget); });
testWidgets('Action sheet destructive text style', (WidgetTester tester) async { await tester.pumpWidget( boilerplate( CupertinoActionSheetAction( isDestructiveAction: true, child: const Text('Ok'), onPressed: () { }, ), ), );
final DefaultTextStyle widget = tester.widget(find.widgetWithText(DefaultTextStyle, 'Ok'));
expect(widget.style.color, const CupertinoDynamicColor.withBrightnessAndContrast( color: Color.fromARGB(255, 255, 59, 48), darkColor: Color.fromARGB(255, 255, 69, 58), highContrastColor: Color.fromARGB(255, 215, 0, 21), darkHighContrastColor: Color.fromARGB(255, 255, 105, 97), )); });
testWidgets('Action sheet dark mode', (WidgetTester tester) async { final Widget action = CupertinoActionSheetAction( child: const Text('action'), onPressed: () {}, );
Brightness brightness = Brightness.light; late StateSetter stateSetter;
TextStyle actionTextStyle(String text) { return tester.widget<DefaultTextStyle>( find.descendant( of: find.widgetWithText(CupertinoActionSheetAction, text), matching: find.byType(DefaultTextStyle), ), ).style; }
await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( StatefulBuilder( builder: (BuildContext context, StateSetter setter) { stateSetter = setter; return CupertinoTheme( data: CupertinoThemeData( brightness: brightness, primaryColor: const CupertinoDynamicColor.withBrightnessAndContrast( color: Color.fromARGB(255, 0, 122, 255), darkColor: Color.fromARGB(255, 10, 132, 255), highContrastColor: Color.fromARGB(255, 0, 64, 221), darkHighContrastColor: Color.fromARGB(255, 64, 156, 255), ), ), child: CupertinoActionSheet(actions: <Widget>[action]), ); }, ), ), );
await tester.tap(find.text('Go')); await tester.pump();
expect( actionTextStyle('action').color!.value, const Color.fromARGB(255, 0, 122, 255).value, );
stateSetter(() { brightness = Brightness.dark; }); await tester.pump();
expect( actionTextStyle('action').color!.value, const Color.fromARGB(255, 10, 132, 255).value, ); });
testWidgets('Action sheet default text style', (WidgetTester tester) async { await tester.pumpWidget( boilerplate( CupertinoActionSheetAction( isDefaultAction: true, child: const Text('Ok'), onPressed: () { }, ), ), );
final DefaultTextStyle widget = tester.widget(find.widgetWithText(DefaultTextStyle, 'Ok'));
expect(widget.style.fontWeight, equals(FontWeight.w600)); });
testWidgets('Action sheet text styles are correct when both title and message are included', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( const CupertinoActionSheet( title: Text('Action Sheet'), message: Text('An action sheet'), ), ), );
await tester.tap(find.text('Go')); await tester.pump();
final DefaultTextStyle titleStyle = tester.firstWidget(find.widgetWithText(DefaultTextStyle, 'Action Sheet')); final DefaultTextStyle messageStyle = tester.firstWidget(find.widgetWithText(DefaultTextStyle, 'An action sheet'));
expect(titleStyle.style.fontWeight, FontWeight.w600); expect(messageStyle.style.fontWeight, FontWeight.w400); });
testWidgets('Action sheet text styles are correct when title but no message is included', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( const CupertinoActionSheet( title: Text('Action Sheet'), ), ), );
await tester.tap(find.text('Go')); await tester.pump();
final DefaultTextStyle titleStyle = tester.firstWidget(find.widgetWithText(DefaultTextStyle, 'Action Sheet'));
expect(titleStyle.style.fontWeight, FontWeight.w400); });
testWidgets('Action sheet text styles are correct when message but no title is included', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( const CupertinoActionSheet( message: Text('An action sheet'), ), ), );
await tester.tap(find.text('Go')); await tester.pump();
final DefaultTextStyle messageStyle = tester.firstWidget(find.widgetWithText(DefaultTextStyle, 'An action sheet'));
expect(messageStyle.style.fontWeight, FontWeight.w600); });
testWidgets('Content section but no actions', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: const Text('The message.'), messageScrollController: scrollController, ), ), );
await tester.tap(find.text('Go'));
await tester.pump(); await tester.pump(const Duration(seconds: 1));
// Content section should be at the bottom left of action sheet // (minus padding). expect( tester.getBottomLeft(find.byType(ClipRRect)), tester.getBottomLeft(find.byType(CupertinoActionSheet)) - const Offset(-8.0, 10.0), );
// Check that the dialog size is the same as the content section size // (minus padding). expect( tester.getSize(find.byType(ClipRRect)).height, tester.getSize(find.byType(CupertinoActionSheet)).height - 20.0, );
expect( tester.getSize(find.byType(ClipRRect)).width, tester.getSize(find.byType(CupertinoActionSheet)).width - 16.0, ); });
testWidgets('Actions but no content section', (WidgetTester tester) async { final ScrollController actionScrollController = ScrollController(); addTearDown(actionScrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], actionScrollController: actionScrollController, ), ), );
await tester.tap(find.text('Go'));
await tester.pump(); await tester.pump(const Duration(seconds: 1));
final Finder finder = find.byElementPredicate( (Element element) { return element.widget.runtimeType.toString() == '_CupertinoAlertActionSection'; }, );
// Check that the title/message section is not displayed (action section is // at the top of the action sheet + padding). expect( tester.getTopLeft(finder), tester.getTopLeft(find.byType(CupertinoActionSheet)) + const Offset(8.0, 10.0), );
expect( tester.getTopLeft(find.byType(CupertinoActionSheet)) + const Offset(8.0, 10.0), tester.getTopLeft(find.widgetWithText(CupertinoActionSheetAction, 'One')), ); expect( tester.getBottomLeft(find.byType(CupertinoActionSheet)) + const Offset(8.0, -10.0), tester.getBottomLeft(find.widgetWithText(CupertinoActionSheetAction, 'Two')), ); });
testWidgets('Action section is scrollable', (WidgetTester tester) async { final ScrollController actionScrollController = ScrollController(); addTearDown(actionScrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( Builder(builder: (BuildContext context) { return MediaQuery( data: MediaQuery.of(context).copyWith(textScaleFactor: 3.0), child: CupertinoActionSheet( title: const Text('The title'), message: const Text('The message.'), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Three'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Four'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Five'), onPressed: () { }, ), ], actionScrollController: actionScrollController, ), ); }), ), );
await tester.tap(find.text('Go'));
await tester.pump(); await tester.pump(const Duration(seconds: 1));
// Check that the action buttons list is scrollable. expect(actionScrollController.offset, 0.0); actionScrollController.jumpTo(100.0); expect(actionScrollController.offset, 100.0); actionScrollController.jumpTo(0.0);
// Check that the action buttons are aligned vertically. expect(tester.getCenter(find.widgetWithText(CupertinoActionSheetAction, 'One')).dx, equals(400.0)); expect(tester.getCenter(find.widgetWithText(CupertinoActionSheetAction, 'Two')).dx, equals(400.0)); expect(tester.getCenter(find.widgetWithText(CupertinoActionSheetAction, 'Three')).dx, equals(400.0)); expect(tester.getCenter(find.widgetWithText(CupertinoActionSheetAction, 'Four')).dx, equals(400.0)); expect(tester.getCenter(find.widgetWithText(CupertinoActionSheetAction, 'Five')).dx, equals(400.0));
// Check that the action buttons are the correct heights. expect(tester.getSize(find.widgetWithText(CupertinoActionSheetAction, 'One')).height, equals(83.0)); expect(tester.getSize(find.widgetWithText(CupertinoActionSheetAction, 'Two')).height, equals(83.0)); expect(tester.getSize(find.widgetWithText(CupertinoActionSheetAction, 'Three')).height, equals(83.0)); expect(tester.getSize(find.widgetWithText(CupertinoActionSheetAction, 'Four')).height, equals(83.0)); expect(tester.getSize(find.widgetWithText(CupertinoActionSheetAction, 'Five')).height, equals(83.0)); });
testWidgets('Content section is scrollable', (WidgetTester tester) async { final ScrollController messageScrollController = ScrollController(); addTearDown(messageScrollController.dispose); late double screenHeight; await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( Builder(builder: (BuildContext context) { screenHeight = MediaQuery.sizeOf(context).height; return MediaQuery( data: MediaQuery.of(context).copyWith(textScaleFactor: 3.0), child: CupertinoActionSheet( title: const Text('The title'), message: Text('Very long content' * 200), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], messageScrollController: messageScrollController, ), ); }), ), );
await tester.tap(find.text('Go')); await tester.pump();
expect(messageScrollController.offset, 0.0); messageScrollController.jumpTo(100.0); expect(messageScrollController.offset, 100.0); // Set the scroll position back to zero. messageScrollController.jumpTo(0.0);
// Expect the action sheet to take all available height. expect(tester.getSize(find.byType(CupertinoActionSheet)).height, screenHeight); });
testWidgets('CupertinoActionSheet scrollbars controllers should be different', (WidgetTester tester) async { // https://github.com/flutter/flutter/pull/81278 await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: Text('Very long content' * 200), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), ], ) ), );
await tester.tap(find.text('Go')); await tester.pump();
final List<CupertinoScrollbar> scrollbars = find.descendant( of: find.byType(CupertinoActionSheet), matching: find.byType(CupertinoScrollbar), ).evaluate().map((Element e) => e.widget as CupertinoScrollbar).toList();
expect(scrollbars.length, 2); expect(scrollbars[0].controller != scrollbars[1].controller, isTrue); });
testWidgets('Tap on button calls onPressed', (WidgetTester tester) async { bool wasPressed = false; await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( Builder(builder: (BuildContext context) { return CupertinoActionSheet( actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { wasPressed = true; Navigator.pop(context); }, ), ], ); }), ), );
await tester.tap(find.text('Go'));
await tester.pump(); await tester.pump(const Duration(seconds: 1));
expect(wasPressed, isFalse);
await tester.tap(find.text('One'));
expect(wasPressed, isTrue);
await tester.pump(); await tester.pump(const Duration(seconds: 1));
expect(find.text('One'), findsNothing); });
testWidgets('Action sheet width is correct when given infinite horizontal space', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( Row( children: <Widget>[ CupertinoActionSheet( actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], ), ], ), ), );
await tester.tap(find.text('Go')); await tester.pump();
expect(tester.getSize(find.byType(CupertinoActionSheet)).width, 600.0); });
testWidgets('Action sheet height is correct when given infinite vertical space', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( Column( children: <Widget>[ CupertinoActionSheet( actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], ), ], ), ), );
await tester.tap(find.text('Go')); await tester.pump();
expect(tester.getSize(find.byType(CupertinoActionSheet)).height, moreOrLessEquals(132.3)); });
testWidgets('1 action button with cancel button', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: Text('Very long content' * 200), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), ], cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { }, ), ), ), );
await tester.tap(find.text('Go')); await tester.pump();
// Action section is size of one action button. expect(findScrollableActionsSectionRenderBox(tester).size.height, 56.0); });
testWidgets('2 action buttons with cancel button', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: Text('Very long content' * 200), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { }, ), ), ), );
await tester.tap(find.text('Go')); await tester.pump();
expect(findScrollableActionsSectionRenderBox(tester).size.height, moreOrLessEquals(112.3)); });
testWidgets('3 action buttons with cancel button', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: Text('Very long content' * 200), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Three'), onPressed: () { }, ), ], cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { }, ), ), ), );
await tester.tap(find.text('Go')); await tester.pump();
expect(findScrollableActionsSectionRenderBox(tester).size.height, moreOrLessEquals(168.6)); });
testWidgets('4+ action buttons with cancel button', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: Text('Very long content' * 200), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Three'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Four'), onPressed: () { }, ), ], cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { }, ), ), ), );
await tester.tap(find.text('Go')); await tester.pump();
expect(findScrollableActionsSectionRenderBox(tester).size.height, moreOrLessEquals(84.3)); });
testWidgets('1 action button without cancel button', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: Text('Very long content' * 200), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), ], ), ), );
await tester.tap(find.text('Go')); await tester.pump();
expect(findScrollableActionsSectionRenderBox(tester).size.height, 56.0); });
testWidgets('2+ action buttons without cancel button', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: Text('Very long content' * 200), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], ), ), );
await tester.tap(find.text('Go')); await tester.pump();
expect(findScrollableActionsSectionRenderBox(tester).size.height, moreOrLessEquals(84.3)); });
testWidgets('Action sheet with just cancel button is correct', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { }, ), ), ), );
await tester.tap(find.text('Go')); await tester.pump();
// Height should be cancel button height + padding expect(tester.getSize(find.byType(CupertinoActionSheet)).height, 76.0); expect(tester.getSize(find.byType(CupertinoActionSheet)).width, 600.0); });
testWidgets('Cancel button tap calls onPressed', (WidgetTester tester) async { bool wasPressed = false; await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( Builder(builder: (BuildContext context) { return CupertinoActionSheet( cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { wasPressed = true; Navigator.pop(context); }, ), ); }), ), );
await tester.tap(find.text('Go'));
await tester.pump(); await tester.pump(const Duration(seconds: 1));
expect(wasPressed, isFalse);
await tester.tap(find.text('Cancel'));
expect(wasPressed, isTrue);
await tester.pump(); await tester.pump(const Duration(seconds: 1));
expect(find.text('Cancel'), findsNothing); });
testWidgets('Layout is correct when cancel button is present', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: const Text('The message'), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { }, ), ), ), );
await tester.tap(find.text('Go'));
await tester.pump(); await tester.pump(const Duration(seconds: 1));
expect(tester.getBottomLeft(find.widgetWithText(CupertinoActionSheetAction, 'Cancel')).dy, 590.0); expect( tester.getBottomLeft(find.widgetWithText(CupertinoActionSheetAction, 'One')).dy, moreOrLessEquals(469.7), ); expect(tester.getBottomLeft(find.widgetWithText(CupertinoActionSheetAction, 'Two')).dy, 526.0); });
testWidgets('Enter/exit animation is correct', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: const Text('The message'), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { }, ), ), ), );
// Enter animation await tester.tap(find.text('Go'));
await tester.pump(); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, 600.0);
await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(483.9, epsilon: 0.1));
await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(398.6, epsilon: 0.1));
await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(365.3, epsilon: 0.1));
await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(354.8, epsilon: 0.1));
await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(350.7, epsilon: 0.1));
await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(349.4, epsilon: 0.1));
// Action sheet has reached final height await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(349.4, epsilon: 0.1));
// Exit animation await tester.tapAt(const Offset(20.0, 20.0)); await tester.pump(); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(349.4, epsilon: 0.1));
await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(465.5, epsilon: 0.1));
await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(550.8, epsilon: 0.1));
await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(584.1, epsilon: 0.1));
await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(594.6, epsilon: 0.1));
await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(598.7, epsilon: 0.1));
// Action sheet has disappeared await tester.pump(const Duration(milliseconds: 60)); expect(find.byType(CupertinoActionSheet), findsNothing); });
testWidgets('Modal barrier is pressed during transition', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: const Text('The message'), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { }, ), ), ), );
// Enter animation await tester.tap(find.text('Go'));
await tester.pump(); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, 600.0);
await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(483.92863239836686, epsilon: 0.1));
await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(398.5571539306641, epsilon: 0.1));
await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(365.3034101784229, epsilon: 0.1));
// Exit animation await tester.tapAt(const Offset(20.0, 20.0)); await tester.pump(const Duration(milliseconds: 60));
await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(398.5571539306641, epsilon: 0.1));
await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, moreOrLessEquals(483.92863239836686, epsilon: 0.1));
await tester.pump(const Duration(milliseconds: 60)); expect(tester.getTopLeft(find.byType(CupertinoActionSheet)).dy, 600.0);
// Action sheet has disappeared await tester.pump(const Duration(milliseconds: 60)); expect(find.byType(CupertinoActionSheet), findsNothing); });
testWidgets('Action sheet semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: const Text('The message'), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], cancelButton: CupertinoActionSheetAction( child: const Text('Cancel'), onPressed: () { }, ), ), ), );
await tester.tap(find.text('Go')); await tester.pumpAndSettle();
expect( semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.scopesRoute, SemanticsFlag.namesRoute, ], label: 'Alert', children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.hasImplicitScrolling, ], children: <TestSemantics>[ TestSemantics( label: 'The title', ), TestSemantics( label: 'The message', ), ], ), TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.hasImplicitScrolling, ], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.isButton, ], actions: <SemanticsAction>[ SemanticsAction.tap, ], label: 'One', ), TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.isButton, ], actions: <SemanticsAction>[ SemanticsAction.tap, ], label: 'Two', ), ], ), TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.isButton, ], actions: <SemanticsAction>[ SemanticsAction.tap, ], label: 'Cancel', ), ], ), ], ), ], ), ], ), ignoreId: true, ignoreRect: true, ignoreTransform: true, ), );
semantics.dispose(); });
testWidgets('Conflicting scrollbars are not applied by ScrollBehavior to CupertinoActionSheet', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/83819 final ScrollController actionScrollController = ScrollController(); addTearDown(actionScrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( Builder(builder: (BuildContext context) { return MediaQuery( data: MediaQuery.of(context).copyWith(textScaleFactor: 3.0), child: CupertinoActionSheet( title: const Text('The title'), message: const Text('The message.'), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), CupertinoActionSheetAction( child: const Text('Two'), onPressed: () { }, ), ], actionScrollController: actionScrollController, ), ); }), ), );
await tester.tap(find.text('Go')); await tester.pump();
// The inherited ScrollBehavior should not apply Scrollbars since they are // already built in to the widget. expect(find.byType(Scrollbar), findsNothing); expect(find.byType(RawScrollbar), findsNothing); // Built in CupertinoScrollbars should only number 2: one for the actions, // one for the content. expect(find.byType(CupertinoScrollbar), findsNWidgets(2)); }, variant: TargetPlatformVariant.all());
testWidgets('Hovering over Cupertino action sheet action updates cursor to clickable on Web', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesActionSheet( CupertinoActionSheet( title: const Text('The title'), message: const Text('Message'), actions: <Widget>[ CupertinoActionSheetAction( child: const Text('One'), onPressed: () { }, ), ], ) ), ); await tester.tap(find.text('Go')); await tester.pump();
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); await gesture.addPointer(location: const Offset(10, 10)); await tester.pumpAndSettle(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
final Offset actionSheetAction = tester.getCenter(find.text('One')); await gesture.moveTo(actionSheetAction); await tester.pumpAndSettle(); expect( RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), kIsWeb ? SystemMouseCursors.click : SystemMouseCursors.basic, ); });}
RenderBox findScrollableActionsSectionRenderBox(WidgetTester tester) { final RenderObject actionsSection = tester.renderObject( find.byElementPredicate((Element element) { return element.widget.runtimeType.toString() == '_CupertinoAlertActionSection'; }), ); assert(actionsSection is RenderBox); return actionsSection as RenderBox;}
Widget createAppWithButtonThatLaunchesActionSheet(Widget actionSheet) { return CupertinoApp( home: Center( child: Builder(builder: (BuildContext context) { return CupertinoButton( onPressed: () { showCupertinoModalPopup<void>( context: context, builder: (BuildContext context) { return actionSheet; }, ); }, child: const Text('Go'), ); }), ), );}
Widget boilerplate(Widget child) { return Directionality( textDirection: TextDirection.ltr, child: child, );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195// 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/scheduler.dart';import 'package:flutter_test/flutter_test.dart';
void main() { testWidgets('Activity indicator animate property works', (WidgetTester tester) async { await tester.pumpWidget(buildCupertinoActivityIndicator()); expect(SchedulerBinding.instance.transientCallbackCount, equals(1));
await tester.pumpWidget(buildCupertinoActivityIndicator(false)); expect(SchedulerBinding.instance.transientCallbackCount, equals(0));
await tester.pumpWidget(Container());
await tester.pumpWidget(buildCupertinoActivityIndicator(false)); expect(SchedulerBinding.instance.transientCallbackCount, equals(0));
await tester.pumpWidget(buildCupertinoActivityIndicator()); expect(SchedulerBinding.instance.transientCallbackCount, equals(1)); });
testWidgets('Activity indicator dark mode', (WidgetTester tester) async { final Key key = UniqueKey(); await tester.pumpWidget( Center( child: MediaQuery( data: const MediaQueryData(), child: RepaintBoundary( key: key, child: const ColoredBox( color: CupertinoColors.white, child: CupertinoActivityIndicator( animating: false, radius: 35, ), ), ), ), ), );
await expectLater( find.byKey(key), matchesGoldenFile('activityIndicator.paused.light.png'), );
await tester.pumpWidget( Center( child: MediaQuery( data: const MediaQueryData(platformBrightness: Brightness.dark), child: RepaintBoundary( key: key, child: const ColoredBox( color: CupertinoColors.black, child: CupertinoActivityIndicator( animating: false, radius: 35, ), ), ), ), ), );
await expectLater( find.byKey(key), matchesGoldenFile('activityIndicator.paused.dark.png'), ); });
testWidgets('Activity indicator 0% in progress', (WidgetTester tester) async { final Key key = UniqueKey(); await tester.pumpWidget( Center( child: RepaintBoundary( key: key, child: const ColoredBox( color: CupertinoColors.white, child: CupertinoActivityIndicator.partiallyRevealed( progress: 0, ), ), ), ), );
await expectLater( find.byKey(key), matchesGoldenFile('activityIndicator.inprogress.0.0.png'), ); });
testWidgets('Activity indicator 30% in progress', (WidgetTester tester) async { final Key key = UniqueKey(); await tester.pumpWidget( Center( child: RepaintBoundary( key: key, child: const ColoredBox( color: CupertinoColors.white, child: CupertinoActivityIndicator.partiallyRevealed( progress: 0.5, ), ), ), ), );
await expectLater( find.byKey(key), matchesGoldenFile('activityIndicator.inprogress.0.3.png'), ); });
testWidgets('Activity indicator 100% in progress', (WidgetTester tester) async { final Key key = UniqueKey(); await tester.pumpWidget( Center( child: RepaintBoundary( key: key, child: const ColoredBox( color: CupertinoColors.white, child: CupertinoActivityIndicator.partiallyRevealed(), ), ), ), );
await expectLater( find.byKey(key), matchesGoldenFile('activityIndicator.inprogress.1.0.png'), ); });
// Regression test for https://github.com/flutter/flutter/issues/41345. testWidgets('has the correct corner radius', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoActivityIndicator(animating: false, radius: 100), );
// An earlier implementation for the activity indicator started drawing // the ticks at 9 o'clock, however, in order to support partially revealed // indicator (https://github.com/flutter/flutter/issues/29159), the // first tick was changed to be at 12 o'clock. expect( find.byType(CupertinoActivityIndicator), paints ..rrect(rrect: const RRect.fromLTRBXY(-10, -100 / 3, 10, -100, 10, 10)), ); });
testWidgets('Can specify color', (WidgetTester tester) async { final Key key = UniqueKey(); await tester.pumpWidget( Center( child: RepaintBoundary( key: key, child: const ColoredBox( color: CupertinoColors.white, child: CupertinoActivityIndicator( animating: false, color: Color(0xFF5D3FD3), radius: 100, ), ), ), ), );
expect( find.byType(CupertinoActivityIndicator), paints ..rrect(rrect: const RRect.fromLTRBXY(-10, -100 / 3, 10, -100, 10, 10), color: const Color(0x935d3fd3)), ); });}
Widget buildCupertinoActivityIndicator([bool? animating]) { return MediaQuery( data: const MediaQueryData(), child: CupertinoActivityIndicator( animating: animating ?? true, ), );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282// 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/foundation.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';
import '../widgets/clipboard_utils.dart';import '../widgets/live_text_utils.dart';import '../widgets/text_selection_toolbar_utils.dart';
void main() { final MockClipboard mockClipboard = MockClipboard();
setUp(() async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( SystemChannels.platform, mockClipboard.handleMethodCall, ); // Fill the clipboard so that the Paste option is available in the text // selection menu. await Clipboard.setData(const ClipboardData(text: 'Clipboard data')); });
tearDown(() { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler( SystemChannels.platform, null, ); });
testWidgets('Builds the right toolbar on each platform, including web, and shows buttonItems', (WidgetTester tester) async { const String buttonText = 'Click me';
await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoAdaptiveTextSelectionToolbar.buttonItems( anchors: const TextSelectionToolbarAnchors( primaryAnchor: Offset.zero, ), buttonItems: <ContextMenuButtonItem>[ ContextMenuButtonItem( label: buttonText, onPressed: () { }, ), ], ), ), ), );
expect(find.text(buttonText), findsOneWidget);
switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.iOS: expect(find.byType(CupertinoTextSelectionToolbar), findsOneWidget); expect(find.byType(CupertinoDesktopTextSelectionToolbar), findsNothing); case TargetPlatform.macOS: case TargetPlatform.linux: case TargetPlatform.windows: expect(find.byType(CupertinoTextSelectionToolbar), findsNothing); expect(find.byType(CupertinoDesktopTextSelectionToolbar), findsOneWidget); } }, variant: TargetPlatformVariant.all(), skip: isBrowser, // [intended] see https://github.com/flutter/flutter/issues/108382 );
testWidgets('Can build children directly as well', (WidgetTester tester) async { final GlobalKey key = GlobalKey();
await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoAdaptiveTextSelectionToolbar( anchors: const TextSelectionToolbarAnchors( primaryAnchor: Offset.zero, ), children: <Widget>[ Container(key: key), ], ), ), ), );
expect(find.byKey(key), findsOneWidget); }, skip: isBrowser, // [intended] see https://github.com/flutter/flutter/issues/108382 );
testWidgets('Can build from EditableTextState', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose); await tester.pumpWidget(CupertinoApp( home: Align( alignment: Alignment.topLeft, child: SizedBox( width: 400, child: EditableText( controller: controller, backgroundCursorColor: const Color(0xff00ffff), focusNode: focusNode, style: const TextStyle(), cursorColor: const Color(0xff00ffff), selectionControls: cupertinoTextSelectionHandleControls, contextMenuBuilder: ( BuildContext context, EditableTextState editableTextState, ) { return CupertinoAdaptiveTextSelectionToolbar.editableText( key: key, editableTextState: editableTextState, ); }, ), ), ), ));
await tester.pump(); // Wait for autofocus to take effect.
expect(find.byKey(key), findsNothing);
// Long-press to bring up the context menu. final Finder textFinder = find.byType(EditableText); await tester.longPress(textFinder); tester.state<EditableTextState>(textFinder).showToolbar(); await tester.pumpAndSettle();
expect(find.byKey(key), findsOneWidget); expect(find.text('Copy'), findsNothing); expect(find.text('Cut'), findsNothing); expect(find.text('Select all'), findsNothing); expect(find.text('Paste'), findsOneWidget);
switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.iOS: expect(find.byType(CupertinoTextSelectionToolbarButton), findsOneWidget); case TargetPlatform.macOS: case TargetPlatform.linux: case TargetPlatform.windows: expect(find.byType(CupertinoDesktopTextSelectionToolbarButton), findsOneWidget); } }, skip: kIsWeb, // [intended] on web the browser handles the context menu. variant: TargetPlatformVariant.all(), );
testWidgets('Can build for editable text from raw parameters', (WidgetTester tester) async { final GlobalKey key = GlobalKey(); await tester.pumpWidget(CupertinoApp( home: Center( child: CupertinoAdaptiveTextSelectionToolbar.editable( key: key, anchors: const TextSelectionToolbarAnchors( primaryAnchor: Offset.zero, ), clipboardStatus: ClipboardStatus.pasteable, onCopy: () {}, onCut: () {}, onPaste: () {}, onSelectAll: () {}, onLiveTextInput: () {}, onLookUp: () {}, onSearchWeb: () {}, onShare: () {}, ), ), ));
expect(find.byKey(key), findsOneWidget);
switch (defaultTargetPlatform) { case TargetPlatform.android: expect(find.byType(CupertinoTextSelectionToolbarButton), findsNWidgets(6)); expect(find.text('Cut'), findsOneWidget); expect(find.text('Copy'), findsOneWidget); expect(find.text('Paste'), findsOneWidget); expect(find.text('Select All'), findsOneWidget); expect(find.text('Share...'), findsOneWidget); expect(findCupertinoOverflowNextButton(), findsOneWidget);
await tapCupertinoOverflowNextButton(tester);
expect(find.byType(CupertinoTextSelectionToolbarButton), findsNWidgets(4)); expect(findCupertinoOverflowBackButton(), findsOneWidget); expect(find.text('Look Up'), findsOneWidget); expect(find.text('Search Web'), findsOneWidget); expect(findLiveTextButton(), findsOneWidget);
case TargetPlatform.fuchsia: case TargetPlatform.iOS: expect(find.byType(CupertinoTextSelectionToolbarButton), findsNWidgets(6)); expect(find.text('Cut'), findsOneWidget); expect(find.text('Copy'), findsOneWidget); expect(find.text('Paste'), findsOneWidget); expect(find.text('Select All'), findsOneWidget); expect(find.text('Look Up'), findsOneWidget); expect(findCupertinoOverflowNextButton(), findsOneWidget);
await tapCupertinoOverflowNextButton(tester);
expect(find.byType(CupertinoTextSelectionToolbarButton), findsNWidgets(4)); expect(findCupertinoOverflowBackButton(), findsOneWidget); expect(find.text('Search Web'), findsOneWidget); expect(find.text('Share...'), findsOneWidget); expect(findLiveTextButton(), findsOneWidget);
case TargetPlatform.macOS: case TargetPlatform.linux: case TargetPlatform.windows: expect(find.byType(CupertinoDesktopTextSelectionToolbarButton), findsNWidgets(8)); expect(find.text('Cut'), findsOneWidget); expect(find.text('Copy'), findsOneWidget); expect(find.text('Paste'), findsOneWidget); expect(find.text('Select All'), findsOneWidget); expect(find.text('Share...'), findsOneWidget); expect(find.text('Look Up'), findsOneWidget); expect(find.text('Search Web'), findsOneWidget); expect(findLiveTextButton(), findsOneWidget); } }, skip: kIsWeb, // [intended] on web the browser handles the context menu. variant: TargetPlatformVariant.all(), );
testWidgets('Builds the correct button per-platform', (WidgetTester tester) async { const String buttonText = 'Click me';
await tester.pumpWidget( CupertinoApp( home: Center( child: Builder( builder: (BuildContext context) { return Column( children: CupertinoAdaptiveTextSelectionToolbar.getAdaptiveButtons( context, <ContextMenuButtonItem>[ ContextMenuButtonItem( label: buttonText, onPressed: () { }, ), ], ).toList(), ); }, ), ), ), );
expect(find.text(buttonText), findsOneWidget);
switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.iOS: expect(find.byType(CupertinoTextSelectionToolbarButton), findsOneWidget); expect(find.byType(CupertinoDesktopTextSelectionToolbarButton), findsNothing); case TargetPlatform.macOS: case TargetPlatform.linux: case TargetPlatform.windows: expect(find.byType(CupertinoTextSelectionToolbarButton), findsNothing); expect(find.byType(CupertinoDesktopTextSelectionToolbarButton), findsOneWidget); } }, variant: TargetPlatformVariant.all(), );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556// 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/foundation.dart';import 'package:flutter/rendering.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';
void main() { testWidgets('Heroes work', (WidgetTester tester) async { await tester.pumpWidget(CupertinoApp( home: ListView(children: <Widget>[ const Hero(tag: 'a', child: Text('foo')), Builder(builder: (BuildContext context) { return CupertinoButton( child: const Text('next'), onPressed: () { Navigator.push( context, CupertinoPageRoute<void>(builder: (BuildContext context) { return const Hero(tag: 'a', child: Text('foo')); }), ); }, ); }), ]), ));
await tester.tap(find.text('next')); await tester.pump(); await tester.pump(const Duration(milliseconds: 100));
// During the hero transition, the hero widget is lifted off of both // page routes and exists as its own overlay on top of both routes. expect(find.widgetWithText(CupertinoPageRoute, 'foo'), findsNothing); expect(find.widgetWithText(Navigator, 'foo'), findsOneWidget); });
testWidgets('Has default cupertino localizations', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Builder( builder: (BuildContext context) { return Column( children: <Widget>[ Text(CupertinoLocalizations.of(context).selectAllButtonLabel), Text(CupertinoLocalizations.of(context).datePickerMediumDate( DateTime(2018, 10, 4), )), ], ); }, ), ), );
expect(find.text('Select All'), findsOneWidget); expect(find.text('Thu Oct 4 '), findsOneWidget); });
testWidgets('Can use dynamic color', (WidgetTester tester) async { const CupertinoDynamicColor dynamicColor = CupertinoDynamicColor.withBrightness( color: Color(0xFF000000), darkColor: Color(0xFF000001), ); await tester.pumpWidget(const CupertinoApp( theme: CupertinoThemeData(brightness: Brightness.light), color: dynamicColor, home: Placeholder(), ));
expect(tester.widget<Title>(find.byType(Title)).color.value, 0xFF000000);
await tester.pumpWidget(const CupertinoApp( theme: CupertinoThemeData(brightness: Brightness.dark), color: dynamicColor, home: Placeholder(), ));
expect(tester.widget<Title>(find.byType(Title)).color.value, 0xFF000001); });
testWidgets('Can customize initial routes', (WidgetTester tester) async { final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>(); await tester.pumpWidget( CupertinoApp( navigatorKey: navigatorKey, onGenerateInitialRoutes: (String initialRoute) { expect(initialRoute, '/abc'); return <Route<void>>[ PageRouteBuilder<void>( pageBuilder: ( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, ) { return const Text('non-regular page one'); }, ), PageRouteBuilder<void>( pageBuilder: ( BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, ) { return const Text('non-regular page two'); }, ), ]; }, initialRoute: '/abc', routes: <String, WidgetBuilder>{ '/': (BuildContext context) => const Text('regular page one'), '/abc': (BuildContext context) => const Text('regular page two'), }, ), ); expect(find.text('non-regular page two'), findsOneWidget); expect(find.text('non-regular page one'), findsNothing); expect(find.text('regular page one'), findsNothing); expect(find.text('regular page two'), findsNothing); navigatorKey.currentState!.pop(); await tester.pumpAndSettle(); expect(find.text('non-regular page two'), findsNothing); expect(find.text('non-regular page one'), findsOneWidget); expect(find.text('regular page one'), findsNothing); expect(find.text('regular page two'), findsNothing); });
testWidgets('CupertinoApp.navigatorKey can be updated', (WidgetTester tester) async { final GlobalKey<NavigatorState> key1 = GlobalKey<NavigatorState>(); await tester.pumpWidget(CupertinoApp( navigatorKey: key1, home: const Placeholder(), )); expect(key1.currentState, isA<NavigatorState>()); final GlobalKey<NavigatorState> key2 = GlobalKey<NavigatorState>(); await tester.pumpWidget(CupertinoApp( navigatorKey: key2, home: const Placeholder(), )); expect(key2.currentState, isA<NavigatorState>()); expect(key1.currentState, isNull); });
testWidgets('CupertinoApp.router works', (WidgetTester tester) async { final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider( initialRouteInformation: RouteInformation( uri: Uri.parse('initial'), ), ); addTearDown(provider.dispose); final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate( builder: (BuildContext context, RouteInformation information) { return Text(information.uri.toString()); }, onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) { delegate.routeInformation = RouteInformation( uri: Uri.parse('popped'), ); return route.didPop(result); }, ); addTearDown(delegate.dispose); await tester.pumpWidget(CupertinoApp.router( routeInformationProvider: provider, routeInformationParser: SimpleRouteInformationParser(), routerDelegate: delegate, )); expect(find.text('initial'), findsOneWidget);
// Simulate android back button intent. final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute')); await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { }); await tester.pumpAndSettle(); expect(find.text('popped'), findsOneWidget); });
testWidgets('CupertinoApp.router route information parser is optional', (WidgetTester tester) async { final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate( builder: (BuildContext context, RouteInformation information) { return Text(information.uri.toString()); }, onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) { delegate.routeInformation = RouteInformation( uri: Uri.parse('popped'), ); return route.didPop(result); }, ); addTearDown(delegate.dispose); delegate.routeInformation = RouteInformation(uri: Uri.parse('initial')); await tester.pumpWidget(CupertinoApp.router( routerDelegate: delegate, )); expect(find.text('initial'), findsOneWidget);
// Simulate android back button intent. final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute')); await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { }); await tester.pumpAndSettle(); expect(find.text('popped'), findsOneWidget); });
testWidgets('CupertinoApp.router throw if route information provider is provided but no route information parser', (WidgetTester tester) async { final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate( builder: (BuildContext context, RouteInformation information) { return Text(information.uri.toString()); }, onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) { delegate.routeInformation = RouteInformation( uri: Uri.parse('popped'), ); return route.didPop(result); }, ); addTearDown(delegate.dispose); delegate.routeInformation = RouteInformation(uri: Uri.parse('initial')); final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider( initialRouteInformation: RouteInformation( uri: Uri.parse('initial'), ), ); addTearDown(provider.dispose); await tester.pumpWidget(CupertinoApp.router( routeInformationProvider: provider, routerDelegate: delegate, )); expect(tester.takeException(), isAssertionError); });
testWidgets('CupertinoApp.router throw if route configuration is provided along with other delegate', (WidgetTester tester) async { final SimpleNavigatorRouterDelegate delegate = SimpleNavigatorRouterDelegate( builder: (BuildContext context, RouteInformation information) { return Text(information.uri.toString()); }, onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) { delegate.routeInformation = RouteInformation( uri: Uri.parse('popped'), ); return route.didPop(result); }, ); addTearDown(delegate.dispose); delegate.routeInformation = RouteInformation(uri: Uri.parse('initial')); final RouterConfig<RouteInformation> routerConfig = RouterConfig<RouteInformation>(routerDelegate: delegate); await tester.pumpWidget(CupertinoApp.router( routerDelegate: delegate, routerConfig: routerConfig, )); expect(tester.takeException(), isAssertionError); });
testWidgets('CupertinoApp.router router config works', (WidgetTester tester) async { late SimpleNavigatorRouterDelegate delegate; addTearDown(() => delegate.dispose()); final PlatformRouteInformationProvider provider = PlatformRouteInformationProvider( initialRouteInformation: RouteInformation( uri: Uri.parse('initial'), ), ); addTearDown(provider.dispose); final RouterConfig<RouteInformation> routerConfig = RouterConfig<RouteInformation>( routeInformationProvider: provider, routeInformationParser: SimpleRouteInformationParser(), routerDelegate: delegate = SimpleNavigatorRouterDelegate( builder: (BuildContext context, RouteInformation information) { return Text(information.uri.toString()); }, onPopPage: (Route<void> route, void result, SimpleNavigatorRouterDelegate delegate) { delegate.routeInformation = RouteInformation( uri: Uri.parse('popped'), ); return route.didPop(result); }, ), backButtonDispatcher: RootBackButtonDispatcher() ); await tester.pumpWidget(CupertinoApp.router( routerConfig: routerConfig, )); expect(find.text('initial'), findsOneWidget);
// Simulate android back button intent. final ByteData message = const JSONMethodCodec().encodeMethodCall(const MethodCall('popRoute')); await tester.binding.defaultBinaryMessenger.handlePlatformMessage('flutter/navigation', message, (_) { }); await tester.pumpAndSettle(); expect(find.text('popped'), findsOneWidget); });
testWidgets('CupertinoApp has correct default ScrollBehavior', (WidgetTester tester) async { late BuildContext capturedContext; await tester.pumpWidget( CupertinoApp( home: Builder( builder: (BuildContext context) { capturedContext = context; return const Placeholder(); }, ), ), ); expect(ScrollConfiguration.of(capturedContext).runtimeType, CupertinoScrollBehavior); });
testWidgets('A ScrollBehavior can be set for CupertinoApp', (WidgetTester tester) async { late BuildContext capturedContext; await tester.pumpWidget( CupertinoApp( scrollBehavior: const MockScrollBehavior(), home: Builder( builder: (BuildContext context) { capturedContext = context; return const Placeholder(); }, ), ), ); final ScrollBehavior scrollBehavior = ScrollConfiguration.of(capturedContext); expect(scrollBehavior.runtimeType, MockScrollBehavior); expect(scrollBehavior.getScrollPhysics(capturedContext).runtimeType, NeverScrollableScrollPhysics); });
testWidgets('When `useInheritedMediaQuery` is true an existing MediaQuery is used if one is available', (WidgetTester tester) async { late BuildContext capturedContext; final UniqueKey uniqueKey = UniqueKey(); await tester.pumpWidget( MediaQuery( key: uniqueKey, data: const MediaQueryData(), child: CupertinoApp( useInheritedMediaQuery: true, builder: (BuildContext context, Widget? child) { capturedContext = context; return const Placeholder(); }, color: const Color(0xFF123456), ), ), ); expect(capturedContext.dependOnInheritedWidgetOfExactType<MediaQuery>()?.key, uniqueKey); });
testWidgets('Text color is correctly resolved when CupertinoThemeData.brightness is null', (WidgetTester tester) async { debugBrightnessOverride = Brightness.dark;
await tester.pumpWidget( const CupertinoApp( home: CupertinoPageScaffold( child: Text('Hello'), ), ), );
final RenderParagraph paragraph = tester.renderObject(find.text('Hello')); final CupertinoDynamicColor textColor = paragraph.text.style!.color! as CupertinoDynamicColor;
// App with non-null brightness, so resolving color // doesn't depend on the MediaQuery.platformBrightness. late BuildContext capturedContext; await tester.pumpWidget( CupertinoApp( theme: const CupertinoThemeData( brightness: Brightness.dark, ), home: Builder( builder: (BuildContext context) { capturedContext = context;
return const Placeholder(); }, ), ), );
// We expect the string representations of the colors to have darkColor indicated (*) as effective color. // (color = Color(0xff000000), *darkColor = Color(0xffffffff)*, resolved by: Builder) expect(textColor.toString(), CupertinoColors.label.resolveFrom(capturedContext).toString());
debugBrightnessOverride = null; });
testWidgets('Cursor color is resolved when CupertinoThemeData.brightness is null', (WidgetTester tester) async { debugBrightnessOverride = Brightness.dark;
RenderEditable findRenderEditable(WidgetTester tester) { final RenderObject root = tester.renderObject(find.byType(EditableText)); expect(root, isNotNull);
RenderEditable? renderEditable; void recursiveFinder(RenderObject child) { if (child is RenderEditable) { renderEditable = child; return; } child.visitChildren(recursiveFinder); }
root.visitChildren(recursiveFinder); expect(renderEditable, isNotNull); return renderEditable!; }
final FocusNode focusNode = FocusNode(); addTearDown(focusNode.dispose); final TextEditingController controller = TextEditingController(); addTearDown(controller.dispose);
await tester.pumpWidget( CupertinoApp( theme: const CupertinoThemeData( primaryColor: CupertinoColors.activeOrange, ), home: CupertinoPageScaffold( child: Builder( builder: (BuildContext context) { return EditableText( backgroundCursorColor: DefaultSelectionStyle.of(context).selectionColor!, cursorColor: DefaultSelectionStyle.of(context).cursorColor!, controller: controller, focusNode: focusNode, style: const TextStyle(), ); }, ), ), ), );
final RenderEditable editableText = findRenderEditable(tester); final Color cursorColor = editableText.cursorColor!;
// Cursor color should be equal to the dark variant of the primary color. // Alpha value needs to be 0, because cursor is not visible by default. expect(cursorColor, CupertinoColors.activeOrange.darkColor.withAlpha(0));
debugBrightnessOverride = null; });
testWidgets('Assert in buildScrollbar that controller != null when using it', (WidgetTester tester) async { const ScrollBehavior defaultBehavior = CupertinoScrollBehavior(); late BuildContext capturedContext;
await tester.pumpWidget(ScrollConfiguration( // Avoid the default ones here. behavior: const CupertinoScrollBehavior().copyWith(scrollbars: false), child: SingleChildScrollView( child: Builder( builder: (BuildContext context) { capturedContext = context; return Container(height: 1000.0); }, ), ), ));
const ScrollableDetails details = ScrollableDetails(direction: AxisDirection.down); final Widget child = Container();
switch (defaultTargetPlatform) { case TargetPlatform.android: case TargetPlatform.fuchsia: case TargetPlatform.iOS: // Does not throw if we aren't using it. defaultBehavior.buildScrollbar(capturedContext, child, details); case TargetPlatform.linux: case TargetPlatform.macOS: case TargetPlatform.windows: expect( () { defaultBehavior.buildScrollbar(capturedContext, child, details); }, throwsA( isA<AssertionError>().having((AssertionError error) => error.toString(), 'description', contains('details.controller != null')), ), ); } }, variant: TargetPlatformVariant.all());}
class MockScrollBehavior extends ScrollBehavior { const MockScrollBehavior();
@override ScrollPhysics getScrollPhysics(BuildContext context) => const NeverScrollableScrollPhysics();}
typedef SimpleRouterDelegateBuilder = Widget Function(BuildContext context, RouteInformation information);typedef SimpleNavigatorRouterDelegatePopPage<T> = bool Function(Route<T> route, T result, SimpleNavigatorRouterDelegate delegate);
class SimpleRouteInformationParser extends RouteInformationParser<RouteInformation> { SimpleRouteInformationParser();
@override Future<RouteInformation> parseRouteInformation(RouteInformation information) { return SynchronousFuture<RouteInformation>(information); }
@override RouteInformation restoreRouteInformation(RouteInformation configuration) { return configuration; }}
class SimpleNavigatorRouterDelegate extends RouterDelegate<RouteInformation> with PopNavigatorRouterDelegateMixin<RouteInformation>, ChangeNotifier { SimpleNavigatorRouterDelegate({ required this.builder, this.onPopPage, });
@override GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
RouteInformation get routeInformation => _routeInformation; late RouteInformation _routeInformation; set routeInformation(RouteInformation newValue) { _routeInformation = newValue; notifyListeners(); }
SimpleRouterDelegateBuilder builder; SimpleNavigatorRouterDelegatePopPage<void>? onPopPage;
@override Future<void> setNewRoutePath(RouteInformation configuration) { _routeInformation = configuration; return SynchronousFuture<void>(null); }
bool _handlePopPage(Route<void> route, void data) { return onPopPage!(route, data, this); }
@override Widget build(BuildContext context) { return Navigator( key: navigatorKey, onPopPage: _handlePopPage, pages: <Page<void>>[ // We need at least two pages for the pop to propagate through. // Otherwise, the navigator will bubble the pop to the system navigator. const CupertinoPage<void>( child: Text('base'), ), CupertinoPage<void>( key: ValueKey<String?>(routeInformation.uri.toString()), child: builder(context, routeInformation), ), ], ); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661// 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/foundation.dart';import 'package:flutter/gestures.dart';import 'package:flutter/rendering.dart';import 'package:flutter_test/flutter_test.dart';
import '../image_data.dart';import '../widgets/semantics_tester.dart';
Future<void> pumpWidgetWithBoilerplate(WidgetTester tester, Widget widget) async { await tester.pumpWidget( Localizations( locale: const Locale('en', 'US'), delegates: const <LocalizationsDelegate<dynamic>>[ DefaultWidgetsLocalizations.delegate, DefaultCupertinoLocalizations.delegate, ], child: Directionality( textDirection: TextDirection.ltr, child: widget, ), ), );}
Future<void> main() async {
testWidgets('Need at least 2 tabs', (WidgetTester tester) async { await expectLater( () => pumpWidgetWithBoilerplate(tester, CupertinoTabBar( items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 1', ), ], )), throwsA(isAssertionError.having( (AssertionError error) => error.toString(), '.toString()', contains('items.length'), )), ); });
testWidgets('Active and inactive colors', (WidgetTester tester) async { await pumpWidgetWithBoilerplate(tester, MediaQuery( data: const MediaQueryData(), child: CupertinoTabBar( items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 1', ), BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 2', ), ], currentIndex: 1, activeColor: const Color(0xFF123456), inactiveColor: const Color(0xFF654321), ), ));
final RichText actualInactive = tester.widget(find.descendant( of: find.text('Tab 1'), matching: find.byType(RichText), )); expect(actualInactive.text.style!.color, const Color(0xFF654321));
final RichText actualActive = tester.widget(find.descendant( of: find.text('Tab 2'), matching: find.byType(RichText), )); expect(actualActive.text.style!.color, const Color(0xFF123456)); });
testWidgets('BottomNavigationBar.label will create a text widget', (WidgetTester tester) async { await pumpWidgetWithBoilerplate(tester, MediaQuery( data: const MediaQueryData(), child: CupertinoTabBar( items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 1', ), BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 2', ), ], currentIndex: 1, ), ));
expect(find.text('Tab 1'), findsOneWidget); expect(find.text('Tab 2'), findsOneWidget); });
testWidgets('Active and inactive colors dark mode', (WidgetTester tester) async { const CupertinoDynamicColor dynamicActiveColor = CupertinoDynamicColor.withBrightness( color: Color(0xFF000000), darkColor: Color(0xFF000001), );
const CupertinoDynamicColor dynamicInactiveColor = CupertinoDynamicColor.withBrightness( color: Color(0xFF000002), darkColor: Color(0xFF000003), );
await pumpWidgetWithBoilerplate(tester, MediaQuery( data: const MediaQueryData(), child: CupertinoTabBar( items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 1', ), BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 2', ), ], currentIndex: 1, activeColor: dynamicActiveColor, inactiveColor: dynamicInactiveColor, ), ));
RichText actualInactive = tester.widget(find.descendant( of: find.text('Tab 1'), matching: find.byType(RichText), )); expect(actualInactive.text.style!.color!.value, 0xFF000002);
RichText actualActive = tester.widget(find.descendant( of: find.text('Tab 2'), matching: find.byType(RichText), )); expect(actualActive.text.style!.color!.value, 0xFF000000);
final RenderDecoratedBox renderDecoratedBox = tester.renderObject(find.descendant( of: find.byType(BackdropFilter), matching: find.byType(DecoratedBox), ));
// Border color is resolved correctly. final BoxDecoration decoration1 = renderDecoratedBox.decoration as BoxDecoration; expect(decoration1.border!.top.color.value, 0x4D000000);
// Switch to dark mode. await pumpWidgetWithBoilerplate(tester, MediaQuery( data: const MediaQueryData(platformBrightness: Brightness.dark), child: CupertinoTabBar( items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 1', ), BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 2', ), ], currentIndex: 1, activeColor: dynamicActiveColor, inactiveColor: dynamicInactiveColor, ), ));
actualInactive = tester.widget(find.descendant( of: find.text('Tab 1'), matching: find.byType(RichText), )); expect(actualInactive.text.style!.color!.value, 0xFF000003);
actualActive = tester.widget(find.descendant( of: find.text('Tab 2'), matching: find.byType(RichText), )); expect(actualActive.text.style!.color!.value, 0xFF000001);
// Border color is resolved correctly. final BoxDecoration decoration2 = renderDecoratedBox.decoration as BoxDecoration; expect(decoration2.border!.top.color.value, 0x29000000); });
testWidgets('Tabs respects themes', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: CupertinoTabBar( items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 1', ), BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 2', ), ], currentIndex: 1, ), ), );
RichText actualInactive = tester.widget(find.descendant( of: find.text('Tab 1'), matching: find.byType(RichText), )); expect(actualInactive.text.style!.color!.value, 0xFF999999);
RichText actualActive = tester.widget(find.descendant( of: find.text('Tab 2'), matching: find.byType(RichText), )); expect(actualActive.text.style!.color, CupertinoColors.activeBlue);
await tester.pumpWidget( CupertinoApp( theme: const CupertinoThemeData(brightness: Brightness.dark), home: CupertinoTabBar( items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 1', ), BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 2', ), ], currentIndex: 1, ), ), );
actualInactive = tester.widget(find.descendant( of: find.text('Tab 1'), matching: find.byType(RichText), )); expect(actualInactive.text.style!.color!.value, 0xFF757575);
actualActive = tester.widget(find.descendant( of: find.text('Tab 2'), matching: find.byType(RichText), ));
expect(actualActive.text.style!.color, isSameColorAs(CupertinoColors.activeBlue.darkColor)); });
testWidgets('Use active icon', (WidgetTester tester) async { final MemoryImage activeIcon = MemoryImage(Uint8List.fromList(kBlueSquarePng)); final MemoryImage inactiveIcon = MemoryImage(Uint8List.fromList(kTransparentImage));
await pumpWidgetWithBoilerplate(tester, MediaQuery( data: const MediaQueryData(), child: CupertinoTabBar( items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 1', ), BottomNavigationBarItem( icon: ImageIcon(inactiveIcon), activeIcon: ImageIcon(activeIcon), label: 'Tab 2', ), ], currentIndex: 1, activeColor: const Color(0xFF123456), inactiveColor: const Color(0xFF654321), ), ));
final Image image = tester.widget(find.descendant( of: find.widgetWithText(GestureDetector, 'Tab 2'), matching: find.byType(Image), ));
expect(image.color, const Color(0xFF123456)); expect(image.image, activeIcon); });
testWidgets('Adjusts height to account for bottom padding', (WidgetTester tester) async { final CupertinoTabBar tabBar = CupertinoTabBar( items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Aka', ), BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Shiro', ), ], );
// Verify height with no bottom padding. await pumpWidgetWithBoilerplate(tester, MediaQuery( data: const MediaQueryData(), child: CupertinoTabScaffold( tabBar: tabBar, tabBuilder: (BuildContext context, int index) { return const Placeholder(); }, ), )); expect(tester.getSize(find.byType(CupertinoTabBar)).height, 50.0);
// Verify height with bottom padding. await pumpWidgetWithBoilerplate(tester, MediaQuery( data: const MediaQueryData(viewPadding: EdgeInsets.only(bottom: 40.0)), child: CupertinoTabScaffold( tabBar: tabBar, tabBuilder: (BuildContext context, int index) { return const Placeholder(); }, ), )); expect(tester.getSize(find.byType(CupertinoTabBar)).height, 90.0); });
testWidgets('Set custom height', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/51704 const double tabBarHeight = 56.0; final CupertinoTabBar tabBar = CupertinoTabBar( height: tabBarHeight, items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Aka', ), BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Shiro', ), ], );
// Verify height with no bottom padding. await pumpWidgetWithBoilerplate(tester, MediaQuery( data: const MediaQueryData(), child: CupertinoTabScaffold( tabBar: tabBar, tabBuilder: (BuildContext context, int index) { return const Placeholder(); }, ), )); expect(tester.getSize(find.byType(CupertinoTabBar)).height, tabBarHeight);
// Verify height with bottom padding. const double bottomPadding = 40.0; await pumpWidgetWithBoilerplate(tester, MediaQuery( data: const MediaQueryData(viewPadding: EdgeInsets.only(bottom: bottomPadding)), child: CupertinoTabScaffold( tabBar: tabBar, tabBuilder: (BuildContext context, int index) { return const Placeholder(); }, ), )); expect(tester.getSize(find.byType(CupertinoTabBar)).height, tabBarHeight + bottomPadding); });
testWidgets('Ensure bar height will not change when toggle keyboard', (WidgetTester tester) async { const double tabBarHeight = 56.0; final CupertinoTabBar tabBar = CupertinoTabBar( height: tabBarHeight, items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Aka', ), BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Shiro', ), ], );
const double bottomPadding = 34.0;
// Test the height is correct when keyboard not showing. // So viewInset should be 0.0. await pumpWidgetWithBoilerplate(tester, MediaQuery( data: const MediaQueryData( padding: EdgeInsets.only(bottom: bottomPadding), viewPadding: EdgeInsets.only(bottom: bottomPadding), ), child: CupertinoTabScaffold( tabBar: tabBar, tabBuilder: (BuildContext context, int index) { return const Placeholder(); }, ), )); expect(tester.getSize(find.byType(CupertinoTabBar)).height, tabBarHeight + bottomPadding);
// Now show keyboard, and test the bar height will not change. await pumpWidgetWithBoilerplate(tester, MediaQuery( data: const MediaQueryData( viewPadding: EdgeInsets.only(bottom: bottomPadding), viewInsets: EdgeInsets.only(bottom: 336.0), ), child: CupertinoTabScaffold( tabBar: tabBar, tabBuilder: (BuildContext context, int index) { return const Placeholder(); }, ), ), );
// Expect the bar height should not change. expect(tester.getSize(find.byType(CupertinoTabBar)).height, tabBarHeight + bottomPadding); });
testWidgets('Opaque background does not add blur effects', (WidgetTester tester) async { await pumpWidgetWithBoilerplate(tester, MediaQuery( data: const MediaQueryData(), child: CupertinoTabBar( items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 1', ), BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 2', ), ], ), ));
expect(find.byType(BackdropFilter), findsOneWidget);
await pumpWidgetWithBoilerplate(tester, MediaQuery( data: const MediaQueryData(), child: CupertinoTabBar( items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 1', ), BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 2', ), ], backgroundColor: const Color(0xFFFFFFFF), // Opaque white. ), ));
expect(find.byType(BackdropFilter), findsNothing); });
testWidgets('Tap callback', (WidgetTester tester) async { late int callbackTab;
await pumpWidgetWithBoilerplate(tester, MediaQuery( data: const MediaQueryData(), child: CupertinoTabBar( items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 1', ), BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 2', ), ], currentIndex: 1, onTap: (int tab) { callbackTab = tab; }, ), ));
await tester.tap(find.text('Tab 1')); expect(callbackTab, 0);
await tester.tap(find.text('Tab 2')); expect(callbackTab, 1); });
testWidgets('tabs announce semantics', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester);
await pumpWidgetWithBoilerplate(tester, MediaQuery( data: const MediaQueryData(), child: CupertinoTabBar( items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 1', ), BottomNavigationBarItem( icon: ImageIcon(MemoryImage(Uint8List.fromList(kTransparentImage))), label: 'Tab 2', ), ], ), ));
expect(semantics, includesNodeWith( label: 'Tab 1', hint: 'Tab 1 of 2', flags: <SemanticsFlag>[SemanticsFlag.isSelected], textDirection: TextDirection.ltr, ));
expect(semantics, includesNodeWith( label: 'Tab 2', hint: 'Tab 2 of 2', textDirection: TextDirection.ltr, ));
semantics.dispose(); });
testWidgets('Label of items should be nullable', (WidgetTester tester) async { final MemoryImage iconProvider = MemoryImage(Uint8List.fromList(kTransparentImage)); final List<int> itemsTapped = <int>[];
await pumpWidgetWithBoilerplate( tester, MediaQuery( data: const MediaQueryData(), child: CupertinoTabBar( items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: ImageIcon( MemoryImage(Uint8List.fromList(kTransparentImage)), ), label: 'Tab 1', ), BottomNavigationBarItem( icon: ImageIcon( iconProvider, ), ), ], onTap: (int index) => itemsTapped.add(index), ), ), );
expect(find.text('Tab 1'), findsOneWidget);
final Finder finder = find.byWidgetPredicate( (Widget widget) => widget is Image && widget.image == iconProvider, );
await tester.tap(finder); expect(itemsTapped, <int>[1]); });
testWidgets('Hide border hides the top border of the tabBar', (WidgetTester tester) async { await pumpWidgetWithBoilerplate( tester, MediaQuery( data: const MediaQueryData(), child: CupertinoTabBar( items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: ImageIcon( MemoryImage(Uint8List.fromList(kTransparentImage)), ), label: 'Tab 1', ), BottomNavigationBarItem( icon: ImageIcon( MemoryImage(Uint8List.fromList(kTransparentImage)), ), label: 'Tab 2', ), ], ), ), );
final DecoratedBox decoratedBox = tester.widget(find.byType(DecoratedBox)); final BoxDecoration boxDecoration = decoratedBox.decoration as BoxDecoration; expect(boxDecoration.border, isNotNull);
await pumpWidgetWithBoilerplate( tester, MediaQuery( data: const MediaQueryData(), child: CupertinoTabBar( items: <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: ImageIcon( MemoryImage(Uint8List.fromList(kTransparentImage)), ), label: 'Tab 1', ), BottomNavigationBarItem( icon: ImageIcon( MemoryImage(Uint8List.fromList(kTransparentImage)), ), label: 'Tab 2', ), ], backgroundColor: const Color(0xFFFFFFFF), // Opaque white. border: null, ), ), );
final DecoratedBox decoratedBoxHiddenBorder = tester.widget(find.byType(DecoratedBox)); final BoxDecoration boxDecorationHiddenBorder = decoratedBoxHiddenBorder.decoration as BoxDecoration; expect(boxDecorationHiddenBorder.border, isNull); });
testWidgets('Hovering over tab bar item updates cursor to clickable on Web', (WidgetTester tester) async { await pumpWidgetWithBoilerplate( tester, MediaQuery( data: const MediaQueryData(), child: Center( child: CupertinoTabBar( items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(CupertinoIcons.alarm), label: 'Tab 1', ), BottomNavigationBarItem( icon: Icon(CupertinoIcons.app_badge), label: 'Tab 2', ), ], ), ), ), );
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); await gesture.addPointer(location: const Offset(10, 10)); await tester.pumpAndSettle(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
final Offset tabItem = tester.getCenter(find.text('Tab 1')); await gesture.moveTo(tabItem); await tester.pumpAndSettle(); expect( RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), kIsWeb ? SystemMouseCursors.click : SystemMouseCursors.basic, ); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496// 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/foundation.dart';import 'package:flutter/gestures.dart';import 'package:flutter/rendering.dart';import 'package:flutter/scheduler.dart';import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
const TextStyle testStyle = TextStyle( fontSize: 10.0, letterSpacing: 0.0,);
void main() { testWidgets('Default layout minimum size', (WidgetTester tester) async { await tester.pumpWidget( boilerplate(child: const CupertinoButton( onPressed: null, child: Text('X', style: testStyle), )), ); final RenderBox buttonBox = tester.renderObject(find.byType(CupertinoButton)); expect( buttonBox.size, // 1 10px character + 16px * 2 is smaller than the default 44px minimum. const Size.square(44.0), ); });
testWidgets('Minimum size parameter', (WidgetTester tester) async { const double minSize = 60.0; await tester.pumpWidget( boilerplate(child: const CupertinoButton( onPressed: null, minSize: minSize, child: Text('X', style: testStyle), )), ); final RenderBox buttonBox = tester.renderObject(find.byType(CupertinoButton)); expect( buttonBox.size, // 1 10px character + 16px * 2 is smaller than defined 60.0px minimum const Size.square(minSize), ); });
testWidgets('Size grows with text', (WidgetTester tester) async { await tester.pumpWidget( boilerplate(child: const CupertinoButton( onPressed: null, child: Text('XXXX', style: testStyle), )), ); final RenderBox buttonBox = tester.renderObject(find.byType(CupertinoButton)); expect( buttonBox.size.width, // 4 10px character + 16px * 2 = 72. 72.0, ); });
// TODO(LongCatIsLoong): Uncomment once https://github.com/flutter/flutter/issues/44115 // is fixed. /* testWidgets( 'CupertinoButton.filled default color contrast meets guideline', (WidgetTester tester) async { // The native color combination systemBlue text over white background fails // to pass the color contrast guideline. //await tester.pumpWidget( // CupertinoTheme( // data: const CupertinoThemeData(), // child: Directionality( // textDirection: TextDirection.ltr, // child: CupertinoButton.filled( // child: const Text('Button'), // onPressed: () {}, // ), // ), // ), //); //await expectLater(tester, meetsGuideline(textContrastGuideline));
await tester.pumpWidget( CupertinoApp( theme: const CupertinoThemeData(brightness: Brightness.dark), home: CupertinoPageScaffold( child: CupertinoButton.filled( child: const Text('Button'), onPressed: () {}, ), ), ), );
await expectLater(tester, meetsGuideline(textContrastGuideline)); }); */
testWidgets('Button child alignment', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: CupertinoButton( onPressed: () { }, child: const Text('button'), ), ), );
Align align = tester.firstWidget<Align>(find.ancestor(of: find.text('button'), matching: find.byType(Align))); expect(align.alignment, Alignment.center); // default
await tester.pumpWidget( CupertinoApp( home: CupertinoButton( alignment: Alignment.centerLeft, onPressed: () { }, child: const Text('button'), ), ), );
align = tester.firstWidget<Align>(find.ancestor(of: find.text('button'), matching: find.byType(Align))); expect(align.alignment, Alignment.centerLeft); });
testWidgets('Button with background is wider', (WidgetTester tester) async { await tester.pumpWidget(boilerplate(child: const CupertinoButton( onPressed: null, color: Color(0xFFFFFFFF), child: Text('X', style: testStyle), ))); final RenderBox buttonBox = tester.renderObject(find.byType(CupertinoButton)); expect( buttonBox.size.width, // 1 10px character + 64 * 2 = 138 for buttons with background. 138.0, ); });
testWidgets('Custom padding', (WidgetTester tester) async { await tester.pumpWidget(boilerplate(child: const CupertinoButton( onPressed: null, padding: EdgeInsets.all(100.0), child: Text('X', style: testStyle), ))); final RenderBox buttonBox = tester.renderObject(find.byType(CupertinoButton)); expect( buttonBox.size, const Size.square(210.0), ); });
testWidgets('Button takes taps', (WidgetTester tester) async { bool value = false; await tester.pumpWidget( StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return boilerplate( child: CupertinoButton( child: const Text('Tap me'), onPressed: () { setState(() { value = true; }); }, ), ); }, ), );
expect(value, isFalse); // No animating by default. expect(SchedulerBinding.instance.transientCallbackCount, equals(0)); await tester.tap(find.byType(CupertinoButton)); expect(value, isTrue); // Animates. expect(SchedulerBinding.instance.transientCallbackCount, equals(1)); });
testWidgets("Disabled button doesn't animate", (WidgetTester tester) async { await tester.pumpWidget(boilerplate(child: const CupertinoButton( onPressed: null, child: Text('Tap me'), ))); expect(SchedulerBinding.instance.transientCallbackCount, equals(0)); await tester.tap(find.byType(CupertinoButton)); // Still doesn't animate. expect(SchedulerBinding.instance.transientCallbackCount, equals(0)); });
testWidgets('Enabled button animates', (WidgetTester tester) async { await tester.pumpWidget(boilerplate(child: CupertinoButton( child: const Text('Tap me'), onPressed: () { }, )));
await tester.tap(find.byType(CupertinoButton)); // Enter animation. await tester.pump(); FadeTransition transition = tester.firstWidget(find.byType(FadeTransition));
await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(find.byType(FadeTransition)); expect(transition.opacity.value, moreOrLessEquals(0.403, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 100)); transition = tester.firstWidget(find.byType(FadeTransition)); expect(transition.opacity.value, moreOrLessEquals(0.400, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(find.byType(FadeTransition)); expect(transition.opacity.value, moreOrLessEquals(0.650, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(find.byType(FadeTransition)); expect(transition.opacity.value, moreOrLessEquals(0.894, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(find.byType(FadeTransition)); expect(transition.opacity.value, moreOrLessEquals(0.988, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(find.byType(FadeTransition)); expect(transition.opacity.value, moreOrLessEquals(1.0, epsilon: 0.001)); });
testWidgets('pressedOpacity defaults to 0.1', (WidgetTester tester) async { await tester.pumpWidget(boilerplate(child: CupertinoButton( child: const Text('Tap me'), onPressed: () { }, )));
// Keep a "down" gesture on the button final Offset center = tester.getCenter(find.byType(CupertinoButton)); final TestGesture gesture = await tester.startGesture(center); await tester.pumpAndSettle();
// Check opacity final FadeTransition opacity = tester.widget(find.descendant( of: find.byType(CupertinoButton), matching: find.byType(FadeTransition), )); expect(opacity.opacity.value, 0.4);
// Finish gesture to release resources. await gesture.up(); await tester.pumpAndSettle(); });
testWidgets('pressedOpacity parameter', (WidgetTester tester) async { const double pressedOpacity = 0.5; await tester.pumpWidget(boilerplate(child: CupertinoButton( pressedOpacity: pressedOpacity, child: const Text('Tap me'), onPressed: () { }, )));
// Keep a "down" gesture on the button final Offset center = tester.getCenter(find.byType(CupertinoButton)); final TestGesture gesture = await tester.startGesture(center); await tester.pumpAndSettle();
// Check opacity final FadeTransition opacity = tester.widget(find.descendant( of: find.byType(CupertinoButton), matching: find.byType(FadeTransition), )); expect(opacity.opacity.value, pressedOpacity);
// Finish gesture to release resources. await gesture.up(); await tester.pumpAndSettle(); });
testWidgets('Cupertino button is semantically a button', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( boilerplate( child: Center( child: CupertinoButton( onPressed: () { }, child: const Text('ABC'), ), ), ), );
expect(semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics.rootChild( actions: SemanticsAction.tap.index, label: 'ABC', flags: SemanticsFlag.isButton.index, ), ], ), ignoreId: true, ignoreRect: true, ignoreTransform: true, ));
semantics.dispose(); });
testWidgets('Can specify colors', (WidgetTester tester) async { await tester.pumpWidget(boilerplate(child: CupertinoButton( color: const Color(0x000000FF), disabledColor: const Color(0x0000FF00), onPressed: () { }, child: const Text('Skeuomorph me'), )));
BoxDecoration boxDecoration = tester.widget<DecoratedBox>( find.widgetWithText(DecoratedBox, 'Skeuomorph me'), ).decoration as BoxDecoration;
expect(boxDecoration.color, const Color(0x000000FF));
await tester.pumpWidget(boilerplate(child: const CupertinoButton( color: Color(0x000000FF), disabledColor: Color(0x0000FF00), onPressed: null, child: Text('Skeuomorph me'), )));
boxDecoration = tester.widget<DecoratedBox>( find.widgetWithText(DecoratedBox, 'Skeuomorph me'), ).decoration as BoxDecoration;
expect(boxDecoration.color, const Color(0x0000FF00)); });
testWidgets('Can specify dynamic colors', (WidgetTester tester) async { const Color bgColor = CupertinoDynamicColor.withBrightness( color: Color(0xFF123456), darkColor: Color(0xFF654321), );
const Color inactive = CupertinoDynamicColor.withBrightness( color: Color(0xFF111111), darkColor: Color(0xFF222222), );
await tester.pumpWidget( MediaQuery( data: const MediaQueryData(platformBrightness: Brightness.dark), child: boilerplate(child: CupertinoButton( color: bgColor, disabledColor: inactive, onPressed: () { }, child: const Text('Skeuomorph me'), )), ), );
BoxDecoration boxDecoration = tester.widget<DecoratedBox>( find.widgetWithText(DecoratedBox, 'Skeuomorph me'), ).decoration as BoxDecoration;
expect(boxDecoration.color!.value, 0xFF654321);
await tester.pumpWidget( MediaQuery( data: const MediaQueryData(), child: boilerplate(child: const CupertinoButton( color: bgColor, disabledColor: inactive, onPressed: null, child: Text('Skeuomorph me'), )), ), );
boxDecoration = tester.widget<DecoratedBox>( find.widgetWithText(DecoratedBox, 'Skeuomorph me'), ).decoration as BoxDecoration;
// Disabled color. expect(boxDecoration.color!.value, 0xFF111111); });
testWidgets('Button respects themes', (WidgetTester tester) async { late TextStyle textStyle;
await tester.pumpWidget( CupertinoApp( home: CupertinoButton( onPressed: () { }, child: Builder(builder: (BuildContext context) { textStyle = DefaultTextStyle.of(context).style; return const Placeholder(); }), ), ), );
expect(textStyle.color, CupertinoColors.activeBlue);
await tester.pumpWidget( CupertinoApp( home: CupertinoButton.filled( onPressed: () { }, child: Builder(builder: (BuildContext context) { textStyle = DefaultTextStyle.of(context).style; return const Placeholder(); }), ), ), );
expect(textStyle.color, isSameColorAs(CupertinoColors.white)); BoxDecoration decoration = tester.widget<DecoratedBox>( find.descendant( of: find.byType(CupertinoButton), matching: find.byType(DecoratedBox), ), ).decoration as BoxDecoration; expect(decoration.color, CupertinoColors.activeBlue);
await tester.pumpWidget( CupertinoApp( theme: const CupertinoThemeData(brightness: Brightness.dark), home: CupertinoButton( onPressed: () { }, child: Builder(builder: (BuildContext context) { textStyle = DefaultTextStyle.of(context).style; return const Placeholder(); }), ), ), ); expect(textStyle.color, isSameColorAs(CupertinoColors.systemBlue.darkColor));
await tester.pumpWidget( CupertinoApp( theme: const CupertinoThemeData(brightness: Brightness.dark), home: CupertinoButton.filled( onPressed: () { }, child: Builder(builder: (BuildContext context) { textStyle = DefaultTextStyle.of(context).style; return const Placeholder(); }), ), ), ); expect(textStyle.color, isSameColorAs(CupertinoColors.black)); decoration = tester.widget<DecoratedBox>( find.descendant( of: find.byType(CupertinoButton), matching: find.byType(DecoratedBox), ), ).decoration as BoxDecoration; expect(decoration.color, isSameColorAs(CupertinoColors.systemBlue.darkColor)); });
testWidgets('Hovering over Cupertino button updates cursor to clickable on Web', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoButton.filled( onPressed: () { }, child: const Text('Tap me'), ), ), ), );
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); await gesture.addPointer(location: const Offset(10, 10)); await tester.pumpAndSettle(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
final Offset button = tester.getCenter(find.byType(CupertinoButton)); await gesture.moveTo(button); await tester.pumpAndSettle(); expect( RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), kIsWeb ? SystemMouseCursors.click : SystemMouseCursors.basic, ); });}
Widget boilerplate({ required Widget child }) { return Directionality( textDirection: TextDirection.ltr, child: Center(child: child), );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413// 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/foundation.dart';import 'package:flutter/rendering.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
void main() { setUp(() { debugResetSemanticsIdCounter(); });
testWidgets('CupertinoCheckbox semantics', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget( CupertinoApp ( home: Center( child: CupertinoCheckbox( value: false, onChanged: (bool? b) { }, ), ) ), );
expect(tester.getSemantics(find.byType(Focus).last), matchesSemantics( hasCheckedState: true, hasEnabledState: true, isEnabled: true, hasTapAction: true, isFocusable: true, ));
await tester.pumpWidget( CupertinoApp ( home: Center( child: CupertinoCheckbox( value: true, onChanged: (bool? b) { }, ), ) ), );
expect(tester.getSemantics(find.byType(Focus).last), matchesSemantics( hasCheckedState: true, hasEnabledState: true, isChecked: true, isEnabled: true, hasTapAction: true, isFocusable: true, ));
await tester.pumpWidget( const CupertinoApp ( home: Center( child: CupertinoCheckbox( value: false, onChanged: null, ), ) ), );
expect(tester.getSemantics(find.byType(CupertinoCheckbox)), matchesSemantics( hasCheckedState: true, hasEnabledState: true, // isFocusable is delayed by 1 frame. isFocusable: true, ));
await tester.pump(); // isFocusable should be false now after the 1 frame delay. expect(tester.getSemantics(find.byType(CupertinoCheckbox)), matchesSemantics( hasCheckedState: true, hasEnabledState: true, ));
await tester.pumpWidget( const CupertinoApp ( home: Center( child: CupertinoCheckbox( value: true, onChanged: null, ), ) ), );
expect(tester.getSemantics(find.byType(CupertinoCheckbox)), matchesSemantics( hasCheckedState: true, hasEnabledState: true, isChecked: true, ));
await tester.pumpWidget( const CupertinoApp ( home: Center( child: CupertinoCheckbox( value: null, tristate: true, onChanged: null, ), ) ), );
expect(tester.getSemantics(find.byType(CupertinoCheckbox)), matchesSemantics( hasCheckedState: true, hasEnabledState: true, isCheckStateMixed: true, ));
await tester.pumpWidget( const CupertinoApp ( home: Center( child: CupertinoCheckbox( value: true, tristate: true, onChanged: null, ), ) ), );
expect(tester.getSemantics(find.byType(CupertinoCheckbox)), matchesSemantics( hasCheckedState: true, hasEnabledState: true, isChecked: true, ));
await tester.pumpWidget( const CupertinoApp ( home: Center( child: CupertinoCheckbox( value: false, tristate: true, onChanged: null, ), ) ), );
expect(tester.getSemantics(find.byType(CupertinoCheckbox)), matchesSemantics( hasCheckedState: true, hasEnabledState: true, ));
handle.dispose(); });
testWidgets('Can wrap CupertinoCheckbox with Semantics', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget( CupertinoApp( home: Semantics( label: 'foo', textDirection: TextDirection.ltr, child: CupertinoCheckbox( value: false, onChanged: (bool? b) { }, ), ), ), );
expect(tester.getSemantics(find.byType(Focus).last), matchesSemantics( label: 'foo', textDirection: TextDirection.ltr, hasCheckedState: true, hasEnabledState: true, isEnabled: true, hasTapAction: true, isFocusable: true, )); handle.dispose(); });
testWidgets('CupertinoCheckbox tristate: true', (WidgetTester tester) async { bool? checkBoxValue;
await tester.pumpWidget( CupertinoApp( home: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return CupertinoCheckbox( tristate: true, value: checkBoxValue, onChanged: (bool? value) { setState(() { checkBoxValue = value; }); }, ); }, ), ), );
expect(tester.widget<CupertinoCheckbox>(find.byType(CupertinoCheckbox)).value, null);
await tester.tap(find.byType(CupertinoCheckbox)); await tester.pumpAndSettle(); expect(checkBoxValue, false);
await tester.tap(find.byType(CupertinoCheckbox)); await tester.pumpAndSettle(); expect(checkBoxValue, true);
await tester.tap(find.byType(CupertinoCheckbox)); await tester.pumpAndSettle(); expect(checkBoxValue, null);
checkBoxValue = true; await tester.pumpAndSettle(); expect(checkBoxValue, true);
checkBoxValue = null; await tester.pumpAndSettle(); expect(checkBoxValue, null); });
testWidgets('has semantics for tristate', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget( CupertinoApp( home: CupertinoCheckbox( tristate: true, value: null, onChanged: (bool? newValue) { }, ), ), );
expect(semantics.nodesWith( flags: <SemanticsFlag>[ SemanticsFlag.hasCheckedState, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocusable, SemanticsFlag.isCheckStateMixed, ], actions: <SemanticsAction>[SemanticsAction.tap], ), hasLength(1));
await tester.pumpWidget( CupertinoApp( home: CupertinoCheckbox( tristate: true, value: true, onChanged: (bool? newValue) { }, ), ), );
expect(semantics.nodesWith( flags: <SemanticsFlag>[ SemanticsFlag.hasCheckedState, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isChecked, SemanticsFlag.isFocusable, ], actions: <SemanticsAction>[SemanticsAction.tap], ), hasLength(1));
await tester.pumpWidget( CupertinoApp( home: CupertinoCheckbox( tristate: true, value: false, onChanged: (bool? newValue) { }, ), ), );
expect(semantics.nodesWith( flags: <SemanticsFlag>[ SemanticsFlag.hasCheckedState, SemanticsFlag.hasEnabledState, SemanticsFlag.isEnabled, SemanticsFlag.isFocusable, ], actions: <SemanticsAction>[SemanticsAction.tap], ), hasLength(1));
semantics.dispose(); });
testWidgets('has semantic events', (WidgetTester tester) async { dynamic semanticEvent; bool? checkboxValue = false; tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>(SystemChannels.accessibility, (dynamic message) async { semanticEvent = message; }); final SemanticsTester semanticsTester = SemanticsTester(tester);
await tester.pumpWidget( CupertinoApp( home: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return CupertinoCheckbox( value: checkboxValue, onChanged: (bool? value) { setState(() { checkboxValue = value; }); }, ); }, ), ), );
await tester.tap(find.byType(CupertinoCheckbox)); final RenderObject object = tester.firstRenderObject(find.byType(CupertinoCheckbox));
expect(checkboxValue, true); expect(semanticEvent, <String, dynamic>{ 'type': 'tap', 'nodeId': object.debugSemantics!.id, 'data': <String, dynamic>{}, }); expect(object.debugSemantics!.getSemanticsData().hasAction(SemanticsAction.tap), true);
tester.binding.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>(SystemChannels.accessibility, null); semanticsTester.dispose(); });
testWidgets('Checkbox can be toggled by keyboard shortcuts', (WidgetTester tester) async { tester.binding.focusManager.highlightStrategy = FocusHighlightStrategy.alwaysTraditional; bool? value = true; Widget buildApp({bool enabled = true}) { return CupertinoApp( home: Center( child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return CupertinoCheckbox( value: value, onChanged: enabled ? (bool? newValue) { setState(() { value = newValue; }); } : null, autofocus: true, ); }), ), ); } await tester.pumpWidget(buildApp()); await tester.pumpAndSettle(); await tester.sendKeyEvent(LogicalKeyboardKey.enter); await tester.pumpAndSettle(); // On web, switches don't respond to the enter key. expect(value, kIsWeb ? isTrue : isFalse); await tester.sendKeyEvent(LogicalKeyboardKey.enter); await tester.pumpAndSettle(); expect(value, isTrue); await tester.sendKeyEvent(LogicalKeyboardKey.space); await tester.pumpAndSettle(); expect(value, isFalse); await tester.sendKeyEvent(LogicalKeyboardKey.space); await tester.pumpAndSettle(); expect(value, isTrue); });
testWidgets('Checkbox respects shape and side', (WidgetTester tester) async { const RoundedRectangleBorder roundedRectangleBorder = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(5)));
const BorderSide side = BorderSide( width: 4, color: Color(0xfff44336), );
Widget buildApp() { return CupertinoApp( home: Center( child: StatefulBuilder(builder: (BuildContext context, StateSetter setState) { return CupertinoCheckbox( value: false, onChanged: (bool? newValue) {}, shape: roundedRectangleBorder, side: side, ); }), ), ); }
await tester.pumpWidget(buildApp()); await tester.pumpAndSettle();
expect(tester.widget<CupertinoCheckbox>(find.byType(CupertinoCheckbox)).shape, roundedRectangleBorder); expect(tester.widget<CupertinoCheckbox>(find.byType(CupertinoCheckbox)).side, side); expect( find.byType(CupertinoCheckbox), paints ..drrect( color: const Color(0xfff44336), outer: RRect.fromLTRBR(13.0, 13.0, 31.0, 31.0, const Radius.circular(5)), inner: RRect.fromLTRBR(17.0, 17.0, 27.0, 27.0, const Radius.circular(1)), ), ); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599// 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();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168// 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/foundation.dart';import 'package:flutter/gestures.dart';import 'package:flutter/rendering.dart';import 'package:flutter_test/flutter_test.dart';
void main() { // Constants taken from _ContextMenuActionState. const CupertinoDynamicColor kBackgroundColor = CupertinoDynamicColor.withBrightness( color: Color(0xFFF1F1F1), darkColor: Color(0xFF212122), ); const CupertinoDynamicColor kBackgroundColorPressed = CupertinoDynamicColor.withBrightness( color: Color(0xFFDDDDDD), darkColor: Color(0xFF3F3F40), ); const Color kDestructiveActionColor = CupertinoColors.destructiveRed; const FontWeight kDefaultActionWeight = FontWeight.w600;
Widget getApp({ VoidCallback? onPressed, bool isDestructiveAction = false, bool isDefaultAction = false, Brightness? brightness, }) { final UniqueKey actionKey = UniqueKey(); final CupertinoContextMenuAction action = CupertinoContextMenuAction( key: actionKey, onPressed: onPressed, trailingIcon: CupertinoIcons.home, isDestructiveAction: isDestructiveAction, isDefaultAction: isDefaultAction, child: const Text('I am a CupertinoContextMenuAction'), );
return CupertinoApp( theme: CupertinoThemeData( brightness: brightness ?? Brightness.light, ), home: CupertinoPageScaffold( child: Center( child: action, ), ), ); }
TextStyle getTextStyle(WidgetTester tester) { final Finder finder = find.descendant( of: find.byType(CupertinoContextMenuAction), matching: find.byType(DefaultTextStyle), ); expect(finder, findsOneWidget); final DefaultTextStyle defaultStyle = tester.widget(finder); return defaultStyle.style; }
Icon getIcon(WidgetTester tester) { final Finder finder = find.descendant( of: find.byType(CupertinoContextMenuAction), matching: find.byType(Icon), ); expect(finder, findsOneWidget); final Icon icon = tester.widget(finder); return icon; }
testWidgets('responds to taps', (WidgetTester tester) async { bool wasPressed = false; await tester.pumpWidget(getApp(onPressed: () { wasPressed = true; }));
expect(wasPressed, false); await tester.tap(find.byType(CupertinoContextMenuAction)); expect(wasPressed, true); });
testWidgets('turns grey when pressed and held', (WidgetTester tester) async { await tester.pumpWidget(getApp()); expect(find.byType(CupertinoContextMenuAction), paints..rect(color: kBackgroundColor.color));
final Offset actionCenterLight = tester.getCenter(find.byType(CupertinoContextMenuAction)); final TestGesture gestureLight = await tester.startGesture(actionCenterLight); await tester.pump(); expect(find.byType(CupertinoContextMenuAction), paints..rect(color: kBackgroundColorPressed.color));
await gestureLight.up(); await tester.pump(); expect(find.byType(CupertinoContextMenuAction), paints..rect(color: kBackgroundColor.color));
await tester.pumpWidget(getApp(brightness: Brightness.dark)); expect(find.byType(CupertinoContextMenuAction), paints..rect(color: kBackgroundColor.darkColor));
final Offset actionCenterDark = tester.getCenter(find.byType(CupertinoContextMenuAction)); final TestGesture gestureDark = await tester.startGesture(actionCenterDark); await tester.pump(); expect(find.byType(CupertinoContextMenuAction), paints..rect(color: kBackgroundColorPressed.darkColor));
await gestureDark.up(); await tester.pump(); expect(find.byType(CupertinoContextMenuAction), paints..rect(color: kBackgroundColor.darkColor)); });
testWidgets('icon and textStyle colors are correct out of the box', (WidgetTester tester) async { await tester.pumpWidget(getApp()); expect(getTextStyle(tester).color, CupertinoColors.label); expect(getIcon(tester).color, CupertinoColors.label); });
testWidgets('icon and textStyle colors are correct for destructive actions', (WidgetTester tester) async { await tester.pumpWidget(getApp(isDestructiveAction: true)); expect(getTextStyle(tester).color, kDestructiveActionColor); expect(getIcon(tester).color, kDestructiveActionColor); });
testWidgets('textStyle is correct for defaultAction', (WidgetTester tester) async { await tester.pumpWidget(getApp(isDefaultAction: true)); expect(getTextStyle(tester).fontWeight, kDefaultActionWeight); });
testWidgets( 'Hovering over Cupertino context menu action updates cursor to clickable on Web', (WidgetTester tester) async { /// Cupertino context menu action without "onPressed" callback. await tester.pumpWidget(getApp()); final Offset contextMenuAction = tester.getCenter(find.text('I am a CupertinoContextMenuAction')); final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); await gesture.addPointer(location: contextMenuAction); await tester.pumpAndSettle(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
// / Cupertino context menu action with "onPressed" callback. await tester.pumpWidget(getApp(onPressed: () {})); await gesture.moveTo(const Offset(10, 10)); await tester.pumpAndSettle(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
await gesture.moveTo(contextMenuAction); await tester.pumpAndSettle(); expect( RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), kIsWeb ? SystemMouseCursors.click : SystemMouseCursors.basic, ); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889// 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:clock/clock.dart';import 'package:flutter/cupertino.dart';import 'package:flutter/foundation.dart';import 'package:flutter/gestures.dart';import 'package:flutter/rendering.dart';import 'package:flutter_test/flutter_test.dart';
void main() { final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized(); const double kOpenScale = 1.15;
Widget getChild() { return Container( width: 300.0, height: 100.0, color: CupertinoColors.activeOrange, ); }
Widget getBuilder(BuildContext context, Animation<double> animation) { return getChild(); }
Widget getContextMenu({ Alignment alignment = Alignment.center, Size screenSize = const Size(800.0, 600.0), Widget? child, }) { return CupertinoApp( home: CupertinoPageScaffold( child: MediaQuery( data: MediaQueryData(size: screenSize), child: Align( alignment: alignment, child: CupertinoContextMenu( actions: <CupertinoContextMenuAction>[ CupertinoContextMenuAction( child: Text('CupertinoContextMenuAction $alignment'), ), ], child: child ?? getChild(), ), ), ), ), ); }
Widget getBuilderContextMenu({ Alignment alignment = Alignment.center, Size screenSize = const Size(800.0, 600.0), CupertinoContextMenuBuilder? builder, }) { return CupertinoApp( home: CupertinoPageScaffold( child: MediaQuery( data: MediaQueryData(size: screenSize), child: Align( alignment: alignment, child: CupertinoContextMenu.builder( actions: <CupertinoContextMenuAction>[ CupertinoContextMenuAction( child: Text('CupertinoContextMenuAction $alignment'), ), ], builder: builder ?? getBuilder, ), ), ), ), ); }
// Finds the child widget that is rendered inside of _DecoyChild. Finder findDecoyChild(Widget child) { return find.descendant( of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DecoyChild'), matching: find.byWidget(child), ); }
// Finds the child widget rendered inside of _ContextMenuRouteStatic. Finder findStatic() { return find.descendant( of: find.byType(CupertinoApp), matching: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_ContextMenuRouteStatic'), ); }
Finder findStaticChild(Widget child) { return find.descendant( of: findStatic(), matching: find.byWidget(child), ); }
Finder findStaticChildDecoration(WidgetTester tester) { return find.descendant( of: findStatic(), matching: find.byType(DecoratedBox), ); }
Finder findFittedBox() { return find.descendant( of: findStatic(), matching: find.byType(FittedBox), ); }
Finder findStaticDefaultPreview() { return find.descendant( of: findFittedBox(), matching: find.byType(ClipRRect), ); }
group('CupertinoContextMenu before and during opening', () { testWidgets('An unopened CupertinoContextMenu renders child in the same place as without', (WidgetTester tester) async { // Measure the child in the scene with no CupertinoContextMenu. final Widget child = getChild(); await tester.pumpWidget( CupertinoApp( home: CupertinoPageScaffold( child: Center( child: child, ), ), ), ); final Rect childRect = tester.getRect(find.byWidget(child));
// When wrapped in a CupertinoContextMenu, the child is rendered in the same Rect. await tester.pumpWidget(getContextMenu(child: child)); expect(find.byWidget(child), findsOneWidget); expect(tester.getRect(find.byWidget(child)), childRect); });
testWidgets('Can open CupertinoContextMenu by tap and hold', (WidgetTester tester) async { final Widget child = getChild(); await tester.pumpWidget(getContextMenu(child: child)); expect(find.byWidget(child), findsOneWidget); final Rect childRect = tester.getRect(find.byWidget(child)); expect(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DecoyChild'), findsNothing);
// Start a press on the child. final TestGesture gesture = await tester.startGesture(childRect.center); await tester.pump();
// The _DecoyChild is showing directly on top of the child. expect(findDecoyChild(child), findsOneWidget); Rect decoyChildRect = tester.getRect(findDecoyChild(child)); expect(childRect, equals(decoyChildRect));
expect(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DecoyChild'), findsOneWidget);
// After a small delay, the _DecoyChild has begun to animate. await tester.pump(const Duration(milliseconds: 400)); decoyChildRect = tester.getRect(findDecoyChild(child)); expect(childRect, isNot(equals(decoyChildRect)));
// Eventually the decoy fully scales by _kOpenSize. await tester.pump(const Duration(milliseconds: 800)); decoyChildRect = tester.getRect(findDecoyChild(child)); expect(childRect, isNot(equals(decoyChildRect))); expect(decoyChildRect.width, childRect.width * kOpenScale);
// Then the CupertinoContextMenu opens. await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle(); expect(findStatic(), findsOneWidget); });
testWidgets('CupertinoContextMenu is in the correct position when within a nested navigator', (WidgetTester tester) async { final Widget child = getChild(); await tester.pumpWidget(CupertinoApp( home: CupertinoPageScaffold( child: MediaQuery( data: const MediaQueryData(size: Size(800, 600)), child: Align( alignment: Alignment.bottomRight, child: SizedBox( width: 700, height: 500, child: Navigator( onGenerateRoute: (RouteSettings settings) { return CupertinoPageRoute<void>( builder: (BuildContext context) => Align( child: CupertinoContextMenu( actions: const <CupertinoContextMenuAction>[ CupertinoContextMenuAction( child: Text('CupertinoContextMenuAction'), ), ], child: child ), ) ); } ) ) ) ) ) )); expect(find.byWidget(child), findsOneWidget); final Rect childRect = tester.getRect(find.byWidget(child)); expect(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DecoyChild'), findsNothing);
// Start a press on the child. final TestGesture gesture = await tester.startGesture(childRect.center); await tester.pump();
// The _DecoyChild is showing directly on top of the child. expect(findDecoyChild(child), findsOneWidget); Rect decoyChildRect = tester.getRect(findDecoyChild(child)); expect(childRect, equals(decoyChildRect));
expect(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DecoyChild'), findsOneWidget);
// After a small delay, the _DecoyChild has begun to animate. await tester.pump(const Duration(milliseconds: 400)); decoyChildRect = tester.getRect(findDecoyChild(child)); expect(childRect, isNot(equals(decoyChildRect)));
// Eventually the decoy fully scales by _kOpenSize. await tester.pump(const Duration(milliseconds: 800)); decoyChildRect = tester.getRect(findDecoyChild(child)); expect(childRect, isNot(equals(decoyChildRect))); expect(decoyChildRect.width, childRect.width * kOpenScale);
// Then the CupertinoContextMenu opens. await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle(); expect(findStatic(), findsOneWidget); });
testWidgets('CupertinoContextMenu with a basic builder opens and closes the same as when providing a child', (WidgetTester tester) async { final Widget child = getChild(); await tester.pumpWidget(getBuilderContextMenu(builder: (BuildContext context, Animation<double> animation) { return child; })); expect(find.byWidget(child), findsOneWidget); final Rect childRect = tester.getRect(find.byWidget(child)); expect(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DecoyChild'), findsNothing);
// Start a press on the child. final TestGesture gesture = await tester.startGesture(childRect.center); await tester.pump();
// The _DecoyChild is showing directly on top of the child. expect(findDecoyChild(child), findsOneWidget); Rect decoyChildRect = tester.getRect(findDecoyChild(child)); expect(childRect, equals(decoyChildRect));
expect(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DecoyChild'), findsOneWidget);
// After a small delay, the _DecoyChild has begun to animate. await tester.pump(const Duration(milliseconds: 400)); decoyChildRect = tester.getRect(findDecoyChild(child)); expect(childRect, isNot(equals(decoyChildRect)));
// Eventually the decoy fully scales by _kOpenSize. await tester.pump(const Duration(milliseconds: 800)); decoyChildRect = tester.getRect(findDecoyChild(child)); expect(childRect, isNot(equals(decoyChildRect))); expect(decoyChildRect.width, childRect.width * kOpenScale);
// Then the CupertinoContextMenu opens. await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle(); expect(findStatic(), findsOneWidget); });
testWidgets('CupertinoContextMenu with a builder can change the animation', (WidgetTester tester) async { await tester.pumpWidget(getBuilderContextMenu(builder: (BuildContext context, Animation<double> animation) { return Container( width: 300.0, height: 100.0, decoration: BoxDecoration( color: CupertinoColors.activeOrange, borderRadius: BorderRadius.circular(25.0 * animation.value) ), ); }));
final Widget child = find.descendant(of: find.byType(TickerMode), matching: find.byType(Container)).evaluate().single.widget; final Rect childRect = tester.getRect(find.byWidget(child)); expect(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DecoyChild'), findsNothing);
// Start a press on the child. final TestGesture gesture = await tester.startGesture(childRect.center); await tester.pump();
Finder findBuilderDecoyChild() { return find.descendant( of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DecoyChild'), matching: find.byType(Container), ); }
final Container decoyContainer = tester.firstElement(findBuilderDecoyChild()).widget as Container; final BoxDecoration? decoyDecoration = decoyContainer.decoration as BoxDecoration?; expect(decoyDecoration?.borderRadius, equals(BorderRadius.circular(0)));
expect(findBuilderDecoyChild(), findsOneWidget);
// After a small delay, the _DecoyChild has begun to animate with a different border radius. await tester.pump(const Duration(milliseconds: 500)); final Container decoyLaterContainer = tester.firstElement(findBuilderDecoyChild()).widget as Container; final BoxDecoration? decoyLaterDecoration = decoyLaterContainer.decoration as BoxDecoration?; expect(decoyLaterDecoration?.borderRadius, isNot(equals(BorderRadius.circular(0))));
// Finish gesture to release resources. await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle(); });
testWidgets('Hovering over Cupertino context menu updates cursor to clickable on Web', (WidgetTester tester) async { final Widget child = getChild(); await tester.pumpWidget(CupertinoApp( home: CupertinoPageScaffold( child: Center( child: CupertinoContextMenu( actions: const <CupertinoContextMenuAction>[ CupertinoContextMenuAction( child: Text('CupertinoContextMenuAction One'), ), ], child: child, ), ), ), ));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); await gesture.addPointer(location: const Offset(10, 10)); await tester.pumpAndSettle(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
final Offset contextMenu = tester.getCenter(find.byWidget(child)); await gesture.moveTo(contextMenu); await tester.pumpAndSettle(); expect( RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), kIsWeb ? SystemMouseCursors.click : SystemMouseCursors.basic, ); });
testWidgets('CupertinoContextMenu is in the correct position when within a Transform.scale', (WidgetTester tester) async { final Widget child = getChild(); await tester.pumpWidget(CupertinoApp( home: CupertinoPageScaffold( child: MediaQuery( data: const MediaQueryData(size: Size(800, 600)), child: Transform.scale( scale: 0.5, child: Align( //alignment: Alignment.bottomRight, child: CupertinoContextMenu( actions: const <CupertinoContextMenuAction>[ CupertinoContextMenuAction( child: Text('CupertinoContextMenuAction'), ), ], child: child ), ) ) ) ) )); expect(find.byWidget(child), findsOneWidget); final Rect childRect = tester.getRect(find.byWidget(child)); expect(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DecoyChild'), findsNothing);
// Start a press on the child. final TestGesture gesture = await tester.startGesture(childRect.center); await tester.pump();
// The _DecoyChild is showing directly on top of the child. expect(findDecoyChild(child), findsOneWidget); Rect decoyChildRect = tester.getRect(findDecoyChild(child)); expect(childRect, equals(decoyChildRect));
expect(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DecoyChild'), findsOneWidget);
// After a small delay, the _DecoyChild has begun to animate. await tester.pump(const Duration(milliseconds: 400)); decoyChildRect = tester.getRect(findDecoyChild(child)); expect(childRect, isNot(equals(decoyChildRect)));
// Eventually the decoy fully scales by _kOpenSize. await tester.pump(const Duration(milliseconds: 800)); decoyChildRect = tester.getRect(findDecoyChild(child)); expect(childRect, isNot(equals(decoyChildRect))); expect(decoyChildRect.width, childRect.width * kOpenScale);
// Then the CupertinoContextMenu opens. await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle(); expect(findStatic(), findsOneWidget); }); });
group('CupertinoContextMenu when open', () { testWidgets('Last action does not have border', (WidgetTester tester) async { final Widget child = getChild(); await tester.pumpWidget(CupertinoApp( home: CupertinoPageScaffold( child: Center( child: CupertinoContextMenu( actions: const <CupertinoContextMenuAction>[ CupertinoContextMenuAction( child: Text('CupertinoContextMenuAction One'), ), ], child: child, ), ), ), ));
// Open the CupertinoContextMenu final TestGesture firstGesture = await tester.startGesture(tester.getCenter(find.byWidget(child))); await tester.pumpAndSettle(); await firstGesture.up(); await tester.pumpAndSettle(); expect(findStatic(), findsOneWidget);
expect(findStaticChildDecoration(tester), findsNWidgets(1));
// Close the CupertinoContextMenu. await tester.tapAt(const Offset(1.0, 1.0)); await tester.pumpAndSettle(); expect(findStatic(), findsNothing);
await tester.pumpWidget(CupertinoApp( home: CupertinoPageScaffold( child: Center( child: CupertinoContextMenu( actions: const <CupertinoContextMenuAction>[ CupertinoContextMenuAction( child: Text('CupertinoContextMenuAction One'), ), CupertinoContextMenuAction( child: Text('CupertinoContextMenuAction Two'), ), ], child: child, ), ), ), ));
// Open the CupertinoContextMenu final TestGesture secondGesture = await tester.startGesture(tester.getCenter(find.byWidget(child))); await tester.pumpAndSettle(); await secondGesture.up(); await tester.pumpAndSettle(); expect(findStatic(), findsOneWidget);
expect(findStaticChildDecoration(tester), findsNWidgets(3)); });
testWidgets('Can close CupertinoContextMenu by background tap', (WidgetTester tester) async { final Widget child = getChild(); await tester.pumpWidget(getContextMenu(child: child));
// Open the CupertinoContextMenu final Rect childRect = tester.getRect(find.byWidget(child)); final TestGesture gesture = await tester.startGesture(childRect.center); await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle(); expect(findStatic(), findsOneWidget);
// Tap and ensure that the CupertinoContextMenu is closed. await tester.tapAt(const Offset(1.0, 1.0)); await tester.pumpAndSettle(); expect(findStatic(), findsNothing); });
testWidgets('Can close CupertinoContextMenu by dragging down', (WidgetTester tester) async { final Widget child = getChild(); await tester.pumpWidget(getContextMenu(child: child));
// Open the CupertinoContextMenu final Rect childRect = tester.getRect(find.byWidget(child)); final TestGesture gesture = await tester.startGesture(childRect.center); await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle(); expect(findStatic(), findsOneWidget);
// Drag down not far enough and it bounces back and doesn't close. expect(findStaticChild(child), findsOneWidget); Offset staticChildCenter = tester.getCenter(findStaticChild(child)); TestGesture swipeGesture = await tester.startGesture(staticChildCenter); await swipeGesture.moveBy( const Offset(0.0, 100.0), timeStamp: const Duration(milliseconds: 100), ); await tester.pump(); await swipeGesture.up(); await tester.pump(); expect(tester.getCenter(findStaticChild(child)).dy, greaterThan(staticChildCenter.dy)); await tester.pumpAndSettle(); expect(tester.getCenter(findStaticChild(child)), equals(staticChildCenter)); expect(findStatic(), findsOneWidget);
// Drag down far enough and it does close. expect(findStaticChild(child), findsOneWidget); staticChildCenter = tester.getCenter(findStaticChild(child)); swipeGesture = await tester.startGesture(staticChildCenter); await swipeGesture.moveBy( const Offset(0.0, 200.0), timeStamp: const Duration(milliseconds: 100), ); await tester.pump(); await swipeGesture.up(); await tester.pumpAndSettle(); expect(findStatic(), findsNothing); });
testWidgets('Can close CupertinoContextMenu by flinging down', (WidgetTester tester) async { final Widget child = getChild(); await tester.pumpWidget(getContextMenu(child: child));
// Open the CupertinoContextMenu final Rect childRect = tester.getRect(find.byWidget(child)); final TestGesture gesture = await tester.startGesture(childRect.center); await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle(); expect(findStatic(), findsOneWidget);
// Fling up and nothing happens. expect(findStaticChild(child), findsOneWidget); await tester.fling(findStaticChild(child), const Offset(0.0, -100.0), 1000.0); await tester.pumpAndSettle(); expect(findStaticChild(child), findsOneWidget);
// Fling down to close the menu. expect(findStaticChild(child), findsOneWidget); await tester.fling(findStaticChild(child), const Offset(0.0, 100.0), 1000.0); await tester.pumpAndSettle(); expect(findStatic(), findsNothing); });
testWidgets("Backdrop is added using ModalRoute's filter parameter", (WidgetTester tester) async { final Widget child = getChild(); await tester.pumpWidget(getContextMenu(child: child)); expect(find.byType(BackdropFilter), findsNothing);
// Open the CupertinoContextMenu final Rect childRect = tester.getRect(find.byWidget(child)); final TestGesture gesture = await tester.startGesture(childRect.center); await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle(); expect(findStatic(), findsOneWidget); expect(find.byType(BackdropFilter), findsOneWidget); });
testWidgets('Preview widget should have the correct border radius', (WidgetTester tester) async { final Widget child = getChild(); await tester.pumpWidget(getContextMenu(child: child));
// Open the CupertinoContextMenu. final Rect childRect = tester.getRect(find.byWidget(child)); final TestGesture gesture = await tester.startGesture(childRect.center); await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle(); expect(findStatic(), findsOneWidget);
// Check border radius. expect(findStaticDefaultPreview(), findsOneWidget); final ClipRRect previewWidget = tester.firstWidget(findStaticDefaultPreview()) as ClipRRect; expect(previewWidget.borderRadius, equals(BorderRadius.circular(12.0))); });
testWidgets('CupertinoContextMenu width is correct', (WidgetTester tester) async { final Widget child = getChild(); await tester.pumpWidget(getContextMenu(child: child)); expect(find.byWidget(child), findsOneWidget); final Rect childRect = tester.getRect(find.byWidget(child)); expect(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DecoyChild'), findsNothing);
// Start a press on the child. final TestGesture gesture = await tester.startGesture(childRect.center); await tester.pump();
// The _DecoyChild is showing directly on top of the child. expect(findDecoyChild(child), findsOneWidget); Rect decoyChildRect = tester.getRect(findDecoyChild(child)); expect(childRect, equals(decoyChildRect));
expect(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_DecoyChild'), findsOneWidget);
// After a small delay, the _DecoyChild has begun to animate. await tester.pump(const Duration(milliseconds: 400)); decoyChildRect = tester.getRect(findDecoyChild(child)); expect(childRect, isNot(equals(decoyChildRect)));
// Eventually the decoy fully scales by _kOpenSize. await tester.pump(const Duration(milliseconds: 800)); decoyChildRect = tester.getRect(findDecoyChild(child)); expect(childRect, isNot(equals(decoyChildRect))); expect(decoyChildRect.width, childRect.width * kOpenScale);
// Then the CupertinoContextMenu opens. await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle(); expect(findStatic(), findsOneWidget);
// The CupertinoContextMenu has the correct width and height. final CupertinoContextMenu widget = tester.widget(find.byType(CupertinoContextMenu)); for (final Widget action in widget.actions) { // The value of the height is 80 because of the font and icon size. expect(tester.getSize(find.byWidget(action)).width, 250); } });
testWidgets("ContextMenu route animation doesn't throw exception on dismiss", (WidgetTester tester) async { // This is a regression test for https://github.com/flutter/flutter/issues/124597. final List<int> items = List<int>.generate(2, (int index) => index).toList();
await tester.pumpWidget(CupertinoApp( home: CupertinoPageScaffold( child: StatefulBuilder( builder: (BuildContext context, StateSetter setState) { return ListView( children: items.map((int index) => CupertinoContextMenu( actions: <CupertinoContextMenuAction>[ CupertinoContextMenuAction( child: const Text('DELETE'), onPressed: () { setState(() { items.remove(index); Navigator.of(context).pop(); }); Navigator.of(context).pop(); }, ), ], child: Text('Item $index'), )).toList(), ); } ), ), ));
// Open the CupertinoContextMenu. final TestGesture gesture = await tester.startGesture(tester.getCenter(find.text('Item 1'))); await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle();
// Tap the delete action. await tester.tap(find.text('DELETE')); await tester.pumpAndSettle();
// The CupertinoContextMenu should be closed with no exception. expect(find.text('DELETE'), findsNothing); expect(tester.takeException(), null); }); });
group("Open layout differs depending on child's position on screen", () { testWidgets('Portrait', (WidgetTester tester) async { const Size portraitScreenSize = Size(600.0, 800.0); await binding.setSurfaceSize(portraitScreenSize);
// Pump a CupertinoContextMenu in the center of the screen and open it. final Widget child = getChild(); await tester.pumpWidget(getContextMenu( screenSize: portraitScreenSize, child: child, )); expect(find.byType(CupertinoContextMenuAction), findsNothing); Rect childRect = tester.getRect(find.byWidget(child)); TestGesture gesture = await tester.startGesture(childRect.center); await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle();
// The position of the action is in the center of the screen. expect(find.byType(CupertinoContextMenuAction), findsOneWidget); final Offset center = tester.getTopLeft(find.byType(CupertinoContextMenuAction));
// Close the CupertinoContextMenu. await tester.tapAt(const Offset(1.0, 1.0)); await tester.pumpAndSettle(); expect(findStatic(), findsNothing);
// Pump a CupertinoContextMenu on the left of the screen and open it. await tester.pumpWidget(getContextMenu( alignment: Alignment.centerLeft, screenSize: portraitScreenSize, child: child, )); expect(find.byType(CupertinoContextMenuAction), findsNothing); await tester.pumpAndSettle(); childRect = tester.getRect(find.byWidget(child)); gesture = await tester.startGesture(childRect.center); await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle();
// The position of the action is on the left of the screen. expect(find.byType(CupertinoContextMenuAction), findsOneWidget); final Offset left = tester.getTopLeft(find.byType(CupertinoContextMenuAction)); expect(left.dx, lessThan(center.dx));
// Close the CupertinoContextMenu. await tester.tapAt(const Offset(1.0, 1.0)); await tester.pumpAndSettle(); expect(findStatic(), findsNothing);
// Pump a CupertinoContextMenu on the right of the screen and open it. await tester.pumpWidget(getContextMenu( alignment: Alignment.centerRight, screenSize: portraitScreenSize, child: child, )); expect(find.byType(CupertinoContextMenuAction), findsNothing); childRect = tester.getRect(find.byWidget(child)); gesture = await tester.startGesture(childRect.center); await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle();
// The position of the action is on the right of the screen. expect(find.byType(CupertinoContextMenuAction), findsOneWidget); final Offset right = tester.getTopLeft(find.byType(CupertinoContextMenuAction)); expect(right.dx, greaterThan(center.dx));
// Set the screen back to its normal size. await binding.setSurfaceSize(const Size(800.0, 600.0)); });
testWidgets('Landscape', (WidgetTester tester) async { // Pump a CupertinoContextMenu in the center of the screen and open it. final Widget child = getChild(); await tester.pumpWidget(getContextMenu( child: child, )); expect(find.byType(CupertinoContextMenuAction), findsNothing); Rect childRect = tester.getRect(find.byWidget(child)); TestGesture gesture = await tester.startGesture(childRect.center); await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle();
// Landscape doesn't support a centered action list, so the action is on // the left side of the screen. expect(find.byType(CupertinoContextMenuAction), findsOneWidget); final Offset center = tester.getTopLeft(find.byType(CupertinoContextMenuAction));
// Close the CupertinoContextMenu. await tester.tapAt(const Offset(1.0, 1.0)); await tester.pumpAndSettle(); expect(findStatic(), findsNothing);
// Pump a CupertinoContextMenu on the left of the screen and open it. await tester.pumpWidget(getContextMenu( alignment: Alignment.centerLeft, child: child, )); expect(find.byType(CupertinoContextMenuAction), findsNothing); childRect = tester.getRect(find.byWidget(child)); gesture = await tester.startGesture(childRect.center); await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle();
// The position of the action is on the right of the screen, which is the // same as for center aligned children in landscape. expect(find.byType(CupertinoContextMenuAction), findsOneWidget); final Offset left = tester.getTopLeft(find.byType(CupertinoContextMenuAction)); expect(left.dx, equals(center.dx));
// Close the CupertinoContextMenu. await tester.tapAt(const Offset(1.0, 1.0)); await tester.pumpAndSettle(); expect(findStatic(), findsNothing);
// Pump a CupertinoContextMenu on the right of the screen and open it. await tester.pumpWidget(getContextMenu( alignment: Alignment.centerRight, child: child, )); expect(find.byType(CupertinoContextMenuAction), findsNothing); childRect = tester.getRect(find.byWidget(child)); gesture = await tester.startGesture(childRect.center); await tester.pumpAndSettle(); await gesture.up(); await tester.pumpAndSettle();
// The position of the action is on the left of the screen. expect(find.byType(CupertinoContextMenuAction), findsOneWidget); final Offset right = tester.getTopLeft(find.byType(CupertinoContextMenuAction)); expect(right.dx, lessThan(left.dx)); }); });
testWidgets('Conflicting gesture detectors', (WidgetTester tester) async { int? onPointerDownTime; int? onPointerUpTime; bool insideTapTriggered = false; // The required duration of the route to be pushed in is [500, 900]ms. // 500ms is calculated from kPressTimeout+_previewLongPressTimeout/2. // 900ms is calculated from kPressTimeout+_previewLongPressTimeout. const Duration pressDuration = Duration(milliseconds: 501);
int now() => clock.now().millisecondsSinceEpoch;
await tester.pumpWidget(Listener( onPointerDown: (PointerDownEvent event) => onPointerDownTime = now(), onPointerUp: (PointerUpEvent event) => onPointerUpTime = now(), child: CupertinoApp( home: Align( child: CupertinoContextMenu( actions: const <CupertinoContextMenuAction>[ CupertinoContextMenuAction( child: Text('CupertinoContextMenuAction'), ), ], child: GestureDetector( onTap: () => insideTapTriggered = true, child: Container( width: 200, height: 200, key: const Key('container'), color: const Color(0xFF00FF00), ), ), ), ), ), ));
// Start a press on the child. final TestGesture gesture = await tester.createGesture(); await gesture.down(tester.getCenter(find.byKey(const Key('container')))); // Simulate the actual situation: // the user keeps pressing and requesting frames. // If there is only one frame, // the animation is mutant and cannot drive the value of the animation controller. for (int i = 0; i < 100; i++) { await tester.pump(pressDuration ~/ 100); } await gesture.up(); // Await pushing route. await tester.pumpAndSettle();
// Judge whether _ContextMenuRouteStatic present on the screen. final Finder routeStatic = find.byWidgetPredicate( (Widget w) => '${w.runtimeType}' == '_ContextMenuRouteStatic', );
// The insideTap and the route should not be triggered at the same time. if (insideTapTriggered) { // Calculate the actual duration. final int actualDuration = onPointerUpTime! - onPointerDownTime!;
expect(routeStatic, findsNothing, reason: 'When actualDuration($actualDuration) is in the range of 500ms~900ms, ' 'which means the route is pushed, ' 'but insideTap should not be triggered at the same time.'); } else { // The route should be pushed when the insideTap is not triggered. expect(routeStatic, findsOneWidget); } });}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982// 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.
// reduced-test-set:// 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 'dart:ui';
import 'package:flutter/cupertino.dart';import 'package:flutter/material.dart';import 'package:flutter/rendering.dart';import 'package:flutter_test/flutter_test.dart';
// TODO(yjbanov): on the web text rendered with perspective produces flaky goldens: https://github.com/flutter/flutter/issues/110785const bool skipPerspectiveTextGoldens = isBrowser;
// A number of the hit tests below say "warnIfMissed: false". This is because// the way the CupertinoPicker works, the hits don't actually reach the labels,// the scroll view intercepts them.
// scrolling by this offset will move the picker to the next itemconst Offset _kRowOffset = Offset(0.0, -50.0);
void main() { group('Countdown timer picker', () { testWidgets('initialTimerDuration falls within limit', (WidgetTester tester) async { expect( () { CupertinoTimerPicker( onTimerDurationChanged: (_) { }, initialTimerDuration: const Duration(days: 1), ); }, throwsAssertionError, );
expect( () { CupertinoTimerPicker( onTimerDurationChanged: (_) { }, initialTimerDuration: const Duration(seconds: -1), ); }, throwsAssertionError, ); });
testWidgets('minuteInterval is positive and is a factor of 60', (WidgetTester tester) async { expect( () { CupertinoTimerPicker( onTimerDurationChanged: (_) { }, minuteInterval: 0, ); }, throwsAssertionError, ); expect( () { CupertinoTimerPicker( onTimerDurationChanged: (_) { }, minuteInterval: -1, ); }, throwsAssertionError, ); expect( () { CupertinoTimerPicker( onTimerDurationChanged: (_) { }, minuteInterval: 7, ); }, throwsAssertionError, ); });
testWidgets('secondInterval is positive and is a factor of 60', (WidgetTester tester) async { expect( () { CupertinoTimerPicker( onTimerDurationChanged: (_) { }, secondInterval: 0, ); }, throwsAssertionError, ); expect( () { CupertinoTimerPicker( onTimerDurationChanged: (_) { }, secondInterval: -1, ); }, throwsAssertionError, ); expect( () { CupertinoTimerPicker( onTimerDurationChanged: (_) { }, secondInterval: 7, ); }, throwsAssertionError, ); });
testWidgets('background color default value', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: CupertinoTimerPicker( onTimerDurationChanged: (_) { }, ), ), );
final Iterable<CupertinoPicker> pickers = tester.allWidgets.whereType<CupertinoPicker>(); expect(pickers.any((CupertinoPicker picker) => picker.backgroundColor != null), false); });
testWidgets('background color can be null', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: CupertinoTimerPicker( onTimerDurationChanged: (_) { }, ), ), );
expect(tester.takeException(), isNull); });
testWidgets('specified background color is applied', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: CupertinoTimerPicker( onTimerDurationChanged: (_) { }, backgroundColor: CupertinoColors.black, ), ), );
final Iterable<CupertinoPicker> pickers = tester.allWidgets.whereType<CupertinoPicker>(); expect(pickers.any((CupertinoPicker picker) => picker.backgroundColor != CupertinoColors.black), false); });
testWidgets('specified item extent value is applied', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: CupertinoTimerPicker( itemExtent: 42, onTimerDurationChanged: (_) { }, ), ), );
final Iterable<CupertinoPicker> pickers = tester.allWidgets.whereType<CupertinoPicker>(); expect(pickers.any((CupertinoPicker picker) => picker.itemExtent != 42), false); });
testWidgets('columns are ordered correctly when text direction is ltr', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: CupertinoTimerPicker( onTimerDurationChanged: (_) { }, initialTimerDuration: const Duration(hours: 12, minutes: 30, seconds: 59), ), ), );
Offset lastOffset = tester.getTopLeft(find.text('12'));
expect(tester.getTopLeft(find.text('hours')).dx > lastOffset.dx, true); lastOffset = tester.getTopLeft(find.text('hours'));
expect(tester.getTopLeft(find.text('30')).dx > lastOffset.dx, true); lastOffset = tester.getTopLeft(find.text('30'));
expect(tester.getTopLeft(find.text('min.')).dx > lastOffset.dx, true); lastOffset = tester.getTopLeft(find.text('min.'));
expect(tester.getTopLeft(find.text('59')).dx > lastOffset.dx, true); lastOffset = tester.getTopLeft(find.text('59'));
expect(tester.getTopLeft(find.text('sec.')).dx > lastOffset.dx, true); });
testWidgets('columns are ordered correctly when text direction is rtl', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Directionality( textDirection: TextDirection.rtl, child: CupertinoTimerPicker( onTimerDurationChanged: (_) { }, initialTimerDuration: const Duration(hours: 12, minutes: 30, seconds: 59), ), ), ), );
Offset lastOffset = tester.getTopLeft(find.text('12'));
expect(tester.getTopLeft(find.text('hours')).dx > lastOffset.dx, false); lastOffset = tester.getTopLeft(find.text('hours'));
expect(tester.getTopLeft(find.text('30')).dx > lastOffset.dx, false); lastOffset = tester.getTopLeft(find.text('30'));
expect(tester.getTopLeft(find.text('min.')).dx > lastOffset.dx, false); lastOffset = tester.getTopLeft(find.text('min.'));
expect(tester.getTopLeft(find.text('59')).dx > lastOffset.dx, false); lastOffset = tester.getTopLeft(find.text('59'));
expect(tester.getTopLeft(find.text('sec.')).dx > lastOffset.dx, false); });
testWidgets('width of picker is consistent', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: SizedBox( height: 400.0, width: 400.0, child: CupertinoTimerPicker( onTimerDurationChanged: (_) { }, initialTimerDuration: const Duration(hours: 12, minutes: 30, seconds: 59), ), ), ), );
// Distance between the first column and the last column. final double distance = tester.getCenter(find.text('sec.')).dx - tester.getCenter(find.text('12')).dx;
await tester.pumpWidget( CupertinoApp( home: SizedBox( height: 400.0, width: 800.0, child: CupertinoTimerPicker( onTimerDurationChanged: (_) { }, initialTimerDuration: const Duration(hours: 12, minutes: 30, seconds: 59), ), ), ), );
// Distance between the first and the last column should be the same. expect( tester.getCenter(find.text('sec.')).dx - tester.getCenter(find.text('12')).dx, distance, ); }); });
testWidgets('picker honors minuteInterval and secondInterval', (WidgetTester tester) async { late Duration duration; await tester.pumpWidget( CupertinoApp( home: SizedBox( height: 400.0, width: 400.0, child: CupertinoTimerPicker( minuteInterval: 10, secondInterval: 12, initialTimerDuration: const Duration(hours: 10, minutes: 40, seconds: 48), onTimerDurationChanged: (Duration d) { duration = d; }, ), ), ), ); await tester.drag(find.text('40'), _kRowOffset, warnIfMissed: false); // see top of file await tester.pump(); await tester.drag(find.text('48'), -_kRowOffset, warnIfMissed: false); // see top of file await tester.pump(); await tester.pump(const Duration(milliseconds: 500));
expect( duration, const Duration(hours: 10, minutes: 50, seconds: 36), ); });
group('Date picker', () { testWidgets('initial date is set to default value', (WidgetTester tester) async { final CupertinoDatePicker picker = CupertinoDatePicker( onDateTimeChanged: (_) { }, ); expect(picker.initialDateTime, isNotNull); });
testWidgets('background color default value', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: CupertinoDatePicker( onDateTimeChanged: (_) { }, ), ), );
final Iterable<CupertinoPicker> pickers = tester.allWidgets.whereType<CupertinoPicker>(); expect(pickers.any((CupertinoPicker picker) => picker.backgroundColor != null), false); });
testWidgets('background color can be null', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: CupertinoDatePicker( onDateTimeChanged: (_) { }, ), ), );
expect(tester.takeException(), isNull); });
testWidgets('specified background color is applied', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: CupertinoDatePicker( onDateTimeChanged: (_) { }, backgroundColor: CupertinoColors.black, ), ), );
final Iterable<CupertinoPicker> pickers = tester.allWidgets.whereType<CupertinoPicker>(); expect(pickers.any((CupertinoPicker picker) => picker.backgroundColor != CupertinoColors.black), false); });
testWidgets('specified item extent value is applied', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: CupertinoDatePicker( itemExtent: 55, onDateTimeChanged: (_) { }, ), ), );
final Iterable<CupertinoPicker> pickers = tester.allWidgets.whereType<CupertinoPicker>(); expect(pickers.any((CupertinoPicker picker) => picker.itemExtent != 55), false); });
testWidgets('initial date honors minuteInterval', (WidgetTester tester) async { late DateTime newDateTime; await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( width: 400, height: 400, child: CupertinoDatePicker( onDateTimeChanged: (DateTime d) => newDateTime = d, initialDateTime: DateTime(2018, 10, 10, 10, 3), minuteInterval: 3, ), ), ), ), );
// Drag the minute picker to the next slot (03 -> 06). // The `initialDateTime` and the `minuteInterval` values are specifically chosen // so that `find.text` finds exactly one widget. await tester.drag(find.text('03'), _kRowOffset, warnIfMissed: false); // see top of file await tester.pump();
expect(newDateTime.minute, 6); });
test('initial date honors minimumDate & maximumDate', () { expect(() { CupertinoDatePicker( onDateTimeChanged: (DateTime d) { }, initialDateTime: DateTime(2018, 10, 10), minimumDate: DateTime(2018, 10, 11), ); }, throwsAssertionError, );
expect(() { CupertinoDatePicker( onDateTimeChanged: (DateTime d) { }, initialDateTime: DateTime(2018, 10, 10), maximumDate: DateTime(2018, 10, 9), ); }, throwsAssertionError, ); });
testWidgets('changing initialDateTime after first build does not do anything', (WidgetTester tester) async { late DateTime selectedDateTime; await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( onDateTimeChanged: (DateTime dateTime) => selectedDateTime = dateTime, initialDateTime: DateTime(2018, 1, 1, 10, 30), ), ), ), ), );
await tester.drag(find.text('10'), const Offset(0.0, 32.0), touchSlopY: 0, warnIfMissed: false); // see top of file await tester.pump(); await tester.pump(const Duration(milliseconds: 500));
expect(selectedDateTime, DateTime(2018, 1, 1, 9, 30));
await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( onDateTimeChanged: (DateTime dateTime) => selectedDateTime = dateTime, // Change the initial date, but it shouldn't affect the present state. initialDateTime: DateTime(2016, 4, 5, 15), ), ), ), ), );
await tester.drag(find.text('9'), const Offset(0.0, 32.0), touchSlopY: 0, warnIfMissed: false); // see top of file await tester.pump(); await tester.pump(const Duration(milliseconds: 500));
// Moving up an hour is still based on the original initial date time. expect(selectedDateTime, DateTime(2018, 1, 1, 8, 30)); });
testWidgets('date picker has expected string', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.date, onDateTimeChanged: (_) { }, initialDateTime: DateTime(2018, 9, 15), ), ), ), ), );
expect(find.text('September'), findsOneWidget); expect(find.text('9'), findsOneWidget); expect(find.text('2018'), findsOneWidget); });
testWidgets('datetime picker has expected string', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( onDateTimeChanged: (_) { }, initialDateTime: DateTime(2018, 9, 15, 3, 14), ), ), ), ), );
expect(find.text('Sat Sep 15'), findsOneWidget); expect(find.text('3'), findsOneWidget); expect(find.text('14'), findsOneWidget); expect(find.text('AM'), findsOneWidget); });
testWidgets('monthYear picker has expected string', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.monthYear, onDateTimeChanged: (_) { }, initialDateTime: DateTime(2018, 9), ), ), ), ), );
expect(find.text('September'), findsOneWidget); expect(find.text('2018'), findsOneWidget); });
testWidgets('width of picker in date and time mode is consistent', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Directionality( textDirection: TextDirection.ltr, child: CupertinoDatePicker( onDateTimeChanged: (_) { }, initialDateTime: DateTime(2018, 1, 1, 10, 30), ), ), ), );
// Distance between the first column and the last column. final double distance = tester.getCenter(find.text('Mon Jan 1 ')).dx - tester.getCenter(find.text('AM')).dx;
await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 800.0, child: CupertinoDatePicker( onDateTimeChanged: (_) { }, initialDateTime: DateTime(2018, 1, 1, 10, 30), ), ), ), ), );
// Distance between the first and the last column should be the same. expect( tester.getCenter(find.text('Mon Jan 1 ')).dx - tester.getCenter(find.text('AM')).dx, distance, ); });
testWidgets('width of picker in date mode is consistent', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.date, onDateTimeChanged: (_) { }, initialDateTime: DateTime(2018, 1, 1, 10, 30), ), ), ), ), );
// Distance between the first column and the last column. final double distance = tester.getCenter(find.text('January')).dx - tester.getCenter(find.text('2018')).dx;
await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 800.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.date, onDateTimeChanged: (_) { }, initialDateTime: DateTime(2018, 1, 1, 10, 30), ), ), ), ), );
// Distance between the first and the last column should be the same. expect( tester.getCenter(find.text('January')).dx - tester.getCenter(find.text('2018')).dx, distance, ); });
testWidgets('width of picker in time mode is consistent', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.time, onDateTimeChanged: (_) { }, initialDateTime: DateTime(2018, 1, 1, 10, 30), ), ), ), ), );
// Distance between the first column and the last column. final double distance = tester.getCenter(find.text('10')).dx - tester.getCenter(find.text('AM')).dx;
await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 800.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.time, onDateTimeChanged: (_) { }, initialDateTime: DateTime(2018, 1, 1, 10, 30), ), ), ), ), );
// Distance between the first and the last column should be the same. expect( tester.getCenter(find.text('10')).dx - tester.getCenter(find.text('AM')).dx, moreOrLessEquals(distance), ); });
testWidgets('width of picker in monthYear mode is consistent', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.monthYear, onDateTimeChanged: (_) { }, initialDateTime: DateTime(2018), ), ), ), ), );
// Distance between the first column and the last column. final double distance = tester.getCenter(find.text('January')).dx - tester.getCenter(find.text('2018')).dx;
await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 800.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.monthYear, onDateTimeChanged: (_) { }, initialDateTime: DateTime(2018), ), ), ), ), );
// Distance between the first and the last column should be the same. expect( tester.getCenter(find.text('January')).dx - tester.getCenter(find.text('2018')).dx, distance, ); });
testWidgets('wheel does not bend outwards', (WidgetTester tester) async {
final Widget dateWidget = CupertinoDatePicker( mode: CupertinoDatePickerMode.date, onDateTimeChanged: (_) { }, initialDateTime: DateTime(2018, 1, 1, 10, 30), );
const String centerMonth = 'January'; const List<String> visibleMonthsExceptTheCenter = <String>[ 'September', 'October', 'November', 'December', 'February', 'March', 'April', 'May', ];
await tester.pumpWidget( CupertinoApp( home: CupertinoPageScaffold( child: Center( child: SizedBox( height: 200.0, width: 300.0, child: dateWidget, ), ), ), ), );
// The wheel does not bend outwards. for (final String month in visibleMonthsExceptTheCenter) { expect( tester.getBottomLeft(find.text(centerMonth)).dx, lessThan(tester.getBottomLeft(find.text(month)).dx), ); }
await tester.pumpWidget( CupertinoApp( home: CupertinoPageScaffold( child: Center( child: SizedBox( height: 200.0, width: 3000.0, child: dateWidget, ), ), ), ), );
// The wheel does not bend outwards at large widths. for (final String month in visibleMonthsExceptTheCenter) { expect( tester.getBottomLeft(find.text(centerMonth)).dx, lessThan(tester.getBottomLeft(find.text(month)).dx), ); } });
testWidgets('picker automatically scrolls away from invalid date on month change', (WidgetTester tester) async { late DateTime date; await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.date, onDateTimeChanged: (DateTime newDate) { date = newDate; }, initialDateTime: DateTime(2018, 3, 30), ), ), ), ), );
await tester.drag(find.text('March'), const Offset(0, 32.0), touchSlopY: 0.0, warnIfMissed: false); // see top of file
// Momentarily, the 2018 and the incorrect 30 of February is aligned. expect( tester.getTopLeft(find.text('2018')).dy, tester.getTopLeft(find.text('30')).dy, ); await tester.pump(); // Once to trigger the post frame animate call. await tester.pump(); // Once to start the DrivenScrollActivity. await tester.pump(const Duration(milliseconds: 500));
expect( date, DateTime(2018, 2, 28), ); expect( tester.getTopLeft(find.text('2018')).dy, tester.getTopLeft(find.text('28')).dy, ); });
testWidgets( 'date picker automatically scrolls away from invalid date, ' "and onDateTimeChanged doesn't report these dates", (WidgetTester tester) async { late DateTime date; // 2016 is a leap year. final DateTime minimum = DateTime(2016, 2, 29); final DateTime maximum = DateTime(2018, 12, 31); await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.date, minimumDate: minimum, maximumDate: maximum, onDateTimeChanged: (DateTime newDate) { date = newDate; // Callback doesn't transiently go into invalid dates. expect(newDate.isAtSameMomentAs(minimum) || newDate.isAfter(minimum), isTrue); expect(newDate.isAtSameMomentAs(maximum) || newDate.isBefore(maximum), isTrue); }, initialDateTime: DateTime(2017, 2, 28), ), ), ), ), );
// 2017 has 28 days in Feb so 29 is greyed out. expect( tester.widget<Text>(find.text('29')).style!.color, isSameColorAs(CupertinoColors.inactiveGray.color), );
await tester.drag(find.text('2017'), const Offset(0.0, 32.0), touchSlopY: 0.0, warnIfMissed: false); // see top of file await tester.pump(); await tester.pumpAndSettle(); // Now the autoscrolling should happen.
expect( date, DateTime(2016, 2, 29), );
// 2016 has 29 days in Feb so 29 is not greyed out. expect( tester.widget<Text>(find.text('29')).style!.color, isNot(isSameColorAs(CupertinoColors.inactiveGray.color)), );
await tester.drag(find.text('2016'), const Offset(0.0, -32.0), touchSlopY: 0.0, warnIfMissed: false); // see top of file await tester.pump(); // Once to trigger the post frame animate call. await tester.pumpAndSettle();
expect( date, DateTime(2017, 2, 28), );
expect( tester.widget<Text>(find.text('29')).style!.color, isSameColorAs(CupertinoColors.inactiveGray.color), ); }, );
testWidgets( 'dateTime picker automatically scrolls away from invalid date, ' "and onDateTimeChanged doesn't report these dates", (WidgetTester tester) async { late DateTime date; final DateTime minimum = DateTime(2019, 11, 11, 3, 30); final DateTime maximum = DateTime(2019, 11, 11, 14, 59, 59); await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( minimumDate: minimum, maximumDate: maximum, onDateTimeChanged: (DateTime newDate) { date = newDate; // Callback doesn't transiently go into invalid dates. expect(minimum.isAfter(newDate), isFalse); expect(maximum.isBefore(newDate), isFalse); }, initialDateTime: DateTime(2019, 11, 11, 4), ), ), ), ), );
// 3:00 is valid but 2:00 should be invalid. expect( tester.widget<Text>(find.text('3')).style!.color, isNot(isSameColorAs(CupertinoColors.inactiveGray.color)), );
expect( tester.widget<Text>(find.text('2')).style!.color, isSameColorAs(CupertinoColors.inactiveGray.color), );
// 'PM' is greyed out. expect( tester.widget<Text>(find.text('PM')).style!.color, isSameColorAs(CupertinoColors.inactiveGray.color), );
await tester.drag(find.text('AM'), const Offset(0.0, -32.0), touchSlopY: 0.0, warnIfMissed: false); // see top of file await tester.pump(); await tester.pumpAndSettle(); // Now the autoscrolling should happen.
expect( date, DateTime(2019, 11, 11, 14, 59), );
// 3'o clock and 'AM' are now greyed out. expect( tester.widget<Text>(find.text('AM')).style!.color, isSameColorAs(CupertinoColors.inactiveGray.color), ); expect( tester.widget<Text>(find.text('3')).style!.color, isSameColorAs(CupertinoColors.inactiveGray.color), );
await tester.drag(find.text('PM'), const Offset(0.0, 32.0), touchSlopY: 0.0, warnIfMissed: false); // see top of file await tester.pump(); // Once to trigger the post frame animate call. await tester.pumpAndSettle();
// Returns to min date. expect( date, DateTime(2019, 11, 11, 3, 30), ); }, );
testWidgets( 'time picker automatically scrolls away from invalid date, ' "and onDateTimeChanged doesn't report these dates", (WidgetTester tester) async { late DateTime date; final DateTime minimum = DateTime(2019, 11, 11, 3, 30); final DateTime maximum = DateTime(2019, 11, 11, 14, 59, 59); await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.time, minimumDate: minimum, maximumDate: maximum, onDateTimeChanged: (DateTime newDate) { date = newDate; // Callback doesn't transiently go into invalid dates. expect(minimum.isAfter(newDate), isFalse); expect(maximum.isBefore(newDate), isFalse); }, initialDateTime: DateTime(2019, 11, 11, 4), ), ), ), ), );
// 3:00 is valid but 2:00 should be invalid. expect( tester.widget<Text>(find.text('3')).style!.color, isNot(isSameColorAs(CupertinoColors.inactiveGray.color)), );
expect( tester.widget<Text>(find.text('2')).style!.color, isSameColorAs(CupertinoColors.inactiveGray.color), );
// 'PM' is greyed out. expect( tester.widget<Text>(find.text('PM')).style!.color, isSameColorAs(CupertinoColors.inactiveGray.color), );
await tester.drag(find.text('AM'), const Offset(0.0, -32.0), touchSlopY: 0.0, warnIfMissed: false); // see top of file await tester.pump(); await tester.pumpAndSettle(); // Now the autoscrolling should happen.
expect( date, DateTime(2019, 11, 11, 14, 59), );
// 3'o clock and 'AM' are now greyed out. expect( tester.widget<Text>(find.text('AM')).style!.color, isSameColorAs(CupertinoColors.inactiveGray.color), ); expect( tester.widget<Text>(find.text('3')).style!.color, isSameColorAs(CupertinoColors.inactiveGray.color), );
await tester.drag(find.text('PM'), const Offset(0.0, 32.0), touchSlopY: 0.0, warnIfMissed: false); // see top of file await tester.pump(); // Once to trigger the post frame animate call. await tester.pumpAndSettle();
// Returns to min date. expect( date, DateTime(2019, 11, 11, 3, 30), ); }, );
testWidgets( 'monthYear picker automatically scrolls away from invalid date, ' "and onDateTimeChanged doesn't report these dates", (WidgetTester tester) async { late DateTime date; final DateTime minimum = DateTime(2016, 2); final DateTime maximum = DateTime(2018, 12); await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.monthYear, minimumDate: minimum, maximumDate: maximum, onDateTimeChanged: (DateTime newDate) { date = newDate; // Callback doesn't transiently go into invalid dates. expect(newDate.isAtSameMomentAs(minimum) || newDate.isAfter(minimum), isTrue); expect(newDate.isAtSameMomentAs(maximum) || newDate.isBefore(maximum), isTrue); }, initialDateTime: DateTime(2017, 2), ), ), ), ), );
await tester.drag(find.text('2017'), const Offset(0.0, 100.0), touchSlopY: 0.0, warnIfMissed: false); // see top of file await tester.pump(); await tester.pumpAndSettle(); // Now the autoscrolling should happen.
expect( date, DateTime(2016, 2), );
await tester.drag(find.text('2016'), const Offset(0.0, -100.0), touchSlopY: 0.0, warnIfMissed: false); // see top of file await tester.pump(); // Once to trigger the post frame animate call. await tester.pumpAndSettle();
expect( date, DateTime(2018, 12), );
await tester.drag(find.text('2016'), const Offset(0.0, 32.0), touchSlopY: 0.0, warnIfMissed: false); // see top of file await tester.pump(); // Once to trigger the post frame animate call. await tester.pumpAndSettle();
expect( date, DateTime(2017, 12), ); }, );
testWidgets('picker automatically scrolls away from invalid date on day change', (WidgetTester tester) async { late DateTime date; await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.date, onDateTimeChanged: (DateTime newDate) { date = newDate; }, initialDateTime: DateTime(2018, 2, 27), // 2018 has 28 days in Feb. ), ), ), ), );
await tester.drag(find.text('27'), const Offset(0.0, -32.0), touchSlopY: 0.0, warnIfMissed: false); // see top of file await tester.pump(); expect( date, DateTime(2018, 2, 28), );
await tester.drag(find.text('28'), const Offset(0.0, -32.0), touchSlopY: 0.0, warnIfMissed: false); // see top of file await tester.pump(); // Once to trigger the post frame animate call.
// Callback doesn't transiently go into invalid dates. expect( date, DateTime(2018, 2, 28), ); // Momentarily, the invalid 29th of Feb is dragged into the middle. expect( tester.getTopLeft(find.text('2018')).dy, tester.getTopLeft(find.text('29')).dy, );
await tester.pump(); // Once to start the DrivenScrollActivity. await tester.pump(const Duration(milliseconds: 500));
expect( date, DateTime(2018, 2, 28), ); expect( tester.getTopLeft(find.text('2018')).dy, tester.getTopLeft(find.text('28')).dy, ); });
testWidgets( 'date picker should only take into account the date part of minimumDate and maximumDate', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/49606. late DateTime date; final DateTime minDate = DateTime(2020, 1, 1, 12); await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.date, minimumDate: minDate, onDateTimeChanged: (DateTime newDate) { date = newDate; }, initialDateTime: DateTime(2020, 1, 12), ), ), ), ), );
// Scroll to 2019. await tester.drag(find.text('2020'), const Offset(0.0, 32.0), touchSlopY: 0.0, warnIfMissed: false); // see top of file await tester.pump(); await tester.pumpAndSettle(); expect(date.year, minDate.year); expect(date.month, minDate.month); expect(date.day, minDate.day); }, );
testWidgets('date picker does not display previous day of minimumDate if it is set at midnight', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/72932 final DateTime minDate = DateTime(2019, 12, 31); await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( minimumDate: minDate, onDateTimeChanged: (DateTime newDate) { }, initialDateTime: minDate.add(const Duration(days: 1)), ), ), ), ), );
expect(find.text('Mon Dec 30'), findsNothing); });
group('Picker handles initial noon/midnight times', () { testWidgets('midnight', (WidgetTester tester) async { late DateTime date; await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.time, onDateTimeChanged: (DateTime newDate) { date = newDate; }, initialDateTime: DateTime(2019, 1, 1, 0, 15), ), ), ), ), );
// 0:15 -> 0:16 await tester.drag(find.text('15'), _kRowOffset, warnIfMissed: false); // see top of file await tester.pump(); await tester.pump(const Duration(milliseconds: 500));
expect(date, DateTime(2019, 1, 1, 0, 16)); });
testWidgets('noon', (WidgetTester tester) async { late DateTime date; await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.time, onDateTimeChanged: (DateTime newDate) { date = newDate; }, initialDateTime: DateTime(2019, 1, 1, 12, 15), ), ), ), ), );
// 12:15 -> 12:16 await tester.drag(find.text('15'), _kRowOffset, warnIfMissed: false); // see top of file await tester.pump(); await tester.pump(const Duration(milliseconds: 500));
expect(date, DateTime(2019, 1, 1, 12, 16)); });
testWidgets('noon in 24 hour time', (WidgetTester tester) async { late DateTime date; await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( use24hFormat: true, mode: CupertinoDatePickerMode.time, onDateTimeChanged: (DateTime newDate) { date = newDate; }, initialDateTime: DateTime(2019, 1, 1, 12, 25), ), ), ), ), );
// 12:25 -> 12:26 await tester.drag(find.text('25'), _kRowOffset, warnIfMissed: false); // see top of file await tester.pump(); await tester.pump(const Duration(milliseconds: 500));
expect(date, DateTime(2019, 1, 1, 12, 26)); }); });
testWidgets('picker persists am/pm value when scrolling hours', (WidgetTester tester) async { late DateTime date; await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.time, onDateTimeChanged: (DateTime newDate) { date = newDate; }, initialDateTime: DateTime(2019, 1, 1, 3), ), ), ), ), );
// 3:00 -> 15:00 await tester.drag(find.text('AM'), _kRowOffset, warnIfMissed: false); // see top of file await tester.pump(); await tester.pump(const Duration(milliseconds: 500));
expect(date, DateTime(2019, 1, 1, 15));
// 15:00 -> 16:00 await tester.drag(find.text('3'), _kRowOffset, warnIfMissed: false); // see top of file await tester.pump(); await tester.pump(const Duration(milliseconds: 500));
expect(date, DateTime(2019, 1, 1, 16));
// 16:00 -> 4:00 await tester.drag(find.text('PM'), -_kRowOffset, warnIfMissed: false); // see top of file await tester.pump(); await tester.pump(const Duration(milliseconds: 500));
expect(date, DateTime(2019, 1, 1, 4));
// 4:00 -> 3:00 await tester.drag(find.text('4'), -_kRowOffset, warnIfMissed: false); // see top of file await tester.pump(); await tester.pump(const Duration(milliseconds: 500));
expect(date, DateTime(2019, 1, 1, 3)); });
testWidgets('picker automatically scrolls the am/pm column when the hour column changes enough', (WidgetTester tester) async { late DateTime date; await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.time, onDateTimeChanged: (DateTime newDate) { date = newDate; }, initialDateTime: DateTime(2018, 1, 1, 11, 59), ), ), ), ), );
const Offset deltaOffset = Offset(0.0, -18.0);
// 11:59 -> 12:59 await tester.drag(find.text('11'), _kRowOffset, warnIfMissed: false); // see top of file await tester.pump(); await tester.pump(const Duration(milliseconds: 500));
expect(date, DateTime(2018, 1, 1, 12, 59));
// 12:59 -> 11:59 await tester.drag(find.text('12'), -_kRowOffset, warnIfMissed: false); // see top of file await tester.pump(); await tester.pump(const Duration(milliseconds: 500));
expect(date, DateTime(2018, 1, 1, 11, 59));
// 11:59 -> 9:59 await tester.drag(find.text('11'), -((_kRowOffset - deltaOffset) * 2 + deltaOffset), warnIfMissed: false); // see top of file await tester.pump(); await tester.pump(const Duration(milliseconds: 500));
expect(date, DateTime(2018, 1, 1, 9, 59));
// 9:59 -> 15:59 await tester.drag(find.text('9'), (_kRowOffset - deltaOffset) * 6 + deltaOffset, warnIfMissed: false); // see top of file await tester.pump(); await tester.pump(const Duration(milliseconds: 500));
expect(date, DateTime(2018, 1, 1, 15, 59)); });
testWidgets('date picker given too narrow space horizontally shows message', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( // This is too small to draw the picker out fully. width: 100, child: CupertinoDatePicker( initialDateTime: DateTime(2019, 1, 1, 4), onDateTimeChanged: (_) {}, ), ), ), ), );
final dynamic exception = tester.takeException(); expect(exception, isFlutterError); expect( exception.toString(), contains('Insufficient horizontal space to render the CupertinoDatePicker'), ); });
testWidgets('DatePicker golden tests', (WidgetTester tester) async { Widget buildApp(CupertinoDatePickerMode mode) { return CupertinoApp( home: Center( child: SizedBox( width: 500, height: 400, child: RepaintBoundary( child: CupertinoDatePicker( key: ValueKey<CupertinoDatePickerMode>(mode), mode: mode, initialDateTime: DateTime(2019, 1, 1, 4, 12, 30), onDateTimeChanged: (_) {}, ), ), ), ), ); }
await tester.pumpWidget(buildApp(CupertinoDatePickerMode.time)); if (!skipPerspectiveTextGoldens) { await expectLater( find.byType(CupertinoDatePicker), matchesGoldenFile('date_picker_test.time.initial.png'), ); }
await tester.pumpWidget(buildApp(CupertinoDatePickerMode.date)); if (!skipPerspectiveTextGoldens) { await expectLater( find.byType(CupertinoDatePicker), matchesGoldenFile('date_picker_test.date.initial.png'), ); }
await tester.pumpWidget(buildApp(CupertinoDatePickerMode.monthYear)); if (!skipPerspectiveTextGoldens) { await expectLater( find.byType(CupertinoDatePicker), matchesGoldenFile('date_picker_test.monthyear.initial.png'), ); }
await tester.pumpWidget(buildApp(CupertinoDatePickerMode.dateAndTime)); if (!skipPerspectiveTextGoldens) { await expectLater( find.byType(CupertinoDatePicker), matchesGoldenFile('date_picker_test.datetime.initial.png'), ); }
// Slightly drag the hour component to make the current hour off-center. await tester.drag(find.text('4'), Offset(0, _kRowOffset.dy / 2), warnIfMissed: false); // see top of file await tester.pump();
if (!skipPerspectiveTextGoldens) { await expectLater( find.byType(CupertinoDatePicker), matchesGoldenFile('date_picker_test.datetime.drag.png'), ); } });
testWidgets('DatePicker displays the date in correct order', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( dateOrder: DatePickerDateOrder.ydm, mode: CupertinoDatePickerMode.date, onDateTimeChanged: (DateTime newDate) {}, initialDateTime: DateTime(2018, 1, 14, 10, 30), ), ), ), ), );
expect( tester.getTopLeft(find.text('2018')).dx, lessThan(tester.getTopLeft(find.text('14')).dx), );
expect( tester.getTopLeft(find.text('14')).dx, lessThan(tester.getTopLeft(find.text('January')).dx), ); });
testWidgets('monthYear DatePicker displays the date in correct order', (WidgetTester tester) async { Widget buildApp(DatePickerDateOrder order) { return CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( key: ValueKey<DatePickerDateOrder>(order), dateOrder: order, mode: CupertinoDatePickerMode.monthYear, onDateTimeChanged: (DateTime newDate) {}, initialDateTime: DateTime(2018, 1, 14, 10, 30), ), ), ), ); }
await tester.pumpWidget(buildApp(DatePickerDateOrder.dmy)); expect( tester.getTopLeft(find.text('January')).dx, lessThan(tester.getTopLeft(find.text('2018')).dx), );
await tester.pumpWidget(buildApp(DatePickerDateOrder.mdy)); expect( tester.getTopLeft(find.text('January')).dx, lessThan(tester.getTopLeft(find.text('2018')).dx), );
await tester.pumpWidget(buildApp(DatePickerDateOrder.ydm)); expect( tester.getTopLeft(find.text('2018')).dx, lessThan(tester.getTopLeft(find.text('January')).dx), );
await tester.pumpWidget(buildApp(DatePickerDateOrder.ymd)); expect( tester.getTopLeft(find.text('2018')).dx, lessThan(tester.getTopLeft(find.text('January')).dx), ); });
testWidgets('DatePicker displays hours and minutes correctly in RTL', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Directionality( textDirection: TextDirection.rtl, child: Center( child: SizedBox( width: 500, height: 400, child: CupertinoDatePicker( initialDateTime: DateTime(2019, 1, 1, 4), onDateTimeChanged: (_) {}, ), ), ), ), ), );
final double hourLeft = tester.getTopLeft(find.text('4')).dx; final double minuteLeft = tester.getTopLeft(find.text('00')).dx; expect(hourLeft, lessThan(minuteLeft)); }); });
testWidgets('TimerPicker golden tests', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( // Also check if the picker respects the theme. theme: const CupertinoThemeData( textTheme: CupertinoTextThemeData( pickerTextStyle: TextStyle( color: Color(0xFF663311), fontSize: 21, ), ), ), home: Center( child: SizedBox( width: 320, height: 216, child: RepaintBoundary( child: CupertinoTimerPicker( mode: CupertinoTimerPickerMode.hm, initialTimerDuration: const Duration(hours: 23, minutes: 59), onTimerDurationChanged: (_) {}, ), ), ), ), ), );
if (!skipPerspectiveTextGoldens) { await expectLater( find.byType(CupertinoTimerPicker), matchesGoldenFile('timer_picker_test.datetime.initial.png'), ); }
// Slightly drag the minute component to make the current minute off-center. await tester.drag(find.text('59'), Offset(0, _kRowOffset.dy / 2), warnIfMissed: false); // see top of file await tester.pump();
if (!skipPerspectiveTextGoldens) { await expectLater( find.byType(CupertinoTimerPicker), matchesGoldenFile('timer_picker_test.datetime.drag.png'), ); } });
testWidgets('TimerPicker only changes hour label after scrolling stops', (WidgetTester tester) async { Duration? duration; await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( width: 320, height: 216, child: CupertinoTimerPicker( mode: CupertinoTimerPickerMode.hm, initialTimerDuration: const Duration(hours: 2, minutes: 30), onTimerDurationChanged: (Duration d) { duration = d; }, ), ), ), ), );
expect(duration, isNull); expect(find.text('hour'), findsNothing); expect(find.text('hours'), findsOneWidget);
await tester.drag(find.text('2'), Offset(0, -_kRowOffset.dy), warnIfMissed: false); // see top of file // Duration should change but not the label. expect(duration!.inHours, 1); expect(find.text('hour'), findsNothing); expect(find.text('hours'), findsOneWidget); await tester.pumpAndSettle();
// Now the label should change. expect(duration!.inHours, 1); expect(find.text('hours'), findsNothing); expect(find.text('hour'), findsOneWidget); });
testWidgets('TimerPicker has intrinsic width and height', (WidgetTester tester) async { const Key key = Key('key');
await tester.pumpWidget( CupertinoApp( home: CupertinoTimerPicker( key: key, mode: CupertinoTimerPickerMode.hm, initialTimerDuration: const Duration(hours: 2, minutes: 30), onTimerDurationChanged: (Duration d) {}, ), ), );
expect(tester.getSize(find.descendant(of: find.byKey(key), matching: find.byType(Row))), const Size(320, 216));
// Different modes shouldn't share state. await tester.pumpWidget(const Placeholder()); await tester.pumpWidget( CupertinoApp( home: CupertinoTimerPicker( key: key, mode: CupertinoTimerPickerMode.ms, initialTimerDuration: const Duration(minutes: 30, seconds: 3), onTimerDurationChanged: (Duration d) {}, ), ), );
expect(tester.getSize(find.descendant(of: find.byKey(key), matching: find.byType(Row))), const Size(320, 216));
// Different modes shouldn't share state. await tester.pumpWidget(const Placeholder()); await tester.pumpWidget( CupertinoApp( home: CupertinoTimerPicker( key: key, initialTimerDuration: const Duration(hours: 5, minutes: 17, seconds: 19), onTimerDurationChanged: (Duration d) {}, ), ), );
expect(tester.getSize(find.descendant(of: find.byKey(key), matching: find.byType(Row))), const Size(342, 216)); });
testWidgets('scrollController can be removed or added', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); late int lastSelectedItem; void onSelectedItemChanged(int index) { lastSelectedItem = index; } final FixedExtentScrollController scrollController1 = FixedExtentScrollController(); addTearDown(scrollController1.dispose); await tester.pumpWidget(_buildPicker( controller: scrollController1, onSelectedItemChanged: onSelectedItemChanged, ));
tester.binding.pipelineOwner.semanticsOwner!.performAction(1, SemanticsAction.increase); await tester.pumpAndSettle(); expect(lastSelectedItem, 1);
await tester.pumpWidget(_buildPicker( onSelectedItemChanged: onSelectedItemChanged, ));
tester.binding.pipelineOwner.semanticsOwner!.performAction(1, SemanticsAction.increase); await tester.pumpAndSettle(); expect(lastSelectedItem, 2);
final FixedExtentScrollController scrollController2 = FixedExtentScrollController(); addTearDown(scrollController2.dispose); await tester.pumpWidget(_buildPicker( controller: scrollController2, onSelectedItemChanged: onSelectedItemChanged, ));
tester.binding.pipelineOwner.semanticsOwner!.performAction(1, SemanticsAction.increase); await tester.pumpAndSettle(); expect(lastSelectedItem, 3);
handle.dispose(); });
testWidgets('CupertinoDataPicker does not provide invalid MediaQuery', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/47989. Brightness brightness = Brightness.light; late StateSetter setState;
await tester.pumpWidget( CupertinoApp( theme: const CupertinoThemeData( textTheme: CupertinoTextThemeData( dateTimePickerTextStyle: TextStyle( color: CupertinoDynamicColor.withBrightness( color: Color(0xFFFFFFFF), darkColor: Color(0xFF000000), ), ), ), ), home: StatefulBuilder(builder: (BuildContext context, StateSetter stateSetter) { setState = stateSetter; return MediaQuery( data: MediaQuery.of(context).copyWith(platformBrightness: brightness), child: CupertinoDatePicker( initialDateTime: DateTime(2019), mode: CupertinoDatePickerMode.date, onDateTimeChanged: (DateTime date) {}, ), ); }), ), );
expect( tester.widget<Text>(find.text('2019')).style!.color, isSameColorAs(const Color(0xFFFFFFFF)), );
setState(() { brightness = Brightness.dark; }); await tester.pump();
expect( tester.widget<Text>(find.text('2019')).style!.color, isSameColorAs(const Color(0xFF000000)), ); });
testWidgets('picker exports semantics', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); debugResetSemanticsIdCounter(); int? lastSelectedItem; await tester.pumpWidget(_buildPicker(onSelectedItemChanged: (int index) { lastSelectedItem = index; }));
expect(tester.getSemantics(find.byType(CupertinoPicker)), matchesSemantics( children: <Matcher>[ matchesSemantics( hasIncreaseAction: true, increasedValue: '1', value: '0', textDirection: TextDirection.ltr, ), ], ));
tester.binding.pipelineOwner.semanticsOwner!.performAction(1, SemanticsAction.increase); await tester.pumpAndSettle();
expect(tester.getSemantics(find.byType(CupertinoPicker)), matchesSemantics( children: <Matcher>[ matchesSemantics( hasIncreaseAction: true, hasDecreaseAction: true, increasedValue: '2', decreasedValue: '0', value: '1', textDirection: TextDirection.ltr, ), ], )); expect(lastSelectedItem, 1); handle.dispose(); });
// Regression test for https://github.com/flutter/flutter/issues/98567 testWidgets('picker semantics action test', (WidgetTester tester) async { final SemanticsHandle handle = tester.ensureSemantics(); debugResetSemanticsIdCounter(); final DateTime initialDate = DateTime(2018, 6, 8); late DateTime? date; await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( onDateTimeChanged: (DateTime newDate) => date = newDate, initialDateTime: initialDate, maximumDate: initialDate.add(const Duration(days: 2)), minimumDate: initialDate.subtract(const Duration(days: 2)), ), ), ), ), );
tester.binding.pipelineOwner.semanticsOwner!.performAction(4, SemanticsAction.decrease); await tester.pumpAndSettle();
expect(date, DateTime(2018, 6, 7));
handle.dispose(); });
testWidgets('DatePicker adapts to MaterialApp dark mode', (WidgetTester tester) async { Widget buildDatePicker(Brightness brightness) { return MaterialApp( theme: ThemeData(brightness: brightness), home: CupertinoDatePicker( mode: CupertinoDatePickerMode.date, onDateTimeChanged: (DateTime neData) {}, initialDateTime: DateTime(2018, 10, 10), ), ); }
// CupertinoDatePicker with light theme. await tester.pumpWidget(buildDatePicker(Brightness.light)); RenderParagraph paragraph = tester.renderObject(find.text('October').first); expect(paragraph.text.style!.color, CupertinoColors.label); // Text style should not return unresolved color. expect(paragraph.text.style!.color.toString().contains('UNRESOLVED'), isFalse);
// CupertinoDatePicker with dark theme. await tester.pumpWidget(buildDatePicker(Brightness.dark)); paragraph = tester.renderObject(find.text('October').first); expect(paragraph.text.style!.color, CupertinoColors.label); // Text style should not return unresolved color. expect(paragraph.text.style!.color.toString().contains('UNRESOLVED'), isFalse); });
testWidgets('TimerPicker adapts to MaterialApp dark mode', (WidgetTester tester) async { Widget buildTimerPicker(Brightness brightness) { return MaterialApp( theme: ThemeData(brightness: brightness), home: CupertinoTimerPicker( mode: CupertinoTimerPickerMode.hm, onTimerDurationChanged: (Duration newDuration) {}, initialTimerDuration: const Duration(hours: 12, minutes: 30, seconds: 59), ), ); }
// CupertinoTimerPicker with light theme. await tester.pumpWidget(buildTimerPicker(Brightness.light)); RenderParagraph paragraph = tester.renderObject(find.text('hours')); expect(paragraph.text.style!.color, CupertinoColors.label); // Text style should not return unresolved color. expect(paragraph.text.style!.color.toString().contains('UNRESOLVED'), isFalse);
// CupertinoTimerPicker with light theme. await tester.pumpWidget(buildTimerPicker(Brightness.dark)); paragraph = tester.renderObject(find.text('hours')); expect(paragraph.text.style!.color, CupertinoColors.label); // Text style should not return unresolved color. expect(paragraph.text.style!.color.toString().contains('UNRESOLVED'), isFalse); });
testWidgets('TimerPicker minDate - maxDate with minuteInterval', (WidgetTester tester) async { late DateTime date; final DateTime minimum = DateTime(2022, 6, 14, 3, 31); final DateTime initial = DateTime(2022, 6, 14, 3, 40); final DateTime maximum = DateTime(2022, 6, 14, 3, 49); await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( initialDateTime: initial, minimumDate: minimum, maximumDate: maximum, minuteInterval: 5, use24hFormat: true, onDateTimeChanged: (DateTime newDate) { date = newDate; }, ), ), ), ), );
// Drag picker minutes to min date await tester.drag(find.text('40'), const Offset(0.0, 32.0), touchSlopY: 0.0, warnIfMissed: false); await tester.pumpAndSettle();
// Returns to min date. expect( date, DateTime(2022, 6, 14, 3, 35), );
// Drag picker minutes to max date await tester.drag(find.text('50'), const Offset(0.0, -64.0), touchSlopY: 0.0, warnIfMissed: false); await tester.pumpAndSettle();
// Returns to max date. expect( date, DateTime(2022, 6, 14, 3, 45), ); });
testWidgets('date picker has expected day of week', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: SizedBox( height: 400.0, width: 400.0, child: CupertinoDatePicker( mode: CupertinoDatePickerMode.date, onDateTimeChanged: (_) { }, initialDateTime: DateTime(2018, 9, 15), showDayOfWeek: true, ), ), ), ), );
expect(find.text('September'), findsOneWidget); expect(find.textContaining('Sat').last, findsOneWidget); expect(find.textContaining('15').last, findsOneWidget); expect(find.text('2018'), findsOneWidget); });}
Widget _buildPicker({ FixedExtentScrollController? controller, required ValueChanged<int> onSelectedItemChanged,}) { return Directionality( textDirection: TextDirection.ltr, child: CupertinoPicker( scrollController: controller, itemExtent: 100.0, onSelectedItemChanged: onSelectedItemChanged, children: List<Widget>.generate(100, (int index) { return Center( child: SizedBox( width: 400.0, height: 100.0, child: Text(index.toString()), ), ); }), ), );}1234567891011121314151617181920212223242526272829303132// 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_test/flutter_test.dart';
void main() { testWidgets('debugCheckHasCupertinoLocalizations throws', (WidgetTester tester) async { final GlobalKey noLocalizationsAvailable = GlobalKey(); final GlobalKey localizationsAvailable = GlobalKey();
await tester.pumpWidget( Container( key: noLocalizationsAvailable, child: CupertinoApp( home: Container( key: localizationsAvailable, ), ), ), );
expect(() => debugCheckHasCupertinoLocalizations(noLocalizationsAvailable.currentContext!), throwsA(isAssertionError.having( (AssertionError e) => e.message, 'message', contains('No CupertinoLocalizations found'), )));
expect(debugCheckHasCupertinoLocalizations(localizationsAvailable.currentContext!), isTrue); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133// 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/gestures.dart';import 'package:flutter_test/flutter_test.dart';
void main() { TestWidgetsFlutterBinding.ensureInitialized();
testWidgets('can press', (WidgetTester tester) async { bool pressed = false; await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoDesktopTextSelectionToolbarButton( onPressed: () { pressed = true; }, child: const Text('Tap me'), ), ), ), );
expect(pressed, false);
await tester.tap(find.byType(CupertinoDesktopTextSelectionToolbarButton)); expect(pressed, true); });
testWidgets('keeps contrast with background on hover', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoDesktopTextSelectionToolbarButton.text( text: 'Tap me', onPressed: () {}, ), ), ), );
final BuildContext context = tester.element(find.byType(CupertinoDesktopTextSelectionToolbarButton));
// The Text color is a CupertinoDynamicColor so we have to compare the color // values instead of just comparing the colors themselves. expect( (tester.firstWidget(find.text('Tap me')) as Text).style!.color!.value, CupertinoColors.black.value, );
// Hover gesture final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse); await gesture.addPointer(location: Offset.zero); addTearDown(gesture.removePointer); await tester.pump(); await gesture.moveTo(tester .getCenter(find.byType(CupertinoDesktopTextSelectionToolbarButton))); await tester.pumpAndSettle();
// The color here should be a standard Color, there's no need to use value. expect( (tester.firstWidget(find.text('Tap me')) as Text).style!.color, CupertinoTheme.of(context).primaryContrastingColor, ); });
testWidgets('pressedOpacity defaults to 0.1', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoDesktopTextSelectionToolbarButton( onPressed: () { }, child: const Text('Tap me'), ), ), ), );
// Original at full opacity. FadeTransition opacity = tester.widget(find.descendant( of: find.byType(CupertinoDesktopTextSelectionToolbarButton), matching: find.byType(FadeTransition), )); expect(opacity.opacity.value, 1.0);
// Make a "down" gesture on the button. final Offset center = tester .getCenter(find.byType(CupertinoDesktopTextSelectionToolbarButton)); final TestGesture gesture = await tester.startGesture(center); await tester.pumpAndSettle();
// Opacity reduces during the down gesture. opacity = tester.widget(find.descendant( of: find.byType(CupertinoDesktopTextSelectionToolbarButton), matching: find.byType(FadeTransition), )); expect(opacity.opacity.value, 0.7);
// Release the down gesture. await gesture.up(); await tester.pumpAndSettle();
// Opacity is back to normal. opacity = tester.widget(find.descendant( of: find.byType(CupertinoDesktopTextSelectionToolbarButton), matching: find.byType(FadeTransition), )); expect(opacity.opacity.value, 1.0); });
testWidgets('passing null to onPressed disables the button', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoDesktopTextSelectionToolbarButton( onPressed: null, child: Text('Tap me'), ), ), ), );
expect(find.byType(CupertinoButton), findsOneWidget); final CupertinoButton button = tester.widget(find.byType(CupertinoButton)); expect(button.enabled, isFalse); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146// 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/cupertino.dart';import 'package:flutter/foundation.dart';import 'package:flutter_test/flutter_test.dart';
void main() { TestWidgetsFlutterBinding.ensureInitialized();
testWidgets('has correct backdrop filters', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoDesktopTextSelectionToolbar( anchor: Offset.zero, children: <Widget>[ CupertinoDesktopTextSelectionToolbarButton( child: const Text('Tap me'), onPressed: () {}, ), ], ), ), ), );
final BackdropFilter toolbarFilter = tester.firstWidget<BackdropFilter>( find.descendant( of: find.byType(CupertinoDesktopTextSelectionToolbar), matching: find.byType(BackdropFilter), ), );
expect( toolbarFilter.filter.runtimeType, // _ComposeImageFilter is internal so we can't test if its filters are // for blur and saturation, but checking if it's a _ComposeImageFilter // should be enough. Outer and inner parameters don't matter, we just need // a new _ComposeImageFilter to get its runtimeType. // // As web doesn't support ImageFilter.compose, we use just blur when // kIsWeb. kIsWeb ? ImageFilter.blur().runtimeType : ImageFilter.compose( outer: ImageFilter.blur(), inner: ImageFilter.blur(), ).runtimeType, ); });
testWidgets('has shadow', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoDesktopTextSelectionToolbar( anchor: Offset.zero, children: <Widget>[ CupertinoDesktopTextSelectionToolbarButton( child: const Text('Tap me'), onPressed: () {}, ), ], ), ), ), );
final DecoratedBox decoratedBox = tester.firstWidget<DecoratedBox>( find.descendant( of: find.byType(CupertinoDesktopTextSelectionToolbar), matching: find.byType(DecoratedBox), ), );
expect( (decoratedBox.decoration as BoxDecoration).boxShadow, isNotNull, ); });
testWidgets('is translucent', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoDesktopTextSelectionToolbar( anchor: Offset.zero, children: <Widget>[ CupertinoDesktopTextSelectionToolbarButton( child: const Text('Tap me'), onPressed: () {}, ), ], ), ), ), );
final DecoratedBox decoratedBox = tester .widgetList<DecoratedBox>( find.descendant( of: find.byType(CupertinoDesktopTextSelectionToolbar), matching: find.byType(DecoratedBox), ), ) // The second DecoratedBox should be the one with color. .elementAt(1);
expect( (decoratedBox.decoration as BoxDecoration).color!.opacity, lessThan(1.0), ); });
testWidgets('positions itself at the anchor', (WidgetTester tester) async { // An arbitrary point on the screen to position at. const Offset anchor = Offset(30.0, 40.0);
await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoDesktopTextSelectionToolbar( anchor: anchor, children: <Widget>[ CupertinoDesktopTextSelectionToolbarButton( child: const Text('Tap me'), onPressed: () {}, ), ], ), ), ), );
expect( tester .getTopLeft(find.byType(CupertinoDesktopTextSelectionToolbarButton)), // Greater than due to padding internal to the toolbar. greaterThan(anchor), ); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644// 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 'dart:math';import 'dart:ui';
import 'package:flutter/cupertino.dart';import 'package:flutter/foundation.dart';import 'package:flutter/material.dart';import 'package:flutter/rendering.dart';import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
void main() { testWidgets('Alert dialog control test', (WidgetTester tester) async { bool didDelete = false;
await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( dialogBuilder: (BuildContext context) { return CupertinoAlertDialog( title: const Text('The title'), content: const Text('The content'), actions: <Widget>[ const CupertinoDialogAction( child: Text('Cancel'), ), CupertinoDialogAction( isDestructiveAction: true, onPressed: () { didDelete = true; Navigator.pop(context); }, child: const Text('Delete'), ), ], ); }, ), );
await tester.tap(find.text('Go')); await tester.pump();
expect(didDelete, isFalse);
await tester.tap(find.text('Delete')); await tester.pump();
expect(didDelete, isTrue); expect(find.text('Delete'), findsNothing); });
testWidgets('Dialog not barrier dismissible by default', (WidgetTester tester) async { await tester.pumpWidget(createAppWithCenteredButton(const Text('Go')));
final BuildContext context = tester.element(find.text('Go'));
showCupertinoDialog<void>( context: context, builder: (BuildContext context) { return Container( width: 100.0, height: 100.0, alignment: Alignment.center, child: const Text('Dialog'), ); }, );
await tester.pumpAndSettle(const Duration(seconds: 1)); expect(find.text('Dialog'), findsOneWidget);
// Tap on the barrier, which shouldn't do anything this time. await tester.tapAt(const Offset(10.0, 10.0));
await tester.pumpAndSettle(const Duration(seconds: 1)); expect(find.text('Dialog'), findsOneWidget);
});
testWidgets('Dialog configurable to be barrier dismissible', (WidgetTester tester) async { await tester.pumpWidget(createAppWithCenteredButton(const Text('Go')));
final BuildContext context = tester.element(find.text('Go'));
showCupertinoDialog<void>( context: context, barrierDismissible: true, builder: (BuildContext context) { return Container( width: 100.0, height: 100.0, alignment: Alignment.center, child: const Text('Dialog'), ); }, );
await tester.pumpAndSettle(const Duration(seconds: 1)); expect(find.text('Dialog'), findsOneWidget);
// Tap off the barrier. await tester.tapAt(const Offset(10.0, 10.0));
await tester.pumpAndSettle(const Duration(seconds: 1)); expect(find.text('Dialog'), findsNothing); });
testWidgets('Dialog destructive action style', (WidgetTester tester) async { await tester.pumpWidget(boilerplate(const CupertinoDialogAction( isDestructiveAction: true, child: Text('Ok'), )));
final DefaultTextStyle widget = tester.widget(find.byType(DefaultTextStyle));
expect(widget.style.color!.withAlpha(255), CupertinoColors.systemRed.color); });
testWidgets('Dialog default action style', (WidgetTester tester) async { await tester.pumpWidget( CupertinoTheme( data: const CupertinoThemeData( primaryColor: CupertinoColors.systemGreen, ), child: boilerplate(const CupertinoDialogAction( child: Text('Ok'), )), ), );
final DefaultTextStyle widget = tester.widget(find.byType(DefaultTextStyle));
expect(widget.style.color!.withAlpha(255), CupertinoColors.systemGreen.color); });
testWidgets('Dialog dark theme', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: MediaQuery( data: const MediaQueryData(platformBrightness: Brightness.dark), child: CupertinoAlertDialog( title: const Text('The Title'), content: const Text('Content'), actions: <Widget>[ CupertinoDialogAction( isDefaultAction: true, onPressed: () {}, child: const Text('Cancel'), ), const CupertinoDialogAction(child: Text('OK')), ], ), ), ), );
final RichText cancelText = tester.widget<RichText>( find.descendant(of: find.text('Cancel'), matching: find.byType(RichText)), );
expect( cancelText.text.style!.color!.value, 0xFF0A84FF, // dark elevated color of systemBlue. );
expect( find.byType(CupertinoAlertDialog), paints..rect(color: const Color(0xBF1E1E1E)), ); });
testWidgets('Has semantic annotations', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester); await tester.pumpWidget(const MaterialApp(home: Material( child: CupertinoAlertDialog( title: Text('The Title'), content: Text('Content'), actions: <Widget>[ CupertinoDialogAction(child: Text('Cancel')), CupertinoDialogAction(child: Text('OK')), ], ), )));
expect( semantics, hasSemantics( TestSemantics.root( children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.scopesRoute, SemanticsFlag.namesRoute], label: 'Alert', children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.hasImplicitScrolling, ], children: <TestSemantics>[ TestSemantics(label: 'The Title'), TestSemantics(label: 'Content'), ], ), TestSemantics( flags: <SemanticsFlag>[ SemanticsFlag.hasImplicitScrolling, ], children: <TestSemantics>[ TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isButton], label: 'Cancel', ), TestSemantics( flags: <SemanticsFlag>[SemanticsFlag.isButton], label: 'OK', ), ], ), ], ), ], ), ], ), ], ), ], ), ignoreId: true, ignoreRect: true, ignoreTransform: true, ), );
semantics.dispose(); });
testWidgets('Dialog default action style', (WidgetTester tester) async { await tester.pumpWidget(boilerplate(const CupertinoDialogAction( isDefaultAction: true, child: Text('Ok'), )));
final DefaultTextStyle widget = tester.widget(find.byType(DefaultTextStyle));
expect(widget.style.fontWeight, equals(FontWeight.w600)); });
testWidgets('Dialog default and destructive action styles', (WidgetTester tester) async { await tester.pumpWidget(boilerplate(const CupertinoDialogAction( isDefaultAction: true, isDestructiveAction: true, child: Text('Ok'), )));
final DefaultTextStyle widget = tester.widget(find.byType(DefaultTextStyle));
expect(widget.style.color!.withAlpha(255), CupertinoColors.systemRed.color); expect(widget.style.fontWeight, equals(FontWeight.w600)); });
testWidgets('Dialog disabled action style', (WidgetTester tester) async { await tester.pumpWidget(boilerplate(const CupertinoDialogAction( child: Text('Ok'), )));
final DefaultTextStyle widget = tester.widget(find.byType(DefaultTextStyle));
expect(widget.style.color!.opacity, greaterThanOrEqualTo(127 / 255)); expect(widget.style.color!.opacity, lessThanOrEqualTo(128 / 255)); });
testWidgets('Dialog enabled action style', (WidgetTester tester) async { await tester.pumpWidget(boilerplate(CupertinoDialogAction( child: const Text('Ok'), onPressed: () {}, )));
final DefaultTextStyle widget = tester.widget(find.byType(DefaultTextStyle));
expect(widget.style.color!.opacity, equals(1.0)); });
testWidgets('Message is scrollable, has correct padding with large text sizes', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( dialogBuilder: (BuildContext context) { return MediaQuery( data: MediaQuery.of(context).copyWith(textScaleFactor: 3.0), child: CupertinoAlertDialog( title: const Text('The Title'), content: Text('Very long content ' * 20), actions: const <Widget>[ CupertinoDialogAction( child: Text('Cancel'), ), CupertinoDialogAction( isDestructiveAction: true, child: Text('OK'), ), ], scrollController: scrollController, ), ); }, ), );
await tester.tap(find.text('Go')); await tester.pumpAndSettle();
expect(scrollController.offset, 0.0); scrollController.jumpTo(100.0); expect(scrollController.offset, 100.0); // Set the scroll position back to zero. scrollController.jumpTo(0.0);
await tester.pumpAndSettle();
// Expect the modal dialog box to take all available height. expect( tester.getSize(find.byType(ClipRRect)), equals(const Size(310.0, 560.0 - 24.0 * 2)), );
// Check sizes/locations of the text. The text is large so these 2 buttons are stacked. // Visually the "Cancel" button and "OK" button are the same height when using the // regular font. However, when using the test font, "Cancel" becomes 2 lines which // is why the height we're verifying for "Cancel" is larger than "OK".
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933 expect(tester.getSize(find.text('The Title')), equals(const Size(270.0, 132.0))); } expect(tester.getTopLeft(find.text('The Title')), equals(const Offset(265.0, 80.0 + 24.0))); expect(tester.getSize(find.widgetWithText(CupertinoDialogAction, 'Cancel')), equals(const Size(310.0, 148.0))); expect(tester.getSize(find.widgetWithText(CupertinoDialogAction, 'OK')), equals(const Size(310.0, 98.0))); });
testWidgets('Dialog respects small constraints.', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( dialogBuilder: (BuildContext context) { return Center( child: ConstrainedBox( // Constrain the dialog to a tiny size and ensure it respects // these exact constraints. constraints: BoxConstraints.tight(const Size(200.0, 100.0)), child: CupertinoAlertDialog( title: const Text('The Title'), content: const Text('The message'), actions: const <Widget>[ CupertinoDialogAction( child: Text('Option 1'), ), CupertinoDialogAction( child: Text('Option 2'), ), CupertinoDialogAction( child: Text('Option 3'), ), ], scrollController: scrollController, ), ), ); }, ), );
await tester.tap(find.text('Go')); await tester.pump();
const double topAndBottomMargin = 40.0; const double topAndBottomPadding = 24.0 * 2; const double leftAndRightPadding = 40.0 * 2; final Finder modalFinder = find.byType(ClipRRect); expect( tester.getSize(modalFinder), equals(const Size(200.0 - leftAndRightPadding, 100.0 - topAndBottomMargin - topAndBottomPadding)), ); });
testWidgets('Button list is scrollable, has correct position with large text sizes.', (WidgetTester tester) async { final ScrollController actionScrollController = ScrollController(); addTearDown(actionScrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( dialogBuilder: (BuildContext context) { return MediaQuery( data: MediaQuery.of(context).copyWith(textScaleFactor: 3.0), child: CupertinoAlertDialog( title: const Text('The title'), content: const Text('The content.'), actions: const <Widget>[ CupertinoDialogAction( child: Text('One'), ), CupertinoDialogAction( child: Text('Two'), ), CupertinoDialogAction( child: Text('Three'), ), CupertinoDialogAction( child: Text('Chocolate Brownies'), ), CupertinoDialogAction( isDestructiveAction: true, child: Text('Cancel'), ), ], actionScrollController: actionScrollController, ), ); }, ), );
await tester.tap(find.text('Go'));
await tester.pump();
// Check that the action buttons list is scrollable. expect(actionScrollController.offset, 0.0); actionScrollController.jumpTo(100.0); expect(actionScrollController.offset, 100.0); actionScrollController.jumpTo(0.0);
// Check that the action buttons are aligned vertically. expect(tester.getCenter(find.widgetWithText(CupertinoDialogAction, 'One')).dx, equals(400.0)); expect(tester.getCenter(find.widgetWithText(CupertinoDialogAction, 'Two')).dx, equals(400.0)); expect(tester.getCenter(find.widgetWithText(CupertinoDialogAction, 'Three')).dx, equals(400.0)); expect(tester.getCenter(find.widgetWithText(CupertinoDialogAction, 'Chocolate Brownies')).dx, equals(400.0)); expect(tester.getCenter(find.widgetWithText(CupertinoDialogAction, 'Cancel')).dx, equals(400.0));
// Check that the action buttons are the correct heights. expect(tester.getSize(find.widgetWithText(CupertinoDialogAction, 'One')).height, equals(98.0)); expect(tester.getSize(find.widgetWithText(CupertinoDialogAction, 'Two')).height, equals(98.0)); expect(tester.getSize(find.widgetWithText(CupertinoDialogAction, 'Three')).height, equals(98.0)); expect(tester.getSize(find.widgetWithText(CupertinoDialogAction, 'Chocolate Brownies')).height, equals(248.0)); expect(tester.getSize(find.widgetWithText(CupertinoDialogAction, 'Cancel')).height, equals(148.0)); });
testWidgets('Title Section is empty, Button section is not empty.', (WidgetTester tester) async { const double textScaleFactor = 1.0; final ScrollController actionScrollController = ScrollController(); addTearDown(actionScrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( dialogBuilder: (BuildContext context) { return MediaQuery( data: MediaQuery.of(context).copyWith(textScaleFactor: textScaleFactor), child: CupertinoAlertDialog( actions: const <Widget>[ CupertinoDialogAction( child: Text('One'), ), CupertinoDialogAction( child: Text('Two'), ), ], actionScrollController: actionScrollController, ), ); }, ), );
await tester.tap(find.text('Go'));
await tester.pump();
// Check that the dialog size is the same as the actions section size. This // ensures that an empty content section doesn't accidentally render some // empty space in the dialog. final Finder contentSectionFinder = find.byElementPredicate((Element element) { return element.widget.runtimeType.toString() == '_CupertinoAlertActionSection'; });
final Finder modalBoundaryFinder = find.byType(ClipRRect);
expect( tester.getSize(contentSectionFinder), tester.getSize(modalBoundaryFinder), );
// Check that the title/message section is not displayed expect(actionScrollController.offset, 0.0); expect(tester.getTopLeft(find.widgetWithText(CupertinoDialogAction, 'One')).dy, equals(277.5));
// Check that the button's vertical size is the same. expect( tester.getSize(find.widgetWithText(CupertinoDialogAction, 'One')).height, equals(tester.getSize(find.widgetWithText(CupertinoDialogAction, 'Two')).height), ); });
testWidgets('Button section is empty, Title section is not empty.', (WidgetTester tester) async { const double textScaleFactor = 1.0; final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( dialogBuilder: (BuildContext context) { return MediaQuery( data: MediaQuery.of(context).copyWith(textScaleFactor: textScaleFactor), child: CupertinoAlertDialog( title: const Text('The title'), content: const Text('The content.'), scrollController: scrollController, ), ); }, ), );
await tester.tap(find.text('Go'));
await tester.pump();
// Check that there's no button action section. expect(scrollController.offset, 0.0); expect(find.widgetWithText(CupertinoDialogAction, 'One'), findsNothing);
// Check that the dialog size is the same as the content section size. This // ensures that an empty button section doesn't accidentally render some // empty space in the dialog. final Finder contentSectionFinder = find.byElementPredicate((Element element) { return element.widget.runtimeType.toString() == '_CupertinoAlertContentSection'; });
final Finder modalBoundaryFinder = find.byType(ClipRRect);
expect( tester.getSize(contentSectionFinder), tester.getSize(modalBoundaryFinder), ); });
testWidgets('Actions section height for 1 button is height of button.', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( dialogBuilder: (BuildContext context) { return CupertinoAlertDialog( title: const Text('The Title'), content: const Text('The message'), actions: const <Widget>[ CupertinoDialogAction( child: Text('OK'), ), ], scrollController: scrollController, ); }, ), );
await tester.tap(find.text('Go')); await tester.pump();
final RenderBox okButtonBox = findActionButtonRenderBoxByTitle(tester, 'OK'); final RenderBox actionsSectionBox = findScrollableActionsSectionRenderBox(tester);
expect(okButtonBox.size.width, actionsSectionBox.size.width); expect(okButtonBox.size.height, actionsSectionBox.size.height); });
testWidgets('Actions section height for 2 side-by-side buttons is height of tallest button.', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); late double dividerWidth; // Will be set when the dialog builder runs. Needs a BuildContext. await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( dialogBuilder: (BuildContext context) { dividerWidth = 0.3; return CupertinoAlertDialog( title: const Text('The Title'), content: const Text('The message'), actions: const <Widget>[ CupertinoDialogAction( child: Text('OK'), ), CupertinoDialogAction( isDestructiveAction: true, child: Text('Cancel'), ), ], scrollController: scrollController, ); }, ), );
await tester.tap(find.text('Go')); await tester.pump();
final RenderBox okButtonBox = findActionButtonRenderBoxByTitle(tester, 'OK'); final RenderBox cancelButtonBox = findActionButtonRenderBoxByTitle(tester, 'Cancel'); final RenderBox actionsSectionBox = findScrollableActionsSectionRenderBox(tester);
expect(okButtonBox.size.width, cancelButtonBox.size.width);
expect( actionsSectionBox.size.width, okButtonBox.size.width + cancelButtonBox.size.width + dividerWidth, );
expect( actionsSectionBox.size.height, max(okButtonBox.size.height, cancelButtonBox.size.height), ); });
testWidgets('Actions section height for 2 stacked buttons with enough room is height of both buttons.', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); const double dividerThickness = 0.3; await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( dialogBuilder: (BuildContext context) { return CupertinoAlertDialog( title: const Text('The Title'), content: const Text('The message'), actions: const <Widget>[ CupertinoDialogAction( child: Text('OK'), ), CupertinoDialogAction( isDestructiveAction: true, child: Text('This is too long to fit'), ), ], scrollController: scrollController, ); }, ), );
await tester.tap(find.text('Go')); await tester.pump();
final RenderBox okButtonBox = findActionButtonRenderBoxByTitle(tester, 'OK'); final RenderBox longButtonBox = findActionButtonRenderBoxByTitle(tester, 'This is too long to fit'); final RenderBox actionsSectionBox = findScrollableActionsSectionRenderBox(tester);
expect(okButtonBox.size.width, longButtonBox.size.width);
expect(okButtonBox.size.width, actionsSectionBox.size.width);
expect( okButtonBox.size.height + dividerThickness + longButtonBox.size.height, actionsSectionBox.size.height, ); });
testWidgets('Actions section height for 2 stacked buttons without enough room and regular font is 1.5 buttons tall.', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( dialogBuilder: (BuildContext context) { return CupertinoAlertDialog( title: const Text('The Title'), content: Text('The message\n' * 40), actions: const <Widget>[ CupertinoDialogAction( child: Text('OK'), ), CupertinoDialogAction( isDestructiveAction: true, child: Text('This is too long to fit'), ), ], scrollController: scrollController, ); }, ), );
await tester.tap(find.text('Go')); await tester.pumpAndSettle();
final RenderBox actionsSectionBox = findScrollableActionsSectionRenderBox(tester);
expect( actionsSectionBox.size.height, 67.80000000000001, ); });
testWidgets('Actions section height for 2 stacked buttons without enough room and large accessibility font is 50% of dialog height.', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( dialogBuilder: (BuildContext context) { return MediaQuery( data: MediaQuery.of(context).copyWith(textScaleFactor: 3.0), child: CupertinoAlertDialog( title: const Text('The Title'), content: Text('The message\n' * 20), actions: const <Widget>[ CupertinoDialogAction( child: Text('This button is multi line'), ), CupertinoDialogAction( isDestructiveAction: true, child: Text('This button is multi line'), ), ], scrollController: scrollController, ), ); }, ), );
await tester.tap(find.text('Go')); await tester.pumpAndSettle();
final RenderBox actionsSectionBox = findScrollableActionsSectionRenderBox(tester);
// The two multiline buttons with large text are taller than 50% of the // dialog height, but with the accessibility layout policy, the 2 buttons // should be in a scrollable area equal to half the dialog height. expect( actionsSectionBox.size.height, 280.0 - 24.0, ); });
testWidgets('Actions section height for 3 buttons without enough room is 1.5 buttons tall.', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( dialogBuilder: (BuildContext context) { return CupertinoAlertDialog( title: const Text('The Title'), content: Text('The message\n' * 40), actions: const <Widget>[ CupertinoDialogAction( child: Text('Option 1'), ), CupertinoDialogAction( child: Text('Option 2'), ), CupertinoDialogAction( child: Text('Option 3'), ), ], scrollController: scrollController, ); }, ), );
await tester.tap(find.text('Go')); await tester.pump(); await tester.pumpAndSettle();
final RenderBox option1ButtonBox = findActionButtonRenderBoxByTitle(tester, 'Option 1'); final RenderBox option2ButtonBox = findActionButtonRenderBoxByTitle(tester, 'Option 2'); final RenderBox actionsSectionBox = findScrollableActionsSectionRenderBox(tester);
expect(option1ButtonBox.size.width, option2ButtonBox.size.width); expect(option1ButtonBox.size.width, actionsSectionBox.size.width);
// Expected Height = button 1 + divider + 1/2 button 2 = 67.80000000000001 const double expectedHeight = 67.80000000000001; expect( actionsSectionBox.size.height, moreOrLessEquals(expectedHeight), ); });
testWidgets('Actions section overscroll is painted white.', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( dialogBuilder: (BuildContext context) { return CupertinoAlertDialog( title: const Text('The Title'), content: const Text('The message'), actions: const <Widget>[ CupertinoDialogAction( child: Text('Option 1'), ), CupertinoDialogAction( child: Text('Option 2'), ), CupertinoDialogAction( child: Text('Option 3'), ), ], scrollController: scrollController, ); }, ), );
await tester.tap(find.text('Go')); await tester.pump();
final RenderBox actionsSectionBox = findScrollableActionsSectionRenderBox(tester);
// The way that overscroll white is accomplished in a scrollable action // section is that the custom RenderBox that lays out the buttons and draws // the dividers also paints a white background the size of Rect.largest. // That background ends up being clipped by the containing ScrollView. // // Here we test that the Rect(0.0, 0.0, renderBox.size.width, renderBox.size.height) // is contained within the painted Path. // We don't test for exclusion because for some reason the Path is reporting // that even points beyond Rect.largest are within the Path. That's not an // issue for our use-case, so we don't worry about it. expect(actionsSectionBox, paints..path( includes: <Offset>[ Offset.zero, Offset(actionsSectionBox.size.width, actionsSectionBox.size.height), ], )); });
testWidgets('Pressed button changes appearance and dividers disappear.', (WidgetTester tester) async { final ScrollController scrollController = ScrollController(); addTearDown(scrollController.dispose); const double dividerThickness = 0.3; await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( dialogBuilder: (BuildContext context) { return CupertinoAlertDialog( title: const Text('The Title'), content: const Text('The message'), actions: const <Widget>[ CupertinoDialogAction( child: Text('Option 1'), ), CupertinoDialogAction( child: Text('Option 2'), ), CupertinoDialogAction( child: Text('Option 3'), ), ], scrollController: scrollController, ); }, ), );
await tester.tap(find.text('Go')); await tester.pump();
const Color normalButtonBackgroundColor = Color(0xCCF2F2F2); const Color pressedButtonBackgroundColor = Color(0xFFE1E1E1); final RenderBox firstButtonBox = findActionButtonRenderBoxByTitle(tester, 'Option 1'); final RenderBox secondButtonBox = findActionButtonRenderBoxByTitle(tester, 'Option 2'); final RenderBox actionsSectionBox = findScrollableActionsSectionRenderBox(tester);
final Offset pressedButtonCenter = Offset( secondButtonBox.size.width / 2.0, firstButtonBox.size.height + dividerThickness + (secondButtonBox.size.height / 2.0), ); final Offset topDividerCenter = Offset( secondButtonBox.size.width / 2.0, firstButtonBox.size.height + (0.5 * dividerThickness), ); final Offset bottomDividerCenter = Offset( secondButtonBox.size.width / 2.0, firstButtonBox.size.height + dividerThickness + secondButtonBox.size.height + (0.5 * dividerThickness), );
// Before pressing the button, verify following expectations: // - Background includes the button that will be pressed // - Background excludes the divider above and below the button that will be pressed // - Pressed button background does NOT include the button that will be pressed expect(actionsSectionBox, paints ..path( color: normalButtonBackgroundColor, includes: <Offset>[ pressedButtonCenter, ], excludes: <Offset>[ topDividerCenter, bottomDividerCenter, ], ) ..path( color: pressedButtonBackgroundColor, excludes: <Offset>[ pressedButtonCenter, ], ), );
// Press down on the button. final TestGesture gesture = await tester.press(find.widgetWithText(CupertinoDialogAction, 'Option 2')); await tester.pump();
// While pressing the button, verify following expectations: // - Background excludes the pressed button // - Background includes the divider above and below the pressed button // - Pressed button background includes the pressed expect(actionsSectionBox, paints ..path( color: normalButtonBackgroundColor, // The background should contain the divider above and below the pressed // button. While pressed, surrounding dividers disappear, which means // they become part of the background. includes: <Offset>[ topDividerCenter, bottomDividerCenter, ], // The background path should not include the tapped button background... excludes: <Offset>[ pressedButtonCenter, ], ) // For a pressed button, a dedicated path is painted with a pressed button // background color... ..path( color: pressedButtonBackgroundColor, includes: <Offset>[ pressedButtonCenter, ], ), );
// We must explicitly cause an "up" gesture to avoid a crash. // TODO(mattcarroll): remove this call, https://github.com/flutter/flutter/issues/19540 await gesture.up(); });
testWidgets('ScaleTransition animation for showCupertinoDialog()', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: Builder( builder: (BuildContext context) { return CupertinoButton( onPressed: () { showCupertinoDialog<void>( context: context, builder: (BuildContext context) { return CupertinoAlertDialog( title: const Text('The title'), content: const Text('The content'), actions: <Widget>[ const CupertinoDialogAction( child: Text('Cancel'), ), CupertinoDialogAction( isDestructiveAction: true, onPressed: () { Navigator.pop(context); }, child: const Text('Delete'), ), ], ); }, ); }, child: const Text('Go'), ); }, ), ), ), );
await tester.tap(find.text('Go'));
// Enter animation. await tester.pump(); Transform transform = tester.widget(find.byType(Transform)); expect(transform.transform[0], moreOrLessEquals(1.3, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transform = tester.widget(find.byType(Transform)); expect(transform.transform[0], moreOrLessEquals(1.145, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transform = tester.widget(find.byType(Transform)); expect(transform.transform[0], moreOrLessEquals(1.044, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transform = tester.widget(find.byType(Transform)); expect(transform.transform[0], moreOrLessEquals(1.013, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transform = tester.widget(find.byType(Transform)); expect(transform.transform[0], moreOrLessEquals(1.003, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transform = tester.widget(find.byType(Transform)); expect(transform.transform[0], moreOrLessEquals(1.000, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transform = tester.widget(find.byType(Transform)); expect(transform.transform[0], moreOrLessEquals(1.000, epsilon: 0.001));
await tester.tap(find.text('Delete'));
await tester.pump(); await tester.pump(const Duration(milliseconds: 50));
// No scaling on exit animation. expect(find.byType(Transform), findsNothing); });
testWidgets('FadeTransition animation for showCupertinoDialog()', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: Builder( builder: (BuildContext context) { return CupertinoButton( onPressed: () { showCupertinoDialog<void>( context: context, builder: (BuildContext context) { return CupertinoAlertDialog( title: const Text('The title'), content: const Text('The content'), actions: <Widget>[ const CupertinoDialogAction( child: Text('Cancel'), ), CupertinoDialogAction( isDestructiveAction: true, onPressed: () { Navigator.pop(context); }, child: const Text('Delete'), ), ], ); }, ); }, child: const Text('Go'), ); }, ), ), ), );
await tester.tap(find.text('Go'));
// Enter animation. await tester.pump(); final Finder fadeTransitionFinder = find.ancestor(of: find.byType(CupertinoAlertDialog), matching: find.byType(FadeTransition)); FadeTransition transition = tester.firstWidget(fadeTransitionFinder);
await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); expect(transition.opacity.value, moreOrLessEquals(0.081, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); expect(transition.opacity.value, moreOrLessEquals(0.332, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); expect(transition.opacity.value, moreOrLessEquals(0.667, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); expect(transition.opacity.value, moreOrLessEquals(0.918, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); expect(transition.opacity.value, moreOrLessEquals(1.0, epsilon: 0.001));
await tester.tap(find.text('Delete'));
// Exit animation, look at reverse FadeTransition. await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); expect(transition.opacity.value, moreOrLessEquals(1.0, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); expect(transition.opacity.value, moreOrLessEquals(0.918, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); expect(transition.opacity.value, moreOrLessEquals(0.667, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); expect(transition.opacity.value, moreOrLessEquals(0.332, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); expect(transition.opacity.value, moreOrLessEquals(0.081, epsilon: 0.001));
await tester.pump(const Duration(milliseconds: 50)); transition = tester.firstWidget(fadeTransitionFinder); expect(transition.opacity.value, moreOrLessEquals(0.0, epsilon: 0.001)); });
testWidgets('Actions are accessible by key', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( dialogBuilder: (BuildContext context) { return const CupertinoAlertDialog( title: Text('The Title'), content: Text('The message'), actions: <Widget>[ CupertinoDialogAction( key: Key('option_1'), child: Text('Option 1'), ), CupertinoDialogAction( key: Key('option_2'), child: Text('Option 2'), ), ], ); }, ), );
await tester.tap(find.text('Go')); await tester.pump();
expect(find.byKey(const Key('option_1')), findsOneWidget); expect(find.byKey(const Key('option_2')), findsOneWidget); expect(find.byKey(const Key('option_3')), findsNothing); });
testWidgets('Dialog widget insets by MediaQuery viewInsets', (WidgetTester tester) async { await tester.pumpWidget( const MaterialApp( home: MediaQuery( data: MediaQueryData(), child: CupertinoAlertDialog(content: Placeholder(fallbackHeight: 200.0)), ), ), );
final Rect placeholderRectWithoutInsets = tester.getRect(find.byType(Placeholder));
await tester.pumpWidget( const MaterialApp( home: MediaQuery( data: MediaQueryData(viewInsets: EdgeInsets.fromLTRB(40.0, 30.0, 20.0, 10.0)), child: CupertinoAlertDialog(content: Placeholder(fallbackHeight: 200.0)), ), ), );
// no change yet because padding is animated expect(tester.getRect(find.byType(Placeholder)), placeholderRectWithoutInsets);
await tester.pump(const Duration(seconds: 1));
// once animation settles the dialog is padded by the new viewInsets expect(tester.getRect(find.byType(Placeholder)), placeholderRectWithoutInsets.translate(10, 10)); });
testWidgets('Material2 - Default cupertino dialog golden', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( useMaterial3: false, dialogBuilder: (BuildContext context) { return MediaQuery( data: MediaQuery.of(context).copyWith(textScaleFactor: 3.0), child: const RepaintBoundary( child: CupertinoAlertDialog( title: Text('Title'), content: Text('text'), actions: <Widget>[ CupertinoDialogAction(child: Text('No')), CupertinoDialogAction(child: Text('OK')), ], ), ), ); }, ), );
await tester.tap(find.text('Go')); await tester.pumpAndSettle();
await expectLater( find.byType(CupertinoAlertDialog), matchesGoldenFile('m2_dialog_test.cupertino.default.png'), ); });
testWidgets('Material3 - Default cupertino dialog golden', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( useMaterial3: true, dialogBuilder: (BuildContext context) { return MediaQuery( data: MediaQuery.of(context).copyWith(textScaleFactor: 3.0), child: const RepaintBoundary( child: CupertinoAlertDialog( title: Text('Title'), content: Text('text'), actions: <Widget>[ CupertinoDialogAction(child: Text('No')), CupertinoDialogAction(child: Text('OK')), ], ), ), ); }, ), );
await tester.tap(find.text('Go')); await tester.pumpAndSettle();
await expectLater( find.byType(CupertinoAlertDialog), matchesGoldenFile('m3_dialog_test.cupertino.default.png'), ); });
testWidgets('showCupertinoDialog - custom barrierLabel', (WidgetTester tester) async { final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget( CupertinoApp( home: Builder( builder: (BuildContext context) { return Center( child: CupertinoButton( child: const Text('X'), onPressed: () { showCupertinoDialog<void>( context: context, barrierLabel: 'Custom label', builder: (BuildContext context) { return const CupertinoAlertDialog( title: Text('Title'), content: Text('Content'), actions: <Widget>[ CupertinoDialogAction(child: Text('Yes')), CupertinoDialogAction(child: Text('No')), ], ); }, ); }, ), ); }, ), ), );
expect(semantics, isNot(includesNodeWith( label: 'Custom label', flags: <SemanticsFlag>[SemanticsFlag.namesRoute], ))); semantics.dispose(); });
testWidgets('CupertinoDialogRoute is state restorable', (WidgetTester tester) async { await tester.pumpWidget( const CupertinoApp( restorationScopeId: 'app', home: _RestorableDialogTestWidget(), ), );
expect(find.byType(CupertinoAlertDialog), findsNothing);
await tester.tap(find.text('X')); await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsOneWidget); final TestRestorationData restorationData = await tester.getRestorationData();
await tester.restartAndRestore();
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
// Tap on the barrier. await tester.tapAt(const Offset(10.0, 10.0)); await tester.pumpAndSettle();
expect(find.byType(CupertinoAlertDialog), findsNothing);
await tester.restoreFrom(restorationData); expect(find.byType(CupertinoAlertDialog), findsOneWidget); }, skip: isBrowser); // https://github.com/flutter/flutter/issues/33615
testWidgets('Conflicting scrollbars are not applied by ScrollBehavior to CupertinoAlertDialog', (WidgetTester tester) async { // Regression test for https://github.com/flutter/flutter/issues/83819 const double textScaleFactor = 1.0; final ScrollController actionScrollController = ScrollController(); addTearDown(actionScrollController.dispose); await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( dialogBuilder: (BuildContext context) { return MediaQuery( data: MediaQuery.of(context).copyWith(textScaleFactor: textScaleFactor), child: CupertinoAlertDialog( title: const Text('Test Title'), content: const Text('Test Content'), actions: const <Widget>[ CupertinoDialogAction( child: Text('One'), ), CupertinoDialogAction( child: Text('Two'), ), ], actionScrollController: actionScrollController, ), ); }, ), );
await tester.tap(find.text('Go')); await tester.pump();
// The inherited ScrollBehavior should not apply Scrollbars since they are // already built in to the widget. expect(find.byType(Scrollbar), findsNothing); expect(find.byType(RawScrollbar), findsNothing); // Built in CupertinoScrollbars should only number 2: one for the actions, // one for the content. expect(find.byType(CupertinoScrollbar), findsNWidgets(2)); }, variant: TargetPlatformVariant.all());
testWidgets('CupertinoAlertDialog scrollbars controllers should be different', (WidgetTester tester) async { // https://github.com/flutter/flutter/pull/81278 await tester.pumpWidget( const MaterialApp( home: MediaQuery( data: MediaQueryData(), child: CupertinoAlertDialog( actions: <Widget>[ CupertinoDialogAction(child: Text('OK')), ], content: Placeholder(fallbackHeight: 200.0), ), ), ), );
final List<CupertinoScrollbar> scrollbars = find.descendant( of: find.byType(CupertinoAlertDialog), matching: find.byType(CupertinoScrollbar), ).evaluate().map((Element e) => e.widget as CupertinoScrollbar).toList();
expect(scrollbars.length, 2); expect(scrollbars[0].controller != scrollbars[1].controller, isTrue); });
group('showCupertinoDialog avoids overlapping display features', () { testWidgets('positioning using anchorPoint', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( builder: (BuildContext context, Widget? child) { return MediaQuery( // Display has a vertical hinge down the middle data: const MediaQueryData( size: Size(800, 600), displayFeatures: <DisplayFeature>[ DisplayFeature( bounds: Rect.fromLTRB(390, 0, 410, 600), type: DisplayFeatureType.hinge, state: DisplayFeatureState.unknown, ), ], ), child: child!, ); }, home: const Center(child: Text('Test')), ), );
final BuildContext context = tester.element(find.text('Test')); showCupertinoDialog<void>( context: context, builder: (BuildContext context) { return const Placeholder(); }, anchorPoint: const Offset(1000, 0), ); await tester.pumpAndSettle();
// Should take the right side of the screen expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(410.0, 0.0)); expect(tester.getBottomRight(find.byType(Placeholder)), const Offset(800.0, 600.0)); });
testWidgets('positioning using Directionality', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( builder: (BuildContext context, Widget? child) { return MediaQuery( // Display has a vertical hinge down the middle data: const MediaQueryData( size: Size(800, 600), displayFeatures: <DisplayFeature>[ DisplayFeature( bounds: Rect.fromLTRB(390, 0, 410, 600), type: DisplayFeatureType.hinge, state: DisplayFeatureState.unknown, ), ], ), child: Directionality( textDirection: TextDirection.rtl, child: child!, ), ); }, home: const Center(child: Text('Test')), ), );
final BuildContext context = tester.element(find.text('Test')); showCupertinoDialog<void>( context: context, builder: (BuildContext context) { return const Placeholder(); }, ); await tester.pumpAndSettle();
// Should take the right side of the screen expect(tester.getTopLeft(find.byType(Placeholder)), const Offset(410.0, 0.0)); expect(tester.getBottomRight(find.byType(Placeholder)), const Offset(800.0, 600.0)); });
testWidgets('default positioning', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( builder: (BuildContext context, Widget? child) { return MediaQuery( // Display has a vertical hinge down the middle data: const MediaQueryData( size: Size(800, 600), displayFeatures: <DisplayFeature>[ DisplayFeature( bounds: Rect.fromLTRB(390, 0, 410, 600), type: DisplayFeatureType.hinge, state: DisplayFeatureState.unknown, ), ], ), child: child!, ); }, home: const Center(child: Text('Test')), ), );
final BuildContext context = tester.element(find.text('Test')); showCupertinoDialog<void>( context: context, builder: (BuildContext context) { return const Placeholder(); }, ); await tester.pumpAndSettle();
// By default it should place the dialog on the left screen expect(tester.getTopLeft(find.byType(Placeholder)), Offset.zero); expect(tester.getBottomRight(find.byType(Placeholder)), const Offset(390.0, 600.0)); }); });
testWidgets('Hovering over Cupertino alert dialog action updates cursor to clickable on Web', (WidgetTester tester) async { await tester.pumpWidget( createAppWithButtonThatLaunchesDialog( dialogBuilder: (BuildContext context) { return MediaQuery( data: MediaQuery.of(context).copyWith(textScaleFactor: 3.0), child: RepaintBoundary( child: CupertinoAlertDialog( title: const Text('Title'), content: const Text('text'), actions: <Widget>[ CupertinoDialogAction( onPressed: () {}, child: const Text('NO'), ), CupertinoDialogAction( onPressed: () {}, child: const Text('OK'), ), ], ), ), ); }, ), );
await tester.tap(find.text('Go')); await tester.pumpAndSettle();
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1); await gesture.addPointer(location: const Offset(10, 10)); await tester.pumpAndSettle(); expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
final Offset dialogAction = tester.getCenter(find.text('OK')); await gesture.moveTo(dialogAction); await tester.pumpAndSettle(); expect( RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), kIsWeb ? SystemMouseCursors.click : SystemMouseCursors.basic, ); });}
RenderBox findActionButtonRenderBoxByTitle(WidgetTester tester, String title) { final RenderObject buttonBox = tester.renderObject(find.widgetWithText(CupertinoDialogAction, title)); assert(buttonBox is RenderBox); return buttonBox as RenderBox;}
RenderBox findScrollableActionsSectionRenderBox(WidgetTester tester) { final RenderObject actionsSection = tester.renderObject(find.byElementPredicate((Element element) { return element.widget.runtimeType.toString() == '_CupertinoAlertActionSection'; })); assert(actionsSection is RenderBox); return actionsSection as RenderBox;}
Widget createAppWithButtonThatLaunchesDialog({ required WidgetBuilder dialogBuilder, bool? useMaterial3,}) { return MaterialApp( theme: ThemeData(useMaterial3: useMaterial3), home: Material( child: Center( child: Builder(builder: (BuildContext context) { return ElevatedButton( onPressed: () { showDialog<void>( context: context, builder: dialogBuilder, ); }, child: const Text('Go'), ); }), ), ), );}
Widget boilerplate(Widget child) { return Directionality( textDirection: TextDirection.ltr, child: child, );}
Widget createAppWithCenteredButton(Widget child) { return MaterialApp( home: Material( child: Center( child: ElevatedButton( onPressed: null, child: child, ), ), ), );}
class _RestorableDialogTestWidget extends StatelessWidget { const _RestorableDialogTestWidget();
@pragma('vm:entry-point') static Route<Object?> _dialogBuilder(BuildContext context, Object? arguments) { return CupertinoDialogRoute<void>( context: context, builder: (BuildContext context) { return const CupertinoAlertDialog( title: Text('Title'), content: Text('Content'), actions: <Widget>[ CupertinoDialogAction(child: Text('Yes')), CupertinoDialogAction(child: Text('No')), ], ); }, ); }
@override Widget build(BuildContext context) { return CupertinoPageScaffold( navigationBar: const CupertinoNavigationBar( middle: Text('Home'), ), child: Center(child: CupertinoButton( onPressed: () { Navigator.of(context).restorablePush(_dialogBuilder); }, child: const Text('X'), )), ); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208// 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/rendering.dart';import 'package:flutter_test/flutter_test.dart';
void main() { testWidgets('Shows prefix', (WidgetTester tester) async { const Widget prefix = Text('Enter Value');
await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoFormRow( prefix: prefix, child: CupertinoTextField(), ), ), ), );
expect(prefix, tester.widget(find.byType(Text))); });
testWidgets('Shows child', (WidgetTester tester) async { const Widget child = CupertinoTextField();
await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoFormRow( child: child, ), ), ), );
expect(child, tester.widget(find.byType(CupertinoTextField))); });
testWidgets('RTL puts prefix after child', (WidgetTester tester) async { const Widget prefix = Text('Enter Value'); const Widget child = CupertinoTextField();
await tester.pumpWidget( const CupertinoApp( home: Center( child: Directionality( textDirection: TextDirection.rtl, child: CupertinoFormRow( prefix: prefix, child: child, ), ), ), ), );
expect(tester.getTopLeft(find.byType(Text)).dx > tester.getTopLeft(find.byType(CupertinoTextField)).dx, true); });
testWidgets('LTR puts child after prefix', (WidgetTester tester) async { const Widget prefix = Text('Enter Value'); const Widget child = CupertinoTextField();
await tester.pumpWidget( const CupertinoApp( home: Center( child: Directionality( textDirection: TextDirection.ltr, child: CupertinoFormRow( prefix: prefix, child: child, ), ), ), ), );
expect(tester.getTopLeft(find.byType(Text)).dx > tester.getTopLeft(find.byType(CupertinoTextField)).dx, false); });
testWidgets('Shows error widget', (WidgetTester tester) async { const Widget error = Text('Error');
await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoFormRow( error: error, child: CupertinoTextField(), ), ), ), );
expect(error, tester.widget(find.byType(Text))); });
testWidgets('Shows helper widget', (WidgetTester tester) async { const Widget helper = Text('Helper');
await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoFormRow( helper: helper, child: CupertinoTextField(), ), ), ), );
expect(helper, tester.widget(find.byType(Text))); });
testWidgets('Shows helper text above error text', (WidgetTester tester) async { const Widget helper = Text('Helper'); const Widget error = CupertinoActivityIndicator();
await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoFormRow( helper: helper, error: error, child: CupertinoTextField(), ), ), ), );
expect( tester.getTopLeft(find.byType(CupertinoActivityIndicator)).dy > tester.getTopLeft(find.byType(Text)).dy, true, ); });
testWidgets('Shows helper in label color and error text in red color', (WidgetTester tester) async { const Widget helper = Text('Helper'); const Widget error = Text('Error');
await tester.pumpWidget( const CupertinoApp( home: Center( child: CupertinoFormRow( helper: helper, error: error, child: CupertinoTextField(), ), ), ), );
final DefaultTextStyle helperTextStyle = tester.widget(find.byType(DefaultTextStyle).first);
expect(helperTextStyle.style.color, CupertinoColors.label);
final DefaultTextStyle errorTextStyle = tester.widget(find.byType(DefaultTextStyle).last);
expect(errorTextStyle.style.color, CupertinoColors.destructiveRed); });
testWidgets('CupertinoFormRow adapts to MaterialApp dark mode', (WidgetTester tester) async { const Widget prefix = Text('Prefix'); const Widget helper = Text('Helper');
Widget buildFormRow(Brightness brightness) { return MaterialApp( theme: ThemeData(brightness: brightness), home: const Center( child: CupertinoFormRow( prefix: prefix, helper: helper, child: CupertinoTextField(), ), ), ); }
// CupertinoFormRow with light theme. await tester.pumpWidget(buildFormRow(Brightness.light)); RenderParagraph helperParagraph = tester.renderObject(find.text('Helper')); expect(helperParagraph.text.style!.color, CupertinoColors.label); // Text style should not return unresolved color. expect(helperParagraph.text.style!.color.toString().contains('UNRESOLVED'), isFalse); RenderParagraph prefixParagraph = tester.renderObject(find.text('Prefix')); expect(prefixParagraph.text.style!.color, CupertinoColors.label); // Text style should not return unresolved color. expect(prefixParagraph.text.style!.color.toString().contains('UNRESOLVED'), isFalse);
// CupertinoFormRow with light theme. await tester.pumpWidget(buildFormRow(Brightness.dark)); helperParagraph = tester.renderObject(find.text('Helper')); expect(helperParagraph.text.style!.color, CupertinoColors.label); // Text style should not return unresolved color. expect(helperParagraph.text.style!.color.toString().contains('UNRESOLVED'), isFalse); prefixParagraph = tester.renderObject(find.text('Prefix')); expect(prefixParagraph.text.style!.color, CupertinoColors.label); // Text style should not return unresolved color. expect(prefixParagraph.text.style!.color.toString().contains('UNRESOLVED'), isFalse); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223// 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/rendering.dart';import 'package:flutter_test/flutter_test.dart';
void main() { testWidgets('Shows header', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection( header: const Text('Header'), children: <Widget>[CupertinoTextFormFieldRow()], ), ), ), );
expect(find.text('Header'), findsOneWidget); });
testWidgets('Shows footer', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection( footer: const Text('Footer'), children: <Widget>[CupertinoTextFormFieldRow()], ), ), ), );
expect(find.text('Footer'), findsOneWidget); });
testWidgets('Shows long dividers in edge-to-edge section part 1', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection( children: <Widget>[CupertinoTextFormFieldRow()], ), ), ), );
// Since the children list is reconstructed with dividers in it, the column // retrieved should have 3 items for an input [children] param with 1 child. final Column childrenColumn = tester.widget(find.byType(Column).at(1)); expect(childrenColumn.children.length, 3); });
testWidgets('Shows long dividers in edge-to-edge section part 2', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection( children: <Widget>[ CupertinoTextFormFieldRow(), CupertinoTextFormFieldRow(), ], ), ), ), );
// Since the children list is reconstructed with dividers in it, the column // retrieved should have 5 items for an input [children] param with 2 // children. Two long dividers, two rows, and one short divider. final Column childrenColumn = tester.widget(find.byType(Column).at(1)); expect(childrenColumn.children.length, 5); });
testWidgets('Does not show long dividers in insetGrouped section part 1', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection.insetGrouped( children: <Widget>[CupertinoTextFormFieldRow()], ), ), ), );
// Since the children list is reconstructed without long dividers in it, the // column retrieved should have 1 item for an input [children] param with 1 // child. final Column childrenColumn = tester.widget(find.byType(Column).at(1)); expect(childrenColumn.children.length, 1); });
testWidgets('Does not show long dividers in insetGrouped section part 2', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( restorationScopeId: 'App', home: Center( child: CupertinoFormSection.insetGrouped( children: <Widget>[ CupertinoTextFormFieldRow(), CupertinoTextFormFieldRow(), ], ), ), ), );
// Since the children list is reconstructed with short dividers in it, the // column retrieved should have 3 items for an input [children] param with 2 // children. Two long dividers, two rows, and one short divider. final Column childrenColumn = tester.widget(find.byType(Column).at(1)); expect(childrenColumn.children.length, 3); });
testWidgets('Sets background color for section', (WidgetTester tester) async { const Color backgroundColor = CupertinoColors.systemBlue;
await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: CupertinoFormSection( backgroundColor: backgroundColor, children: <Widget>[CupertinoTextFormFieldRow()], ), ), ), );
final DecoratedBox decoratedBox = tester.widget(find.byType(DecoratedBox).first); final BoxDecoration boxDecoration = decoratedBox.decoration as BoxDecoration; expect(boxDecoration.color, backgroundColor); });
testWidgets('Setting clipBehavior clips children section', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection( clipBehavior: Clip.antiAlias, children: <Widget>[CupertinoTextFormFieldRow()], ), ), ), );
expect(find.byType(ClipRRect), findsOneWidget); });
testWidgets('Not setting clipBehavior does not produce a RenderClipRRect object', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection( children: <Widget>[CupertinoTextFormFieldRow()], ), ), ), );
final Iterable<RenderClipRRect> renderClips = tester.allRenderObjects.whereType<RenderClipRRect>(); expect(renderClips, isEmpty); });
testWidgets('Does not double up padding on header', (WidgetTester tester) async { const Widget header = Text('Header');
await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection( header: header, children: <Widget>[CupertinoTextFormFieldRow()], ), ), ), );
expect(tester.getTopLeft(find.byWidget(header)), const Offset(20, 22)); });
testWidgets('Does not double up padding on footer', (WidgetTester tester) async { const Widget footer = Text('Footer');
await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection( footer: footer, children: <Widget>[CupertinoTextFormFieldRow()], ), ), ), );
expect(tester.getTopLeft(find.byWidget(footer)), offsetMoreOrLessEquals(const Offset(20, 65), epsilon: 1)); });
testWidgets('Sets custom margin', (WidgetTester tester) async { final Widget child = CupertinoTextFormFieldRow();
const double margin = 35;
await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoFormSection( margin: const EdgeInsets.all(margin), children: <Widget>[child], ), ), ), );
expect(tester.getTopLeft(find.byWidget(child)), offsetMoreOrLessEquals(const Offset(margin, 22 + margin), epsilon: 1)); });}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647// 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_test/flutter_test.dart';
void main() { testWidgets('IconTheme.of works', (WidgetTester tester) async { const IconThemeData data = IconThemeData( size: 16.0, fill: 0.0, weight: 400.0, grade: 0.0, opticalSize: 48.0, color: Color(0xAAAAAAAA), opacity: 0.5, applyTextScaling: true, );
late IconThemeData retrieved; await tester.pumpWidget( IconTheme(data: data, child: Builder(builder: (BuildContext context) { retrieved = IconTheme.of(context); return const SizedBox(); })), );
expect(retrieved, data);
await tester.pumpWidget( IconTheme( data: const CupertinoIconThemeData(color: CupertinoColors.systemBlue), child: MediaQuery( data: const MediaQueryData(platformBrightness: Brightness.dark), child: Builder(builder: (BuildContext context) { retrieved = IconTheme.of(context); return const SizedBox(); }, ), ), ), );
expect(retrieved.color, isSameColorAs(CupertinoColors.systemBlue.darkColor)); });}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265// 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_test/flutter_test.dart';
void main() { testWidgets('shows header', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoListSection( header: const Text('Header'), children: const <Widget>[ CupertinoListTile(title: Text('CupertinoListTile')), ], ), ), ), );
expect(find.text('Header'), findsOneWidget); });
testWidgets('shows footer', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoListSection( footer: const Text('Footer'), children: const <Widget>[ CupertinoListTile(title: Text('CupertinoListTile')), ], ), ), ), );
expect(find.text('Footer'), findsOneWidget); });
testWidgets('shows long dividers in edge-to-edge section part 1', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoListSection( children: const <Widget>[ CupertinoListTile(title: Text('CupertinoListTile')), ], ), ), ), );
// Since the children list is reconstructed with dividers in it, the column // retrieved should have 3 items for an input [children] param with 1 child. final Column childrenColumn = tester.widget(find.byType(Column).at(1)); expect(childrenColumn.children.length, 3); });
testWidgets('shows long dividers in edge-to-edge section part 2', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoListSection( children: const <Widget>[ CupertinoListTile(title: Text('CupertinoListTile')), CupertinoListTile(title: Text('CupertinoListTile')), ], ), ), ), );
// Since the children list is reconstructed with dividers in it, the column // retrieved should have 5 items for an input [children] param with 2 // children. Two long dividers, two rows, and one short divider. final Column childrenColumn = tester.widget(find.byType(Column).at(1)); expect(childrenColumn.children.length, 5); });
testWidgets('does not show long dividers in insetGrouped section part 1', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoListSection.insetGrouped( children: const <Widget>[ CupertinoListTile(title: Text('CupertinoListTile')), ], ), ), ), );
// Since the children list is reconstructed without long dividers in it, the // column retrieved should have 1 item for an input [children] param with 1 // child. final Column childrenColumn = tester.widget(find.byType(Column).at(1)); expect(childrenColumn.children.length, 1); });
testWidgets('does not show long dividers in insetGrouped section part 2', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoListSection.insetGrouped( children: const <Widget>[ CupertinoListTile(title: Text('CupertinoListTile')), CupertinoListTile(title: Text('CupertinoListTile')), ], ), ), ), );
// Since the children list is reconstructed with short dividers in it, the // column retrieved should have 3 items for an input [children] param with 2 // children. Two long dividers, two rows, and one short divider. final Column childrenColumn = tester.widget(find.byType(Column).at(1)); expect(childrenColumn.children.length, 3); });
testWidgets('sets background color for section', (WidgetTester tester) async { const Color backgroundColor = CupertinoColors.systemBlue;
await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: MediaQuery( data: const MediaQueryData(), child: CupertinoListSection( backgroundColor: backgroundColor, children: const <Widget>[ CupertinoListTile(title: Text('CupertinoListTile')), ], ), ), ), );
final DecoratedBox decoratedBox = tester.widget(find.byType(DecoratedBox).first); final BoxDecoration boxDecoration = decoratedBox.decoration as BoxDecoration; expect(boxDecoration.color, backgroundColor); });
testWidgets('setting clipBehavior clips children section', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoListSection( clipBehavior: Clip.antiAlias, children: const <Widget>[ CupertinoListTile(title: Text('CupertinoListTile')), ], ), ), ), );
expect(find.byType(ClipRRect), findsOneWidget); });
testWidgets('not setting clipBehavior does not clip children section', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoListSection( children: const <Widget>[ CupertinoListTile(title: Text('CupertinoListTile')), ], ), ), ), );
expect(find.byType(ClipRRect), findsNothing); });
testWidgets('CupertinoListSection respects separatorColor', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoListSection( separatorColor: const Color.fromARGB(255, 143, 193, 51), children: const <Widget>[ CupertinoListTile(title: Text('CupertinoListTile')), CupertinoListTile(title: Text('CupertinoListTile')), ], ), ), ), );
final Column childrenColumn = tester.widget(find.byType(Column).at(1)); for (final Widget e in childrenColumn.children) { if (e is Container) { expect(e.color, const Color.fromARGB(255, 143, 193, 51)); } } });
testWidgets('CupertinoListSection.separatorColor defaults CupertinoColors.separator', (WidgetTester tester) async { await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoListSection( children: const <Widget>[ CupertinoListTile(title: Text('CupertinoListTile')), CupertinoListTile(title: Text('CupertinoListTile')), ], ), ), ), );
final BuildContext context = tester.element(find.byType(CupertinoListSection)); final Column childrenColumn = tester.widget(find.byType(Column).at(1)); for (final Widget e in childrenColumn.children) { if (e is Container) { expect(e.color, CupertinoColors.separator.resolveFrom(context)); } } });
testWidgets('does not show margin by default', (WidgetTester tester) async { const Widget child = CupertinoListTile(title: Text('CupertinoListTile'));
await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoListSection( header: const Text('Header'), children: const <Widget>[ child, ], ), ), ), );
expect(tester.getTopLeft(find.byWidget(child)), offsetMoreOrLessEquals(const Offset(0, 41), epsilon: 1)); });
testWidgets('shows custom margin', (WidgetTester tester) async { const Widget child = CupertinoListTile(title: Text('CupertinoListTile')); const double margin = 10;
await tester.pumpWidget( CupertinoApp( home: Center( child: CupertinoListSection( header: const Text('Header'), margin: const EdgeInsets.all(margin), children: const <Widget>[ child, ], ), ), ), );
expect(tester.getTopLeft(find.byWidget(child)), offsetMoreOrLessEquals(const Offset(margin, 41 + margin), epsilon: 1)); });}novelforge-project/flutter.tar.xzAdded+3
novelforge-project/flutter/packages/flutter/coverage/lcov.base.infoAdded
novelforge-project/flutter/packages/flutter/coverage/lcov.infoAdded
novelforge-project/flutter/packages/flutter/lib/analysis_options.yamlAdded+6
novelforge-project/flutter/packages/flutter/lib/animation.dartAdded+173
novelforge-project/flutter/packages/flutter/lib/cupertino.dartAdded+73
novelforge-project/flutter/packages/flutter/lib/foundation.dartAdded+49
novelforge-project/flutter/packages/flutter/lib/gestures.dartAdded+35
novelforge-project/flutter/packages/flutter/lib/material.dartAdded+196
novelforge-project/flutter/packages/flutter/lib/painting.dartAdded+65
novelforge-project/flutter/packages/flutter/lib/physics.dartAdded+17
novelforge-project/flutter/packages/flutter/lib/rendering.dartAdded+78
novelforge-project/flutter/packages/flutter/lib/scheduler.dartAdded+20
novelforge-project/flutter/packages/flutter/lib/semantics.dartAdded+22
novelforge-project/flutter/packages/flutter/lib/services.dartAdded+58
novelforge-project/flutter/packages/flutter/lib/widgets.dartAdded+167
novelforge-project/flutter/packages/flutter/test/_goldens_io.dartAdded+5
novelforge-project/flutter/packages/flutter/test/_goldens_web.dartAdded+8
novelforge-project/flutter/packages/flutter/test/analysis_options.yamlAdded+9
novelforge-project/flutter/packages/flutter/test/animation/animation_controller_listener_test.dartAdded+52
novelforge-project/flutter/packages/flutter/test/animation/animation_controller_test.dartAdded+1106
novelforge-project/flutter/packages/flutter/test/animation/animation_from_listener_test.dartAdded+83
novelforge-project/flutter/packages/flutter/test/animation/animation_sheet_test.dartAdded+185
novelforge-project/flutter/packages/flutter/test/animation/animation_style_test.dartAdded+92
novelforge-project/flutter/packages/flutter/test/animation/animations_test.dartAdded+501
novelforge-project/flutter/packages/flutter/test/animation/curves_test.dartAdded+616
novelforge-project/flutter/packages/flutter/test/animation/futures_test.dartAdded+189
novelforge-project/flutter/packages/flutter/test/animation/iteration_patterns_test.dartAdded+129
novelforge-project/flutter/packages/flutter/test/animation/listener_helpers_test.dartAdded+54
novelforge-project/flutter/packages/flutter/test/animation/live_binding_test.dartAdded+140
novelforge-project/flutter/packages/flutter/test/animation/tween_test.dartAdded+222
novelforge-project/flutter/packages/flutter/test/cupertino/action_sheet_test.dartAdded+1144
novelforge-project/flutter/packages/flutter/test/cupertino/activity_indicator_test.dartAdded+195
novelforge-project/flutter/packages/flutter/test/cupertino/adaptive_text_selection_toolbar_test.dartAdded+282
novelforge-project/flutter/packages/flutter/test/cupertino/app_test.dartAdded+556
novelforge-project/flutter/packages/flutter/test/cupertino/bottom_tab_bar_test.dartAdded+661
novelforge-project/flutter/packages/flutter/test/cupertino/button_test.dartAdded+496
novelforge-project/flutter/packages/flutter/test/cupertino/checkbox_test.dartAdded+413
novelforge-project/flutter/packages/flutter/test/cupertino/colors_test.dartAdded+599
novelforge-project/flutter/packages/flutter/test/cupertino/context_menu_action_test.dartAdded+168
novelforge-project/flutter/packages/flutter/test/cupertino/context_menu_test.dartAdded+889
novelforge-project/flutter/packages/flutter/test/cupertino/date_picker_test.dartAdded+1982
novelforge-project/flutter/packages/flutter/test/cupertino/debug_test.dartAdded+32
novelforge-project/flutter/packages/flutter/test/cupertino/desktop_text_selection_toolbar_button_test.dartAdded+133
novelforge-project/flutter/packages/flutter/test/cupertino/desktop_text_selection_toolbar_test.dartAdded+146
novelforge-project/flutter/packages/flutter/test/cupertino/dialog_test.dartAdded+1644
novelforge-project/flutter/packages/flutter/test/cupertino/form_row_test.dartAdded+208
novelforge-project/flutter/packages/flutter/test/cupertino/form_section_test.dartAdded+223
novelforge-project/flutter/packages/flutter/test/cupertino/icon_theme_data_test.dartAdded+47
novelforge-project/flutter/packages/flutter/test/cupertino/list_section_test.dartAdded+265