text
stringlengths 6
13.6M
| id
stringlengths 13
176
| metadata
dict | __index_level_0__
int64 0
1.69k
|
---|---|---|---|
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// 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';
| flutter/packages/flutter/lib/services.dart/0 | {
"file_path": "flutter/packages/flutter/lib/services.dart",
"repo_id": "flutter",
"token_count": 798
} | 612 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'debug.dart';
// Examples can assume:
// late BuildContext context;
/// Determines the order of the columns inside [CupertinoDatePicker] in
/// time and date time mode.
enum DatePickerDateTimeOrder {
/// Order of the columns, from left to right: date, hour, minute, am/pm.
///
/// Example: Fri Aug 31 | 02 | 08 | PM.
date_time_dayPeriod,
/// Order of the columns, from left to right: date, am/pm, hour, minute.
///
/// Example: Fri Aug 31 | PM | 02 | 08.
date_dayPeriod_time,
/// Order of the columns, from left to right: hour, minute, am/pm, date.
///
/// Example: 02 | 08 | PM | Fri Aug 31.
time_dayPeriod_date,
/// Order of the columns, from left to right: am/pm, hour, minute, date.
///
/// Example: PM | 02 | 08 | Fri Aug 31.
dayPeriod_time_date,
}
/// Determines the order of the columns inside [CupertinoDatePicker] in date mode.
enum DatePickerDateOrder {
/// Order of the columns, from left to right: day, month, year.
///
/// Example: 12 | March | 1996.
dmy,
/// Order of the columns, from left to right: month, day, year.
///
/// Example: March | 12 | 1996.
mdy,
/// Order of the columns, from left to right: year, month, day.
///
/// Example: 1996 | March | 12.
ymd,
/// Order of the columns, from left to right: year, day, month.
///
/// Example: 1996 | 12 | March.
ydm,
}
/// Defines the localized resource values used by the Cupertino widgets.
///
/// See also:
///
/// * [DefaultCupertinoLocalizations], the default, English-only, implementation
/// of this interface.
abstract class CupertinoLocalizations {
/// Year that is shown in [CupertinoDatePicker] spinner corresponding to the
/// given year index.
///
/// Examples: datePickerYear(1) in:
///
/// - US English: 2018
/// - Korean: 2018년
// The global version uses date symbols data from the intl package.
String datePickerYear(int yearIndex);
/// Month that is shown in [CupertinoDatePicker] spinner corresponding to
/// the given month index.
///
/// Examples: datePickerMonth(1) in:
///
/// - US English: January
/// - Korean: 1월
/// - Russian: января
// The global version uses date symbols data from the intl package.
String datePickerMonth(int monthIndex);
/// Month that is shown in [CupertinoDatePicker] spinner corresponding to
/// the given month index in [CupertinoDatePickerMode.monthYear] mode.
///
/// This is distinct from [datePickerMonth] because in some languages, like Russian,
/// the name of a month takes a different form depending
/// on whether it is preceded by a day or whether it stands alone.
///
/// Examples: datePickerMonth(1) in:
///
/// - US English: January
/// - Korean: 1월
/// - Russian: Январь
// The global version uses date symbols data from the intl package.
String datePickerStandaloneMonth(int monthIndex);
/// Day of month that is shown in [CupertinoDatePicker] spinner corresponding
/// to the given day index.
///
/// If weekDay is provided then it will also show weekday name alongside the numerical day.
///
/// Examples: datePickerDayOfMonth(1) in:
///
/// - US English: 1
/// - Korean: 1일
/// Examples: datePickerDayOfMonth(1, 1) in:
///
/// - US English: Mon 1
// The global version uses date symbols data from the intl package.
String datePickerDayOfMonth(int dayIndex, [int? weekDay]);
/// The medium-width date format that is shown in [CupertinoDatePicker]
/// spinner. Abbreviates month and days of week.
///
/// Examples:
///
/// - US English: Wed Sep 27
/// - Russian: ср сент. 27
// The global version is based on intl package's DateFormat.MMMEd.
String datePickerMediumDate(DateTime date);
/// Hour that is shown in [CupertinoDatePicker] spinner corresponding
/// to the given hour value.
///
/// Examples: datePickerHour(1) in:
///
/// - US English: 1
/// - Arabic: ٠١
// The global version uses date symbols data from the intl package.
String datePickerHour(int hour);
/// Semantics label for the given hour value in [CupertinoDatePicker].
// The global version uses the translated string from the arb file.
String? datePickerHourSemanticsLabel(int hour);
/// Minute that is shown in [CupertinoDatePicker] spinner corresponding
/// to the given minute value.
///
/// Examples: datePickerMinute(1) in:
///
/// - US English: 01
/// - Arabic: ٠١
// The global version uses date symbols data from the intl package.
String datePickerMinute(int minute);
/// Semantics label for the given minute value in [CupertinoDatePicker].
// The global version uses the translated string from the arb file.
String? datePickerMinuteSemanticsLabel(int minute);
/// The order of the date elements that will be shown in [CupertinoDatePicker].
// The global version uses the translated string from the arb file.
DatePickerDateOrder get datePickerDateOrder;
/// The order of the time elements that will be shown in [CupertinoDatePicker].
// The global version uses the translated string from the arb file.
DatePickerDateTimeOrder get datePickerDateTimeOrder;
/// The abbreviation for ante meridiem (before noon) shown in the time picker.
// The global version uses the translated string from the arb file.
String get anteMeridiemAbbreviation;
/// The abbreviation for post meridiem (after noon) shown in the time picker.
// The global version uses the translated string from the arb file.
String get postMeridiemAbbreviation;
/// Label shown in date pickers when the date is today.
// The global version uses the translated string from the arb file.
String get todayLabel;
/// The term used by the system to announce dialog alerts.
// The global version uses the translated string from the arb file.
String get alertDialogLabel;
/// The accessibility label used on a tab in a [CupertinoTabBar].
///
/// This message describes the index of the selected tab and how many tabs
/// there are, e.g. 'tab, 1 of 2' in United States English.
///
/// `tabIndex` and `tabCount` must be greater than or equal to one.
String tabSemanticsLabel({required int tabIndex, required int tabCount});
/// Hour that is shown in [CupertinoTimerPicker] corresponding to
/// the given hour value.
///
/// Examples: timerPickerHour(1) in:
///
/// - US English: 1
/// - Arabic: ١
// The global version uses date symbols data from the intl package.
String timerPickerHour(int hour);
/// Minute that is shown in [CupertinoTimerPicker] corresponding to
/// the given minute value.
///
/// Examples: timerPickerMinute(1) in:
///
/// - US English: 1
/// - Arabic: ١
// The global version uses date symbols data from the intl package.
String timerPickerMinute(int minute);
/// Second that is shown in [CupertinoTimerPicker] corresponding to
/// the given second value.
///
/// Examples: timerPickerSecond(1) in:
///
/// - US English: 1
/// - Arabic: ١
// The global version uses date symbols data from the intl package.
String timerPickerSecond(int second);
/// Label that appears next to the hour picker in
/// [CupertinoTimerPicker] when selected hour value is `hour`.
/// This function will deal with pluralization based on the `hour` parameter.
// The global version uses the translated string from the arb file.
String? timerPickerHourLabel(int hour);
/// All possible hour labels that appears next to the hour picker in
/// [CupertinoTimerPicker]
List<String> get timerPickerHourLabels;
/// Label that appears next to the minute picker in
/// [CupertinoTimerPicker] when selected minute value is `minute`.
/// This function will deal with pluralization based on the `minute` parameter.
// The global version uses the translated string from the arb file.
String? timerPickerMinuteLabel(int minute);
/// All possible minute labels that appears next to the minute picker in
/// [CupertinoTimerPicker]
List<String> get timerPickerMinuteLabels;
/// Label that appears next to the minute picker in
/// [CupertinoTimerPicker] when selected minute value is `second`.
/// This function will deal with pluralization based on the `second` parameter.
// The global version uses the translated string from the arb file.
String? timerPickerSecondLabel(int second);
/// All possible second labels that appears next to the second picker in
/// [CupertinoTimerPicker]
List<String> get timerPickerSecondLabels;
/// The term used for cutting.
// The global version uses the translated string from the arb file.
String get cutButtonLabel;
/// The term used for copying.
// The global version uses the translated string from the arb file.
String get copyButtonLabel;
/// The term used for pasting.
// The global version uses the translated string from the arb file.
String get pasteButtonLabel;
/// The term used for clearing a field.
// The global version uses the translated string from the arb file.
String get clearButtonLabel;
/// Label that appears in the Cupertino toolbar when the spell checker
/// couldn't find any replacements for the current word.
// The global version uses the translated string from the arb file.
String get noSpellCheckReplacementsLabel;
/// The term used for selecting everything.
// The global version uses the translated string from the arb file.
String get selectAllButtonLabel;
/// The term used for looking up a selection.
// The global version uses the translated string from the arb file.
String get lookUpButtonLabel;
/// The term used for launching a web search on a selection.
// The global version uses the translated string from the arb file.
String get searchWebButtonLabel;
/// The term used for launching a web search on a selection.
// The global version uses the translated string from the arb file.
String get shareButtonLabel;
/// The default placeholder used in [CupertinoSearchTextField].
// The global version uses the translated string from the arb file.
String get searchTextFieldPlaceholderLabel;
/// Label read out by accessibility tools (VoiceOver) for a modal
/// barrier to indicate that a tap dismisses the barrier.
///
/// A modal barrier can for example be found behind an alert or popup to block
/// user interaction with elements behind it.
String get modalBarrierDismissLabel;
/// Label read out by accessibility tools (VoiceOver) for a context menu to
/// indicate that a tap outside dismisses the context menu.
String get menuDismissLabel;
/// The `CupertinoLocalizations` from the closest [Localizations] instance
/// that encloses the given context.
///
/// If no [CupertinoLocalizations] are available in the given `context`, this
/// method throws an exception.
///
/// This method is just a convenient shorthand for:
/// `Localizations.of<CupertinoLocalizations>(context, CupertinoLocalizations)!`.
///
/// References to the localized resources defined by this class are typically
/// written in terms of this method. For example:
///
/// ```dart
/// CupertinoLocalizations.of(context).anteMeridiemAbbreviation;
/// ```
static CupertinoLocalizations of(BuildContext context) {
assert(debugCheckHasCupertinoLocalizations(context));
return Localizations.of<CupertinoLocalizations>(context, CupertinoLocalizations)!;
}
}
class _CupertinoLocalizationsDelegate extends LocalizationsDelegate<CupertinoLocalizations> {
const _CupertinoLocalizationsDelegate();
@override
bool isSupported(Locale locale) => locale.languageCode == 'en';
@override
Future<CupertinoLocalizations> load(Locale locale) => DefaultCupertinoLocalizations.load(locale);
@override
bool shouldReload(_CupertinoLocalizationsDelegate old) => false;
@override
String toString() => 'DefaultCupertinoLocalizations.delegate(en_US)';
}
/// US English strings for the Cupertino widgets.
class DefaultCupertinoLocalizations implements CupertinoLocalizations {
/// Constructs an object that defines the cupertino widgets' localized strings
/// for US English (only).
///
/// [LocalizationsDelegate] implementations typically call the static [load]
/// function, rather than constructing this class directly.
const DefaultCupertinoLocalizations();
/// Short version of days of week.
static const List<String> shortWeekdays = <String>[
'Mon',
'Tue',
'Wed',
'Thu',
'Fri',
'Sat',
'Sun',
];
static const List<String> _shortMonths = <String>[
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
static const List<String> _months = <String>[
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December',
];
@override
String datePickerYear(int yearIndex) => yearIndex.toString();
@override
String datePickerMonth(int monthIndex) => _months[monthIndex - 1];
@override
String datePickerStandaloneMonth(int monthIndex) => _months[monthIndex - 1];
@override
String datePickerDayOfMonth(int dayIndex, [int? weekDay]) {
if (weekDay != null) {
return ' ${shortWeekdays[weekDay - DateTime.monday]} $dayIndex ';
}
return dayIndex.toString();
}
@override
String datePickerHour(int hour) => hour.toString();
@override
String datePickerHourSemanticsLabel(int hour) => "$hour o'clock";
@override
String datePickerMinute(int minute) => minute.toString().padLeft(2, '0');
@override
String datePickerMinuteSemanticsLabel(int minute) {
if (minute == 1) {
return '1 minute';
}
return '$minute minutes';
}
@override
String datePickerMediumDate(DateTime date) {
return '${shortWeekdays[date.weekday - DateTime.monday]} '
'${_shortMonths[date.month - DateTime.january]} '
'${date.day.toString().padRight(2)}';
}
@override
DatePickerDateOrder get datePickerDateOrder => DatePickerDateOrder.mdy;
@override
DatePickerDateTimeOrder get datePickerDateTimeOrder => DatePickerDateTimeOrder.date_time_dayPeriod;
@override
String get anteMeridiemAbbreviation => 'AM';
@override
String get postMeridiemAbbreviation => 'PM';
@override
String get todayLabel => 'Today';
@override
String get alertDialogLabel => 'Alert';
@override
String tabSemanticsLabel({required int tabIndex, required int tabCount}) {
assert(tabIndex >= 1);
assert(tabCount >= 1);
return 'Tab $tabIndex of $tabCount';
}
@override
String timerPickerHour(int hour) => hour.toString();
@override
String timerPickerMinute(int minute) => minute.toString();
@override
String timerPickerSecond(int second) => second.toString();
@override
String timerPickerHourLabel(int hour) => hour == 1 ? 'hour' : 'hours';
@override
List<String> get timerPickerHourLabels => const <String>['hour', 'hours'];
@override
String timerPickerMinuteLabel(int minute) => 'min.';
@override
List<String> get timerPickerMinuteLabels => const <String>['min.'];
@override
String timerPickerSecondLabel(int second) => 'sec.';
@override
List<String> get timerPickerSecondLabels => const <String>['sec.'];
@override
String get cutButtonLabel => 'Cut';
@override
String get copyButtonLabel => 'Copy';
@override
String get pasteButtonLabel => 'Paste';
@override
String get clearButtonLabel => 'Clear';
@override
String get noSpellCheckReplacementsLabel => 'No Replacements Found';
@override
String get selectAllButtonLabel => 'Select All';
@override
String get lookUpButtonLabel => 'Look Up';
@override
String get searchWebButtonLabel => 'Search Web';
@override
String get shareButtonLabel => 'Share...';
@override
String get searchTextFieldPlaceholderLabel => 'Search';
@override
String get modalBarrierDismissLabel => 'Dismiss';
@override
String get menuDismissLabel => 'Dismiss menu';
/// Creates an object that provides US English resource values for the
/// cupertino library widgets.
///
/// The [locale] parameter is ignored.
///
/// This method is typically used to create a [LocalizationsDelegate].
static Future<CupertinoLocalizations> load(Locale locale) {
return SynchronousFuture<CupertinoLocalizations>(const DefaultCupertinoLocalizations());
}
/// A [LocalizationsDelegate] that uses [DefaultCupertinoLocalizations.load]
/// to create an instance of this class.
static const LocalizationsDelegate<CupertinoLocalizations> delegate = _CupertinoLocalizationsDelegate();
}
| flutter/packages/flutter/lib/src/cupertino/localizations.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/cupertino/localizations.dart",
"repo_id": "flutter",
"token_count": 5020
} | 613 |
// 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 'app.dart' show CupertinoApp;
import 'route.dart';
/// A single tab view with its own [Navigator] state and history.
///
/// A typical tab view is used as the content of each tab in a
/// [CupertinoTabScaffold] where multiple tabs with parallel navigation states
/// and history can co-exist.
///
/// [CupertinoTabView] configures the top-level [Navigator] to search for routes
/// in the following order:
///
/// 1. For the `/` route, the [builder] property, if non-null, is used.
///
/// 2. Otherwise, the [routes] table is used, if it has an entry for the route,
/// including `/` if [builder] is not specified.
///
/// 3. Otherwise, [onGenerateRoute] is called, if provided. It should return a
/// non-null value for any _valid_ route not handled by [builder] and [routes].
///
/// 4. Finally if all else fails [onUnknownRoute] is called.
///
/// These navigation properties are not shared with any sibling [CupertinoTabView]
/// nor any ancestor or descendant [Navigator] instances.
///
/// To push a route above this [CupertinoTabView] instead of inside it (such
/// as when showing a dialog on top of all tabs), use
/// `Navigator.of(rootNavigator: true)`.
///
/// See also:
///
/// * [CupertinoTabScaffold], a typical host that supports switching between tabs.
/// * [CupertinoPageRoute], a typical modal page route pushed onto the
/// [CupertinoTabView]'s [Navigator].
class CupertinoTabView extends StatefulWidget {
/// Creates the content area for a tab in a [CupertinoTabScaffold].
const CupertinoTabView({
super.key,
this.builder,
this.navigatorKey,
this.defaultTitle,
this.routes,
this.onGenerateRoute,
this.onUnknownRoute,
this.navigatorObservers = const <NavigatorObserver>[],
this.restorationScopeId,
});
/// The widget builder for the default route of the tab view
/// ([Navigator.defaultRouteName], which is `/`).
///
/// If a [builder] is specified, then [routes] must not include an entry for `/`,
/// as [builder] takes its place.
///
/// Rebuilding a [CupertinoTabView] with a different [builder] will not clear
/// its current navigation stack or update its descendant. Instead, trigger a
/// rebuild from a descendant in its subtree. This can be done via methods such
/// as:
///
/// * Calling [State.setState] on a descendant [StatefulWidget]'s [State]
/// * Modifying an [InheritedWidget] that a descendant registered itself
/// as a dependent to.
final WidgetBuilder? builder;
/// A key to use when building this widget's [Navigator].
///
/// If a [navigatorKey] is specified, the [Navigator] can be directly
/// manipulated without first obtaining it from a [BuildContext] via
/// [Navigator.of]: from the [navigatorKey], use the [GlobalKey.currentState]
/// getter.
///
/// If this is changed, a new [Navigator] will be created, losing all the
/// tab's state in the process; in that case, the [navigatorObservers]
/// must also be changed, since the previous observers will be attached to the
/// previous navigator.
final GlobalKey<NavigatorState>? navigatorKey;
/// The title of the default route.
final String? defaultTitle;
/// This tab view's routing table.
///
/// When a named route is pushed with [Navigator.pushNamed] inside this tab view,
/// the route name is looked up in this map. If the name is present,
/// the associated [widgets.WidgetBuilder] is used to construct a
/// [CupertinoPageRoute] that performs an appropriate transition to the new
/// route.
///
/// If the tab view only has one page, then you can specify it using [builder] instead.
///
/// If [builder] is specified, then it implies an entry in this table for the
/// [Navigator.defaultRouteName] route (`/`), and it is an error to
/// redundantly provide such a route in the [routes] table.
///
/// If a route is requested that is not specified in this table (or by
/// [builder]), then the [onGenerateRoute] callback is called to build the page
/// instead.
///
/// This routing table is not shared with any routing tables of ancestor or
/// descendant [Navigator]s.
final Map<String, WidgetBuilder>? routes;
/// The route generator callback used when the tab view is navigated to a named route.
///
/// This is used if [routes] does not contain the requested route.
final RouteFactory? onGenerateRoute;
/// Called when [onGenerateRoute] also fails to generate a route.
///
/// This callback is typically used for error handling. For example, this
/// callback might always generate a "not found" page that describes the route
/// that wasn't found.
///
/// The default implementation pushes a route that displays an ugly error
/// message.
final RouteFactory? onUnknownRoute;
/// The list of observers for the [Navigator] created in this tab view.
///
/// This list of observers is not shared with ancestor or descendant [Navigator]s.
final List<NavigatorObserver> navigatorObservers;
/// Restoration ID to save and restore the state of the [Navigator] built by
/// this [CupertinoTabView].
///
/// {@macro flutter.widgets.navigator.restorationScopeId}
final String? restorationScopeId;
@override
State<CupertinoTabView> createState() => _CupertinoTabViewState();
}
class _CupertinoTabViewState extends State<CupertinoTabView> {
late HeroController _heroController;
late List<NavigatorObserver> _navigatorObservers;
@override
void initState() {
super.initState();
_heroController = CupertinoApp.createCupertinoHeroController();
_updateObservers();
}
@override
void didUpdateWidget(CupertinoTabView oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.navigatorKey != oldWidget.navigatorKey
|| widget.navigatorObservers != oldWidget.navigatorObservers) {
_updateObservers();
}
}
@override
void dispose() {
_heroController.dispose();
super.dispose();
}
void _updateObservers() {
_navigatorObservers =
List<NavigatorObserver>.of(widget.navigatorObservers)
..add(_heroController);
}
GlobalKey<NavigatorState>? _ownedNavigatorKey;
GlobalKey<NavigatorState> get _navigatorKey {
if (widget.navigatorKey != null) {
return widget.navigatorKey!;
}
_ownedNavigatorKey ??= GlobalKey<NavigatorState>();
return _ownedNavigatorKey!;
}
// Whether this tab is currently the active tab.
bool get _isActive => TickerMode.of(context);
@override
Widget build(BuildContext context) {
final Widget child = Navigator(
key: _navigatorKey,
onGenerateRoute: _onGenerateRoute,
onUnknownRoute: _onUnknownRoute,
observers: _navigatorObservers,
restorationScopeId: widget.restorationScopeId,
);
// Handle system back gestures only if the tab is currently active.
return NavigatorPopHandler(
enabled: _isActive,
onPop: () {
if (!_isActive) {
return;
}
_navigatorKey.currentState!.maybePop();
},
child: child,
);
}
Route<dynamic>? _onGenerateRoute(RouteSettings settings) {
final String? name = settings.name;
final WidgetBuilder? routeBuilder;
String? title;
if (name == Navigator.defaultRouteName && widget.builder != null) {
routeBuilder = widget.builder;
title = widget.defaultTitle;
} else {
routeBuilder = widget.routes?[name];
}
if (routeBuilder != null) {
return CupertinoPageRoute<dynamic>(
builder: routeBuilder,
title: title,
settings: settings,
);
}
return widget.onGenerateRoute?.call(settings);
}
Route<dynamic>? _onUnknownRoute(RouteSettings settings) {
assert(() {
if (widget.onUnknownRoute == null) {
throw FlutterError(
'Could not find a generator for route $settings in the $runtimeType.\n'
'Generators for routes are searched for in the following order:\n'
' 1. For the "/" route, the "builder" property, if non-null, is used.\n'
' 2. Otherwise, the "routes" table is used, if it has an entry for '
'the route.\n'
' 3. Otherwise, onGenerateRoute is called. It should return a '
'non-null value for any valid route not handled by "builder" and "routes".\n'
' 4. Finally if all else fails onUnknownRoute is called.\n'
'Unfortunately, onUnknownRoute was not set.',
);
}
return true;
}());
final Route<dynamic>? result = widget.onUnknownRoute!(settings);
assert(() {
if (result == null) {
throw FlutterError(
'The onUnknownRoute callback returned null.\n'
'When the $runtimeType requested the route $settings from its '
'onUnknownRoute callback, the callback returned null. Such callbacks '
'must never return null.',
);
}
return true;
}());
return result;
}
}
| flutter/packages/flutter/lib/src/cupertino/tab_view.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/cupertino/tab_view.dart",
"repo_id": "flutter",
"token_count": 2994
} | 614 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:isolate';
import 'constants.dart';
import 'isolates.dart' as isolates;
export 'isolates.dart' show ComputeCallback;
/// The dart:io implementation of [isolate.compute].
@pragma('vm:prefer-inline')
Future<R> compute<M, R>(isolates.ComputeCallback<M, R> callback, M message, {String? debugLabel}) async {
debugLabel ??= kReleaseMode ? 'compute' : callback.toString();
return Isolate.run<R>(() {
return callback(message);
}, debugName: debugLabel);
}
| flutter/packages/flutter/lib/src/foundation/_isolates_io.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/foundation/_isolates_io.dart",
"repo_id": "flutter",
"token_count": 214
} | 615 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui show Brightness;
import 'assertions.dart';
import 'platform.dart';
import 'print.dart';
export 'dart:ui' show Brightness;
export 'print.dart' show DebugPrintCallback;
/// Returns true if none of the foundation library debug variables have been
/// changed.
///
/// This function is used by the test framework to ensure that debug variables
/// haven't been inadvertently changed.
///
/// The `debugPrintOverride` argument can be specified to indicate the expected
/// value of the [debugPrint] variable. This is useful for test frameworks that
/// override [debugPrint] themselves and want to check that their own custom
/// value wasn't overridden by a test.
///
/// See [the foundation library](foundation/foundation-library.html)
/// for a complete list.
bool debugAssertAllFoundationVarsUnset(String reason, { DebugPrintCallback debugPrintOverride = debugPrintThrottled }) {
assert(() {
if (debugPrint != debugPrintOverride ||
debugDefaultTargetPlatformOverride != null ||
debugDoublePrecision != null ||
debugBrightnessOverride != null) {
throw FlutterError(reason);
}
return true;
}());
return true;
}
/// Boolean value indicating whether [debugInstrumentAction] will instrument
/// actions in debug builds.
///
/// The framework does not use [debugInstrumentAction] internally, so this
/// does not enable any additional instrumentation for the framework itself.
///
/// See also:
///
/// * [debugProfileBuildsEnabled], which enables additional tracing of builds
/// in [Widget]s.
/// * [debugProfileLayoutsEnabled], which enables additional tracing of layout
/// events in [RenderObject]s.
/// * [debugProfilePaintsEnabled], which enables additional tracing of paint
/// events in [RenderObject]s.
bool debugInstrumentationEnabled = false;
/// Runs the specified [action], timing how long the action takes in debug
/// builds when [debugInstrumentationEnabled] is true.
///
/// The instrumentation will be printed to the logs using [debugPrint]. In
/// non-debug builds, or when [debugInstrumentationEnabled] is false, this will
/// run [action] without any instrumentation.
///
/// Returns the result of running [action].
///
/// See also:
///
/// * [Timeline], which is used to record synchronous tracing events for
/// visualization in Chrome's tracing format. This method does not
/// implicitly add any timeline events.
Future<T> debugInstrumentAction<T>(String description, Future<T> Function() action) async {
bool instrument = false;
assert(() {
instrument = debugInstrumentationEnabled;
return true;
}());
if (instrument) {
final Stopwatch stopwatch = Stopwatch()..start(); // flutter_ignore: stopwatch (see analyze.dart)
// Ignore context: The framework does not use this function internally so it will not cause flakes.
try {
return await action();
} finally {
stopwatch.stop();
debugPrint('Action "$description" took ${stopwatch.elapsed}');
}
} else {
return action();
}
}
/// Configure [debugFormatDouble] using [num.toStringAsPrecision].
///
/// Defaults to null, which uses the default logic of [debugFormatDouble].
int? debugDoublePrecision;
/// Formats a double to have standard formatting.
///
/// This behavior can be overridden by [debugDoublePrecision].
String debugFormatDouble(double? value) {
if (value == null) {
return 'null';
}
if (debugDoublePrecision != null) {
return value.toStringAsPrecision(debugDoublePrecision!);
}
return value.toStringAsFixed(1);
}
/// A setting that can be used to override the platform [Brightness] exposed
/// from [BindingBase.platformDispatcher].
///
/// See also:
///
/// * [WidgetsApp], which uses the [debugBrightnessOverride] setting in debug mode
/// to construct a [MediaQueryData].
ui.Brightness? debugBrightnessOverride;
/// The address for the active DevTools server used for debugging this
/// application.
String? activeDevToolsServerAddress;
/// The uri for the connected vm service protocol.
String? connectedVmServiceUri;
| flutter/packages/flutter/lib/src/foundation/debug.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/foundation/debug.dart",
"repo_id": "flutter",
"token_count": 1181
} | 616 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:developer';
import 'dart:typed_data';
import 'package:meta/meta.dart';
import '_timeline_io.dart'
if (dart.library.js_interop) '_timeline_web.dart' as impl;
import 'constants.dart';
/// Measures how long blocks of code take to run.
///
/// This class can be used as a drop-in replacement for [Timeline] as it
/// provides methods compatible with [Timeline] signature-wise, and it has
/// minimal overhead.
///
/// Provides [debugReset] and [debugCollect] methods that make it convenient to use in
/// frame-oriented environment where collected metrics can be attributed to a
/// frame, then aggregated into frame statistics, e.g. frame averages.
///
/// Forwards measurements to [Timeline] so they appear in Flutter DevTools.
abstract final class FlutterTimeline {
static _BlockBuffer _buffer = _BlockBuffer();
/// Whether block timings are collected and can be retrieved using the
/// [debugCollect] method.
///
/// This is always false in release mode.
static bool get debugCollectionEnabled => _collectionEnabled;
/// Enables metric collection.
///
/// Metric collection can only be enabled in non-release modes. It is most
/// useful in profile mode where application performance is representative
/// of a deployed application.
///
/// When disabled, resets collected data by calling [debugReset].
///
/// Throws a [StateError] if invoked in release mode.
static set debugCollectionEnabled(bool value) {
if (kReleaseMode) {
throw _createReleaseModeNotSupportedError();
}
if (value == _collectionEnabled) {
return;
}
_collectionEnabled = value;
debugReset();
}
static StateError _createReleaseModeNotSupportedError() {
return StateError('FlutterTimeline metric collection not supported in release mode.');
}
static bool _collectionEnabled = false;
/// Start a synchronous operation labeled `name`.
///
/// Optionally takes a map of `arguments`. This slice may also optionally be
/// associated with a [Flow] event. This operation must be finished by calling
/// [finishSync] before returning to the event queue.
///
/// This is a drop-in replacement for [Timeline.startSync].
static void startSync(String name, { Map<String, Object?>? arguments, Flow? flow }) {
Timeline.startSync(name, arguments: arguments, flow: flow);
if (!kReleaseMode && _collectionEnabled) {
_buffer.startSync(name, arguments: arguments, flow: flow);
}
}
/// Finish the last synchronous operation that was started.
///
/// This is a drop-in replacement for [Timeline.finishSync].
static void finishSync() {
Timeline.finishSync();
if (!kReleaseMode && _collectionEnabled) {
_buffer.finishSync();
}
}
/// Emit an instant event.
///
/// This is a drop-in replacement for [Timeline.instantSync].
static void instantSync(String name, { Map<String, Object?>? arguments }) {
Timeline.instantSync(name, arguments: arguments);
}
/// A utility method to time a synchronous `function`. Internally calls
/// `function` bracketed by calls to [startSync] and [finishSync].
///
/// This is a drop-in replacement for [Timeline.timeSync].
static T timeSync<T>(String name, TimelineSyncFunction<T> function,
{ Map<String, Object?>? arguments, Flow? flow }) {
startSync(name, arguments: arguments, flow: flow);
try {
return function();
} finally {
finishSync();
}
}
/// The current time stamp from the clock used by the timeline in
/// microseconds.
///
/// When run on the Dart VM, uses the same monotonic clock as the embedding
/// API's `Dart_TimelineGetMicros`.
///
/// When run on the web, uses `window.performance.now`.
///
/// This is a drop-in replacement for [Timeline.now].
static int get now => impl.performanceTimestamp.toInt();
/// Returns timings collected since [debugCollectionEnabled] was set to true,
/// since the previous [debugCollect], or since the previous [debugReset],
/// whichever was last.
///
/// Resets the collected timings.
///
/// This is only meant to be used in non-release modes, typically in profile
/// mode that provides timings close to release mode timings.
static AggregatedTimings debugCollect() {
if (kReleaseMode) {
throw _createReleaseModeNotSupportedError();
}
if (!_collectionEnabled) {
throw StateError('Timeline metric collection not enabled.');
}
final AggregatedTimings result = AggregatedTimings(_buffer.computeTimings());
debugReset();
return result;
}
/// Forgets all previously collected timing data.
///
/// Use this method to scope metrics to a frame, a pointer event, or any
/// other event. To do that, call [debugReset] at the start of the event, then
/// call [debugCollect] at the end of the event.
///
/// This is only meant to be used in non-release modes.
static void debugReset() {
if (kReleaseMode) {
throw _createReleaseModeNotSupportedError();
}
_buffer = _BlockBuffer();
}
}
/// Provides [start], [end], and [duration] of a named block of code, timed by
/// [FlutterTimeline].
@immutable
final class TimedBlock {
/// Creates a timed block of code from a [name], [start], and [end].
///
/// The [name] should be sufficiently unique and descriptive for someone to
/// easily tell which part of code was measured.
const TimedBlock({
required this.name,
required this.start,
required this.end,
}) : assert(end >= start, 'The start timestamp must not be greater than the end timestamp.');
/// A readable label for a block of code that was measured.
///
/// This field should be sufficiently unique and descriptive for someone to
/// easily tell which part of code was measured.
final String name;
/// The timestamp in microseconds that marks the beginning of the measured
/// block of code.
final double start;
/// The timestamp in microseconds that marks the end of the measured block of
/// code.
final double end;
/// How long the measured block of code took to execute in microseconds.
double get duration => end - start;
@override
String toString() {
return 'TimedBlock($name, $start, $end, $duration)';
}
}
/// Provides aggregated results for timings collected by [FlutterTimeline].
@immutable
final class AggregatedTimings {
/// Creates aggregated timings for the provided timed blocks.
AggregatedTimings(this.timedBlocks);
/// All timed blocks collected between the last reset and [FlutterTimeline.debugCollect].
final List<TimedBlock> timedBlocks;
/// Aggregated timed blocks collected between the last reset and [FlutterTimeline.debugCollect].
///
/// Does not guarantee that all code blocks will be reported. Only those that
/// executed since the last reset are listed here. Use [getAggregated] for
/// graceful handling of missing code blocks.
late final List<AggregatedTimedBlock> aggregatedBlocks = _computeAggregatedBlocks();
List<AggregatedTimedBlock> _computeAggregatedBlocks() {
final Map<String, (double, int)> aggregate = <String, (double, int)>{};
for (final TimedBlock block in timedBlocks) {
final (double, int) previousValue = aggregate.putIfAbsent(block.name, () => (0, 0));
aggregate[block.name] = (previousValue.$1 + block.duration, previousValue.$2 + 1);
}
return aggregate.entries.map<AggregatedTimedBlock>(
(MapEntry<String, (double, int)> entry) {
return AggregatedTimedBlock(name: entry.key, duration: entry.value.$1, count: entry.value.$2);
}
).toList();
}
/// Returns aggregated numbers for a named block of code.
///
/// If the block in question never executed since the last reset, returns an
/// aggregation with zero duration and count.
AggregatedTimedBlock getAggregated(String name) {
return aggregatedBlocks.singleWhere(
(AggregatedTimedBlock block) => block.name == name,
// Handle the case where there are no recorded blocks of the specified
// type. In this case, the aggregated duration is simply zero, and so is
// the number of occurrences (i.e. count).
orElse: () => AggregatedTimedBlock(name: name, duration: 0, count: 0),
);
}
}
/// Aggregates multiple [TimedBlock] objects that share a [name].
///
/// It is common for the same block of code to be executed multiple times within
/// a frame. It is useful to combine multiple executions and report the total
/// amount of time attributed to that block of code.
@immutable
final class AggregatedTimedBlock {
/// Creates a timed block of code from a [name] and [duration].
///
/// The [name] should be sufficiently unique and descriptive for someone to
/// easily tell which part of code was measured.
const AggregatedTimedBlock({
required this.name,
required this.duration,
required this.count,
}) : assert(duration >= 0);
/// A readable label for a block of code that was measured.
///
/// This field should be sufficiently unique and descriptive for someone to
/// easily tell which part of code was measured.
final String name;
/// The sum of [TimedBlock.duration] values of aggregated blocks.
final double duration;
/// The number of [TimedBlock] objects aggregated.
final int count;
@override
String toString() {
return 'AggregatedTimedBlock($name, $duration, $count)';
}
}
const int _kSliceSize = 500;
/// A growable list of float64 values with predictable [add] performance.
///
/// The list is organized into a "chain" of [Float64List]s. The object starts
/// with a `Float64List` "slice". When [add] is called, the value is added to
/// the slice. Once the slice is full, it is moved into the chain, and a new
/// slice is allocated. Slice size is static and therefore its allocation has
/// predictable cost. This is unlike the default [List] implementation, which,
/// when full, doubles its buffer size and copies all old elements into the new
/// buffer, leading to unpredictable performance. This makes it a poor choice
/// for recording performance because buffer reallocation would affect the
/// runtime.
///
/// The trade-off is that reading values back from the chain is more expensive
/// compared to [List] because it requires iterating over multiple slices. This
/// is a reasonable trade-off for performance metrics, because it is more
/// important to minimize the overhead while recording metrics, than it is when
/// reading them.
final class _Float64ListChain {
_Float64ListChain();
final List<Float64List> _chain = <Float64List>[];
Float64List _slice = Float64List(_kSliceSize);
int _pointer = 0;
int get length => _length;
int _length = 0;
/// Adds and [element] to this chain.
void add(double element) {
_slice[_pointer] = element;
_pointer += 1;
_length += 1;
if (_pointer >= _kSliceSize) {
_chain.add(_slice);
_slice = Float64List(_kSliceSize);
_pointer = 0;
}
}
/// Returns all elements added to this chain.
///
/// This getter is not optimized to be fast. It is assumed that when metrics
/// are read back, they do not affect the timings of the work being
/// benchmarked.
List<double> extractElements() {
final List<double> result = <double>[];
_chain.forEach(result.addAll);
for (int i = 0; i < _pointer; i++) {
result.add(_slice[i]);
}
return result;
}
}
/// Same as [_Float64ListChain] but for recording string values.
final class _StringListChain {
_StringListChain();
final List<List<String?>> _chain = <List<String?>>[];
List<String?> _slice = List<String?>.filled(_kSliceSize, null);
int _pointer = 0;
int get length => _length;
int _length = 0;
/// Adds and [element] to this chain.
void add(String element) {
_slice[_pointer] = element;
_pointer += 1;
_length += 1;
if (_pointer >= _kSliceSize) {
_chain.add(_slice);
_slice = List<String?>.filled(_kSliceSize, null);
_pointer = 0;
}
}
/// Returns all elements added to this chain.
///
/// This getter is not optimized to be fast. It is assumed that when metrics
/// are read back, they do not affect the timings of the work being
/// benchmarked.
List<String> extractElements() {
final List<String> result = <String>[];
for (final List<String?> slice in _chain) {
for (final String? element in slice) {
result.add(element!);
}
}
for (int i = 0; i < _pointer; i++) {
result.add(_slice[i]!);
}
return result;
}
}
/// A buffer that records starts and ends of code blocks, and their names.
final class _BlockBuffer {
// Start-finish blocks can be nested. Track this nestedness by stacking the
// start timestamps. Finish timestamps will pop timings from the stack and
// add the (start, finish) tuple to the _block.
static const int _stackDepth = 1000;
static final Float64List _startStack = Float64List(_stackDepth);
static final List<String?> _nameStack = List<String?>.filled(_stackDepth, null);
static int _stackPointer = 0;
final _Float64ListChain _starts = _Float64ListChain();
final _Float64ListChain _finishes = _Float64ListChain();
final _StringListChain _names = _StringListChain();
List<TimedBlock> computeTimings() {
assert(
_stackPointer == 0,
'Invalid sequence of `startSync` and `finishSync`.\n'
'The operation stack was not empty. The following operations are still '
'waiting to be finished via the `finishSync` method:\n'
'${List<String>.generate(_stackPointer, (int i) => _nameStack[i]!).join(', ')}'
);
final List<TimedBlock> result = <TimedBlock>[];
final int length = _finishes.length;
final List<double> starts = _starts.extractElements();
final List<double> finishes = _finishes.extractElements();
final List<String> names = _names.extractElements();
assert(starts.length == length);
assert(finishes.length == length);
assert(names.length == length);
for (int i = 0; i < length; i++) {
result.add(TimedBlock(
start: starts[i],
end: finishes[i],
name: names[i],
));
}
return result;
}
void startSync(String name, { Map<String, Object?>? arguments, Flow? flow }) {
_startStack[_stackPointer] = impl.performanceTimestamp;
_nameStack[_stackPointer] = name;
_stackPointer += 1;
}
void finishSync() {
assert(
_stackPointer > 0,
'Invalid sequence of `startSync` and `finishSync`.\n'
'Attempted to finish timing a block of code, but there are no pending '
'`startSync` calls.'
);
final double finishTime = impl.performanceTimestamp;
final double startTime = _startStack[_stackPointer - 1];
final String name = _nameStack[_stackPointer - 1]!;
_stackPointer -= 1;
_starts.add(startTime);
_finishes.add(finishTime);
_names.add(name);
}
}
| flutter/packages/flutter/lib/src/foundation/timeline.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/foundation/timeline.dart",
"repo_id": "flutter",
"token_count": 4631
} | 617 |
// 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';
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
import 'constants.dart';
import 'drag_details.dart';
import 'events.dart';
import 'recognizer.dart';
import 'velocity_tracker.dart';
export 'dart:ui' show PointerDeviceKind;
export 'package:flutter/foundation.dart' show DiagnosticPropertiesBuilder;
export 'drag.dart' show DragEndDetails, DragUpdateDetails;
export 'drag_details.dart' show DragDownDetails, DragStartDetails, DragUpdateDetails, GestureDragDownCallback, GestureDragStartCallback, GestureDragUpdateCallback;
export 'events.dart' show PointerDownEvent, PointerEvent, PointerPanZoomStartEvent;
export 'recognizer.dart' show DragStartBehavior;
export 'velocity_tracker.dart' show VelocityEstimate, VelocityTracker;
enum _DragState {
ready,
possible,
accepted,
}
/// {@template flutter.gestures.monodrag.GestureDragEndCallback}
/// Signature for when a pointer that was previously in contact with the screen
/// and moving is no longer in contact with the screen.
///
/// The velocity at which the pointer was moving when it stopped contacting
/// the screen is available in the `details`.
/// {@endtemplate}
///
/// Used by [DragGestureRecognizer.onEnd].
typedef GestureDragEndCallback = void Function(DragEndDetails details);
/// Signature for when the pointer that previously triggered a
/// [GestureDragDownCallback] did not complete.
///
/// Used by [DragGestureRecognizer.onCancel].
typedef GestureDragCancelCallback = void Function();
/// Signature for a function that builds a [VelocityTracker].
///
/// Used by [DragGestureRecognizer.velocityTrackerBuilder].
typedef GestureVelocityTrackerBuilder = VelocityTracker Function(PointerEvent event);
/// Recognizes movement.
///
/// In contrast to [MultiDragGestureRecognizer], [DragGestureRecognizer]
/// recognizes a single gesture sequence for all the pointers it watches, which
/// means that the recognizer has at most one drag sequence active at any given
/// time regardless of how many pointers are in contact with the screen.
///
/// [DragGestureRecognizer] is not intended to be used directly. Instead,
/// consider using one of its subclasses to recognize specific types for drag
/// gestures.
///
/// [DragGestureRecognizer] competes on pointer events only when it has at
/// least one non-null callback. If it has no callbacks, it is a no-op.
///
/// See also:
///
/// * [HorizontalDragGestureRecognizer], for left and right drags.
/// * [VerticalDragGestureRecognizer], for up and down drags.
/// * [PanGestureRecognizer], for drags that are not locked to a single axis.
abstract class DragGestureRecognizer extends OneSequenceGestureRecognizer {
/// Initialize the object.
///
/// {@macro flutter.gestures.GestureRecognizer.supportedDevices}
DragGestureRecognizer({
super.debugOwner,
this.dragStartBehavior = DragStartBehavior.start,
this.multitouchDragStrategy = MultitouchDragStrategy.latestPointer,
this.velocityTrackerBuilder = _defaultBuilder,
this.onlyAcceptDragOnThreshold = false,
super.supportedDevices,
AllowedButtonsFilter? allowedButtonsFilter,
}) : super(allowedButtonsFilter: allowedButtonsFilter ?? _defaultButtonAcceptBehavior);
static VelocityTracker _defaultBuilder(PointerEvent event) => VelocityTracker.withKind(event.kind);
// Accept the input if, and only if, [kPrimaryButton] is pressed.
static bool _defaultButtonAcceptBehavior(int buttons) => buttons == kPrimaryButton;
/// Configure the behavior of offsets passed to [onStart].
///
/// If set to [DragStartBehavior.start], the [onStart] callback will be called
/// with the position of the pointer at the time this gesture recognizer won
/// the arena. If [DragStartBehavior.down], [onStart] will be called with
/// the position of the first detected down event for the pointer. When there
/// are no other gestures competing with this gesture in the arena, there's
/// no difference in behavior between the two settings.
///
/// For more information about the gesture arena:
/// https://flutter.dev/docs/development/ui/advanced/gestures#gesture-disambiguation
///
/// By default, the drag start behavior is [DragStartBehavior.start].
///
/// ## Example:
///
/// A [HorizontalDragGestureRecognizer] and a [VerticalDragGestureRecognizer]
/// compete with each other. A finger presses down on the screen with
/// offset (500.0, 500.0), and then moves to position (510.0, 500.0) before
/// the [HorizontalDragGestureRecognizer] wins the arena. With
/// [dragStartBehavior] set to [DragStartBehavior.down], the [onStart]
/// callback will be called with position (500.0, 500.0). If it is
/// instead set to [DragStartBehavior.start], [onStart] will be called with
/// position (510.0, 500.0).
DragStartBehavior dragStartBehavior;
/// {@template flutter.gestures.monodrag.DragGestureRecognizer.multitouchDragStrategy}
/// Configure the multi-finger drag strategy on multi-touch devices.
///
/// If set to [MultitouchDragStrategy.latestPointer], the drag gesture recognizer
/// will only track the latest active (accepted by this recognizer) pointer, which
/// appears to be only one finger dragging.
///
/// If set to [MultitouchDragStrategy.averageBoundaryPointers], all active
/// pointers will be tracked, and the result is computed from the boundary pointers.
///
/// If set to [MultitouchDragStrategy.sumAllPointers],
/// all active pointers will be tracked together and the scrolling offset
/// is the sum of the offsets of all active pointers
/// {@endtemplate}
///
/// By default, the strategy is [MultitouchDragStrategy.latestPointer].
///
/// See also:
///
/// * [MultitouchDragStrategy], which defines several different drag strategies for
/// multi-finger drag.
MultitouchDragStrategy multitouchDragStrategy;
/// A pointer has contacted the screen with a primary button and might begin
/// to move.
///
/// The position of the pointer is provided in the callback's `details`
/// argument, which is a [DragDownDetails] object.
///
/// See also:
///
/// * [allowedButtonsFilter], which decides which button will be allowed.
/// * [DragDownDetails], which is passed as an argument to this callback.
GestureDragDownCallback? onDown;
/// {@template flutter.gestures.monodrag.DragGestureRecognizer.onStart}
/// A pointer has contacted the screen with a primary button and has begun to
/// move.
/// {@endtemplate}
///
/// The position of the pointer is provided in the callback's `details`
/// argument, which is a [DragStartDetails] object. The [dragStartBehavior]
/// determines this position.
///
/// See also:
///
/// * [allowedButtonsFilter], which decides which button will be allowed.
/// * [DragStartDetails], which is passed as an argument to this callback.
GestureDragStartCallback? onStart;
/// {@template flutter.gestures.monodrag.DragGestureRecognizer.onUpdate}
/// A pointer that is in contact with the screen with a primary button and
/// moving has moved again.
/// {@endtemplate}
///
/// The distance traveled by the pointer since the last update is provided in
/// the callback's `details` argument, which is a [DragUpdateDetails] object.
///
/// If this gesture recognizer recognizes movement on a single axis (a
/// [VerticalDragGestureRecognizer] or [HorizontalDragGestureRecognizer]),
/// then `details` will reflect movement only on that axis and its
/// [DragUpdateDetails.primaryDelta] will be non-null.
/// If this gesture recognizer recognizes movement in all directions
/// (a [PanGestureRecognizer]), then `details` will reflect movement on
/// both axes and its [DragUpdateDetails.primaryDelta] will be null.
///
/// See also:
///
/// * [allowedButtonsFilter], which decides which button will be allowed.
/// * [DragUpdateDetails], which is passed as an argument to this callback.
GestureDragUpdateCallback? onUpdate;
/// {@template flutter.gestures.monodrag.DragGestureRecognizer.onEnd}
/// A pointer that was previously in contact with the screen with a primary
/// button and moving is no longer in contact with the screen and was moving
/// at a specific velocity when it stopped contacting the screen.
/// {@endtemplate}
///
/// The velocity is provided in the callback's `details` argument, which is a
/// [DragEndDetails] object.
///
/// If this gesture recognizer recognizes movement on a single axis (a
/// [VerticalDragGestureRecognizer] or [HorizontalDragGestureRecognizer]),
/// then `details` will reflect movement only on that axis and its
/// [DragEndDetails.primaryVelocity] will be non-null.
/// If this gesture recognizer recognizes movement in all directions
/// (a [PanGestureRecognizer]), then `details` will reflect movement on
/// both axes and its [DragEndDetails.primaryVelocity] will be null.
///
/// See also:
///
/// * [allowedButtonsFilter], which decides which button will be allowed.
/// * [DragEndDetails], which is passed as an argument to this callback.
GestureDragEndCallback? onEnd;
/// The pointer that previously triggered [onDown] did not complete.
///
/// See also:
///
/// * [allowedButtonsFilter], which decides which button will be allowed.
GestureDragCancelCallback? onCancel;
/// The minimum distance an input pointer drag must have moved
/// to be considered a fling gesture.
///
/// This value is typically compared with the distance traveled along the
/// scrolling axis. If null then [kTouchSlop] is used.
double? minFlingDistance;
/// The minimum velocity for an input pointer drag to be considered fling.
///
/// This value is typically compared with the magnitude of fling gesture's
/// velocity along the scrolling axis. If null then [kMinFlingVelocity]
/// is used.
double? minFlingVelocity;
/// Fling velocity magnitudes will be clamped to this value.
///
/// If null then [kMaxFlingVelocity] is used.
double? maxFlingVelocity;
/// Whether the drag threshold should be met before dispatching any drag callbacks.
///
/// The drag threshold is met when the global distance traveled by a pointer has
/// exceeded the defined threshold on the relevant axis, i.e. y-axis for the
/// [VerticalDragGestureRecognizer], x-axis for the [HorizontalDragGestureRecognizer],
/// and the entire plane for [PanGestureRecognizer]. The threshold for both
/// [VerticalDragGestureRecognizer] and [HorizontalDragGestureRecognizer] are
/// calculated by [computeHitSlop], while [computePanSlop] is used for
/// [PanGestureRecognizer].
///
/// If true, the drag callbacks will only be dispatched when this recognizer has
/// won the arena and the drag threshold has been met.
///
/// If false, the drag callbacks will be dispatched immediately when this recognizer
/// has won the arena.
///
/// This value defaults to false.
bool onlyAcceptDragOnThreshold;
/// Determines the type of velocity estimation method to use for a potential
/// drag gesture, when a new pointer is added.
///
/// To estimate the velocity of a gesture, [DragGestureRecognizer] calls
/// [velocityTrackerBuilder] when it starts to track a new pointer in
/// [addAllowedPointer], and add subsequent updates on the pointer to the
/// resulting velocity tracker, until the gesture recognizer stops tracking
/// the pointer. This allows you to specify a different velocity estimation
/// strategy for each allowed pointer added, by changing the type of velocity
/// tracker this [GestureVelocityTrackerBuilder] returns.
///
/// If left unspecified the default [velocityTrackerBuilder] creates a new
/// [VelocityTracker] for every pointer added.
///
/// See also:
///
/// * [VelocityTracker], a velocity tracker that uses least squares estimation
/// on the 20 most recent pointer data samples. It's a well-rounded velocity
/// tracker and is used by default.
/// * [IOSScrollViewFlingVelocityTracker], a specialized velocity tracker for
/// determining the initial fling velocity for a [Scrollable] on iOS, to
/// match the native behavior on that platform.
GestureVelocityTrackerBuilder velocityTrackerBuilder;
_DragState _state = _DragState.ready;
late OffsetPair _initialPosition;
late OffsetPair _pendingDragOffset;
late OffsetPair _finalPosition;
Duration? _lastPendingEventTimestamp;
/// When asserts are enabled, returns the last tracked pending event timestamp
/// for this recognizer.
///
/// Otherwise, returns null.
///
/// This getter is intended for use in framework unit tests. Applications must
/// not depend on its value.
@visibleForTesting
Duration? get debugLastPendingEventTimestamp {
Duration? lastPendingEventTimestamp;
assert(() {
lastPendingEventTimestamp = _lastPendingEventTimestamp;
return true;
}());
return lastPendingEventTimestamp;
}
// The buttons sent by `PointerDownEvent`. If a `PointerMoveEvent` comes with a
// different set of buttons, the gesture is canceled.
int? _initialButtons;
Matrix4? _lastTransform;
/// Distance moved in the global coordinate space of the screen in drag direction.
///
/// If drag is only allowed along a defined axis, this value may be negative to
/// differentiate the direction of the drag.
late double _globalDistanceMoved;
/// Determines if a gesture is a fling or not based on velocity.
///
/// A fling calls its gesture end callback with a velocity, allowing the
/// provider of the callback to respond by carrying the gesture forward with
/// inertia, for example.
bool isFlingGesture(VelocityEstimate estimate, PointerDeviceKind kind);
/// Determines if a gesture is a fling or not, and if so its effective velocity.
///
/// A fling calls its gesture end callback with a velocity, allowing the
/// provider of the callback to respond by carrying the gesture forward with
/// inertia, for example.
DragEndDetails? _considerFling(VelocityEstimate estimate, PointerDeviceKind kind);
Offset _getDeltaForDetails(Offset delta);
double? _getPrimaryValueFromOffset(Offset value);
/// The axis (horizontal or vertical) corresponding to the primary drag direction.
///
/// The [PanGestureRecognizer] returns null.
_DragDirection? _getPrimaryDragAxis() => null;
bool _hasSufficientGlobalDistanceToAccept(PointerDeviceKind pointerDeviceKind, double? deviceTouchSlop);
bool _hasDragThresholdBeenMet = false;
final Map<int, VelocityTracker> _velocityTrackers = <int, VelocityTracker>{};
// The move delta of each pointer before the next frame.
//
// The key is the pointer ID. It is cleared whenever a new batch of pointer events is detected.
final Map<int, Offset> _moveDeltaBeforeFrame = <int, Offset>{};
// The timestamp of all events of the current frame.
//
// On a event with a different timestamp, the event is considered a new batch.
Duration? _frameTimeStamp;
Offset _lastUpdatedDeltaForPan = Offset.zero;
@override
bool isPointerAllowed(PointerEvent event) {
if (_initialButtons == null) {
if (onDown == null &&
onStart == null &&
onUpdate == null &&
onEnd == null &&
onCancel == null) {
return false;
}
} else {
// There can be multiple drags simultaneously. Their effects are combined.
if (event.buttons != _initialButtons) {
return false;
}
}
return super.isPointerAllowed(event as PointerDownEvent);
}
void _addPointer(PointerEvent event) {
_velocityTrackers[event.pointer] = velocityTrackerBuilder(event);
switch (_state) {
case _DragState.ready:
_state = _DragState.possible;
_initialPosition = OffsetPair(global: event.position, local: event.localPosition);
_finalPosition = _initialPosition;
_pendingDragOffset = OffsetPair.zero;
_globalDistanceMoved = 0.0;
_lastPendingEventTimestamp = event.timeStamp;
_lastTransform = event.transform;
_checkDown();
case _DragState.possible:
break;
case _DragState.accepted:
resolve(GestureDisposition.accepted);
}
}
@override
void addAllowedPointer(PointerDownEvent event) {
super.addAllowedPointer(event);
if (_state == _DragState.ready) {
_initialButtons = event.buttons;
}
_addPointer(event);
}
@override
void addAllowedPointerPanZoom(PointerPanZoomStartEvent event) {
super.addAllowedPointerPanZoom(event);
startTrackingPointer(event.pointer, event.transform);
if (_state == _DragState.ready) {
_initialButtons = kPrimaryButton;
}
_addPointer(event);
}
bool _shouldTrackMoveEvent(int pointer) {
final bool result;
switch (multitouchDragStrategy) {
case MultitouchDragStrategy.sumAllPointers:
case MultitouchDragStrategy.averageBoundaryPointers:
result = true;
case MultitouchDragStrategy.latestPointer:
result = _activePointer == null || pointer == _activePointer;
}
return result;
}
void _recordMoveDeltaForMultitouch(int pointer, Offset localDelta) {
if (multitouchDragStrategy != MultitouchDragStrategy.averageBoundaryPointers) {
assert(_frameTimeStamp == null);
assert(_moveDeltaBeforeFrame.isEmpty);
return;
}
assert(_frameTimeStamp == SchedulerBinding.instance.currentSystemFrameTimeStamp);
if (_state != _DragState.accepted || localDelta == Offset.zero) {
return;
}
if (_moveDeltaBeforeFrame.containsKey(pointer)) {
final Offset offset = _moveDeltaBeforeFrame[pointer]!;
_moveDeltaBeforeFrame[pointer] = offset + localDelta;
} else {
_moveDeltaBeforeFrame[pointer] = localDelta;
}
}
double _getSumDelta({
required int pointer,
required bool positive,
required _DragDirection axis,
}) {
double sum = 0.0;
if (!_moveDeltaBeforeFrame.containsKey(pointer)) {
return sum;
}
final Offset offset = _moveDeltaBeforeFrame[pointer]!;
if (positive) {
if (axis == _DragDirection.vertical) {
sum = max(offset.dy, 0.0);
} else {
sum = max(offset.dx, 0.0);
}
} else {
if (axis == _DragDirection.vertical) {
sum = min(offset.dy, 0.0);
} else {
sum = min(offset.dx, 0.0);
}
}
return sum;
}
int? _getMaxSumDeltaPointer({
required bool positive,
required _DragDirection axis,
}) {
if (_moveDeltaBeforeFrame.isEmpty) {
return null;
}
int? ret;
double? max;
double sum;
for (final int pointer in _moveDeltaBeforeFrame.keys) {
sum = _getSumDelta(pointer: pointer, positive: positive, axis: axis);
if (ret == null) {
ret = pointer;
max = sum;
} else {
if (positive) {
if (sum > max!) {
ret = pointer;
max = sum;
}
} else {
if (sum < max!) {
ret = pointer;
max = sum;
}
}
}
}
assert(ret != null);
return ret;
}
Offset _resolveLocalDeltaForMultitouch(int pointer, Offset localDelta) {
if (multitouchDragStrategy != MultitouchDragStrategy.averageBoundaryPointers) {
if (_frameTimeStamp != null) {
_moveDeltaBeforeFrame.clear();
_frameTimeStamp = null;
_lastUpdatedDeltaForPan = Offset.zero;
}
return localDelta;
}
final Duration currentSystemFrameTimeStamp = SchedulerBinding.instance.currentSystemFrameTimeStamp;
if (_frameTimeStamp != currentSystemFrameTimeStamp) {
_moveDeltaBeforeFrame.clear();
_lastUpdatedDeltaForPan = Offset.zero;
_frameTimeStamp = currentSystemFrameTimeStamp;
}
assert(_frameTimeStamp == SchedulerBinding.instance.currentSystemFrameTimeStamp);
final _DragDirection? axis = _getPrimaryDragAxis();
if (_state != _DragState.accepted || localDelta == Offset.zero || (_moveDeltaBeforeFrame.isEmpty && axis != null)) {
return localDelta;
}
final double dx,dy;
if (axis == _DragDirection.horizontal) {
dx = _resolveDelta(pointer: pointer, axis: _DragDirection.horizontal, localDelta: localDelta);
assert(dx.abs() <= localDelta.dx.abs());
dy = 0.0;
} else if (axis == _DragDirection.vertical) {
dx = 0.0;
dy = _resolveDelta(pointer: pointer, axis: _DragDirection.vertical, localDelta: localDelta);
assert(dy.abs() <= localDelta.dy.abs());
} else {
final double averageX = _resolveDeltaForPanGesture(axis: _DragDirection.horizontal, localDelta: localDelta);
final double averageY = _resolveDeltaForPanGesture(axis: _DragDirection.vertical, localDelta: localDelta);
final Offset updatedDelta = Offset(averageX, averageY) - _lastUpdatedDeltaForPan;
_lastUpdatedDeltaForPan = Offset(averageX, averageY);
dx = updatedDelta.dx;
dy = updatedDelta.dy;
}
return Offset(dx, dy);
}
double _resolveDelta({
required int pointer,
required _DragDirection axis,
required Offset localDelta,
}) {
final bool positive = axis == _DragDirection.horizontal ? localDelta.dx > 0 : localDelta.dy > 0;
final double delta = axis == _DragDirection.horizontal ? localDelta.dx : localDelta.dy;
final int? maxSumDeltaPointer = _getMaxSumDeltaPointer(positive: positive, axis: axis);
assert(maxSumDeltaPointer != null);
if (maxSumDeltaPointer == pointer) {
return delta;
} else {
final double maxSumDelta = _getSumDelta(pointer: maxSumDeltaPointer!, positive: positive, axis: axis);
final double curPointerSumDelta = _getSumDelta(pointer: pointer, positive: positive, axis: axis);
if (positive) {
if (curPointerSumDelta + delta > maxSumDelta) {
return curPointerSumDelta + delta - maxSumDelta;
} else {
return 0.0;
}
} else {
if (curPointerSumDelta + delta < maxSumDelta) {
return curPointerSumDelta + delta - maxSumDelta;
} else {
return 0.0;
}
}
}
}
double _resolveDeltaForPanGesture({
required _DragDirection axis,
required Offset localDelta,
}) {
final double delta = axis == _DragDirection.horizontal ? localDelta.dx : localDelta.dy;
final int pointerCount = _acceptedActivePointers.length;
assert(pointerCount >= 1);
double sum = delta;
for (final Offset offset in _moveDeltaBeforeFrame.values) {
if (axis == _DragDirection.horizontal) {
sum += offset.dx;
} else {
sum += offset.dy;
}
}
return sum / pointerCount;
}
@override
void handleEvent(PointerEvent event) {
assert(_state != _DragState.ready);
if (!event.synthesized &&
(event is PointerDownEvent ||
event is PointerMoveEvent ||
event is PointerPanZoomStartEvent ||
event is PointerPanZoomUpdateEvent)) {
final VelocityTracker tracker = _velocityTrackers[event.pointer]!;
if (event is PointerPanZoomStartEvent) {
tracker.addPosition(event.timeStamp, Offset.zero);
} else if (event is PointerPanZoomUpdateEvent) {
tracker.addPosition(event.timeStamp, event.pan);
} else {
tracker.addPosition(event.timeStamp, event.localPosition);
}
}
if (event is PointerMoveEvent && event.buttons != _initialButtons) {
_giveUpPointer(event.pointer);
return;
}
if ((event is PointerMoveEvent || event is PointerPanZoomUpdateEvent)
&& _shouldTrackMoveEvent(event.pointer)) {
final Offset delta = (event is PointerMoveEvent) ? event.delta : (event as PointerPanZoomUpdateEvent).panDelta;
final Offset localDelta = (event is PointerMoveEvent) ? event.localDelta : (event as PointerPanZoomUpdateEvent).localPanDelta;
final Offset position = (event is PointerMoveEvent) ? event.position : (event.position + (event as PointerPanZoomUpdateEvent).pan);
final Offset localPosition = (event is PointerMoveEvent) ? event.localPosition : (event.localPosition + (event as PointerPanZoomUpdateEvent).localPan);
_finalPosition = OffsetPair(local: localPosition, global: position);
final Offset resolvedDelta = _resolveLocalDeltaForMultitouch(event.pointer, localDelta);
switch (_state) {
case _DragState.ready || _DragState.possible:
_pendingDragOffset += OffsetPair(local: localDelta, global: delta);
_lastPendingEventTimestamp = event.timeStamp;
_lastTransform = event.transform;
final Offset movedLocally = _getDeltaForDetails(localDelta);
final Matrix4? localToGlobalTransform = event.transform == null ? null : Matrix4.tryInvert(event.transform!);
_globalDistanceMoved += PointerEvent.transformDeltaViaPositions(
transform: localToGlobalTransform,
untransformedDelta: movedLocally,
untransformedEndPosition: localPosition
).distance * (_getPrimaryValueFromOffset(movedLocally) ?? 1).sign;
if (_hasSufficientGlobalDistanceToAccept(event.kind, gestureSettings?.touchSlop)) {
_hasDragThresholdBeenMet = true;
if (_acceptedActivePointers.contains(event.pointer)) {
_checkDrag(event.pointer);
} else {
resolve(GestureDisposition.accepted);
}
}
case _DragState.accepted:
_checkUpdate(
sourceTimeStamp: event.timeStamp,
delta: _getDeltaForDetails(resolvedDelta),
primaryDelta: _getPrimaryValueFromOffset(resolvedDelta),
globalPosition: position,
localPosition: localPosition,
);
}
_recordMoveDeltaForMultitouch(event.pointer, localDelta);
}
if (event case PointerUpEvent() || PointerCancelEvent() || PointerPanZoomEndEvent()) {
_giveUpPointer(event.pointer);
}
}
final List<int> _acceptedActivePointers = <int>[];
// This value is used when the multitouch strategy is `latestPointer`,
// it keeps track of the last accepted pointer. If this active pointer
// leave up, it will be set to the first accepted pointer.
// Refer to the implementation of Android `RecyclerView`(line 3846):
// https://android.googlesource.com/platform/frameworks/support/+/refs/heads/androidx-master-dev/recyclerview/recyclerview/src/main/java/androidx/recyclerview/widget/RecyclerView.java
int? _activePointer;
@override
void acceptGesture(int pointer) {
assert(!_acceptedActivePointers.contains(pointer));
_acceptedActivePointers.add(pointer);
_activePointer = pointer;
if (!onlyAcceptDragOnThreshold || _hasDragThresholdBeenMet) {
_checkDrag(pointer);
}
}
@override
void rejectGesture(int pointer) {
_giveUpPointer(pointer);
}
@override
void didStopTrackingLastPointer(int pointer) {
assert(_state != _DragState.ready);
switch (_state) {
case _DragState.ready:
break;
case _DragState.possible:
resolve(GestureDisposition.rejected);
_checkCancel();
case _DragState.accepted:
_checkEnd(pointer);
}
_hasDragThresholdBeenMet = false;
_velocityTrackers.clear();
_initialButtons = null;
_state = _DragState.ready;
}
void _giveUpPointer(int pointer) {
stopTrackingPointer(pointer);
// If we never accepted the pointer, we reject it since we are no longer
// interested in winning the gesture arena for it.
if (!_acceptedActivePointers.remove(pointer)) {
resolvePointer(pointer, GestureDisposition.rejected);
}
_moveDeltaBeforeFrame.remove(pointer);
if (_activePointer == pointer) {
_activePointer =
_acceptedActivePointers.isNotEmpty ? _acceptedActivePointers.first : null;
}
}
void _checkDown() {
if (onDown != null) {
final DragDownDetails details = DragDownDetails(
globalPosition: _initialPosition.global,
localPosition: _initialPosition.local,
);
invokeCallback<void>('onDown', () => onDown!(details));
}
}
void _checkDrag(int pointer) {
if (_state == _DragState.accepted) {
return;
}
_state = _DragState.accepted;
final OffsetPair delta = _pendingDragOffset;
final Duration? timestamp = _lastPendingEventTimestamp;
final Matrix4? transform = _lastTransform;
final Offset localUpdateDelta;
switch (dragStartBehavior) {
case DragStartBehavior.start:
_initialPosition = _initialPosition + delta;
localUpdateDelta = Offset.zero;
case DragStartBehavior.down:
localUpdateDelta = _getDeltaForDetails(delta.local);
}
_pendingDragOffset = OffsetPair.zero;
_lastPendingEventTimestamp = null;
_lastTransform = null;
_checkStart(timestamp, pointer);
if (localUpdateDelta != Offset.zero && onUpdate != null) {
final Matrix4? localToGlobal = transform != null ? Matrix4.tryInvert(transform) : null;
final Offset correctedLocalPosition = _initialPosition.local + localUpdateDelta;
final Offset globalUpdateDelta = PointerEvent.transformDeltaViaPositions(
untransformedEndPosition: correctedLocalPosition,
untransformedDelta: localUpdateDelta,
transform: localToGlobal,
);
final OffsetPair updateDelta = OffsetPair(local: localUpdateDelta, global: globalUpdateDelta);
final OffsetPair correctedPosition = _initialPosition + updateDelta; // Only adds delta for down behaviour
_checkUpdate(
sourceTimeStamp: timestamp,
delta: localUpdateDelta,
primaryDelta: _getPrimaryValueFromOffset(localUpdateDelta),
globalPosition: correctedPosition.global,
localPosition: correctedPosition.local,
);
}
// This acceptGesture might have been called only for one pointer, instead
// of all pointers. Resolve all pointers to `accepted`. This won't cause
// infinite recursion because an accepted pointer won't be accepted again.
resolve(GestureDisposition.accepted);
}
void _checkStart(Duration? timestamp, int pointer) {
if (onStart != null) {
final DragStartDetails details = DragStartDetails(
sourceTimeStamp: timestamp,
globalPosition: _initialPosition.global,
localPosition: _initialPosition.local,
kind: getKindForPointer(pointer),
);
invokeCallback<void>('onStart', () => onStart!(details));
}
}
void _checkUpdate({
Duration? sourceTimeStamp,
required Offset delta,
double? primaryDelta,
required Offset globalPosition,
Offset? localPosition,
}) {
if (onUpdate != null) {
final DragUpdateDetails details = DragUpdateDetails(
sourceTimeStamp: sourceTimeStamp,
delta: delta,
primaryDelta: primaryDelta,
globalPosition: globalPosition,
localPosition: localPosition,
);
invokeCallback<void>('onUpdate', () => onUpdate!(details));
}
}
void _checkEnd(int pointer) {
if (onEnd == null) {
return;
}
final VelocityTracker tracker = _velocityTrackers[pointer]!;
final VelocityEstimate? estimate = tracker.getVelocityEstimate();
DragEndDetails? details;
final String Function() debugReport;
if (estimate == null) {
debugReport = () => 'Could not estimate velocity.';
} else {
details = _considerFling(estimate, tracker.kind);
debugReport = (details != null)
? () => '$estimate; fling at ${details!.velocity}.'
: () => '$estimate; judged to not be a fling.';
}
details ??= DragEndDetails(
primaryVelocity: 0.0,
globalPosition: _finalPosition.global,
localPosition: _finalPosition.local,
);
invokeCallback<void>('onEnd', () => onEnd!(details!), debugReport: debugReport);
}
void _checkCancel() {
if (onCancel != null) {
invokeCallback<void>('onCancel', onCancel!);
}
}
@override
void dispose() {
_velocityTrackers.clear();
super.dispose();
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(EnumProperty<DragStartBehavior>('start behavior', dragStartBehavior));
}
}
/// Recognizes movement in the vertical direction.
///
/// Used for vertical scrolling.
///
/// See also:
///
/// * [HorizontalDragGestureRecognizer], for a similar recognizer but for
/// horizontal movement.
/// * [MultiDragGestureRecognizer], for a family of gesture recognizers that
/// track each touch point independently.
class VerticalDragGestureRecognizer extends DragGestureRecognizer {
/// Create a gesture recognizer for interactions in the vertical axis.
///
/// {@macro flutter.gestures.GestureRecognizer.supportedDevices}
VerticalDragGestureRecognizer({
super.debugOwner,
super.supportedDevices,
super.allowedButtonsFilter,
});
@override
bool isFlingGesture(VelocityEstimate estimate, PointerDeviceKind kind) {
final double minVelocity = minFlingVelocity ?? kMinFlingVelocity;
final double minDistance = minFlingDistance ?? computeHitSlop(kind, gestureSettings);
return estimate.pixelsPerSecond.dy.abs() > minVelocity && estimate.offset.dy.abs() > minDistance;
}
@override
DragEndDetails? _considerFling(VelocityEstimate estimate, PointerDeviceKind kind) {
if (!isFlingGesture(estimate, kind)) {
return null;
}
final double maxVelocity = maxFlingVelocity ?? kMaxFlingVelocity;
final double dy = clampDouble(estimate.pixelsPerSecond.dy, -maxVelocity, maxVelocity);
return DragEndDetails(
velocity: Velocity(pixelsPerSecond: Offset(0, dy)),
primaryVelocity: dy,
globalPosition: _finalPosition.global,
localPosition: _finalPosition.local,
);
}
@override
bool _hasSufficientGlobalDistanceToAccept(PointerDeviceKind pointerDeviceKind, double? deviceTouchSlop) {
return _globalDistanceMoved.abs() > computeHitSlop(pointerDeviceKind, gestureSettings);
}
@override
Offset _getDeltaForDetails(Offset delta) => Offset(0.0, delta.dy);
@override
double _getPrimaryValueFromOffset(Offset value) => value.dy;
@override
_DragDirection? _getPrimaryDragAxis() => _DragDirection.vertical;
@override
String get debugDescription => 'vertical drag';
}
/// Recognizes movement in the horizontal direction.
///
/// Used for horizontal scrolling.
///
/// See also:
///
/// * [VerticalDragGestureRecognizer], for a similar recognizer but for
/// vertical movement.
/// * [MultiDragGestureRecognizer], for a family of gesture recognizers that
/// track each touch point independently.
class HorizontalDragGestureRecognizer extends DragGestureRecognizer {
/// Create a gesture recognizer for interactions in the horizontal axis.
///
/// {@macro flutter.gestures.GestureRecognizer.supportedDevices}
HorizontalDragGestureRecognizer({
super.debugOwner,
super.supportedDevices,
super.allowedButtonsFilter,
});
@override
bool isFlingGesture(VelocityEstimate estimate, PointerDeviceKind kind) {
final double minVelocity = minFlingVelocity ?? kMinFlingVelocity;
final double minDistance = minFlingDistance ?? computeHitSlop(kind, gestureSettings);
return estimate.pixelsPerSecond.dx.abs() > minVelocity && estimate.offset.dx.abs() > minDistance;
}
@override
DragEndDetails? _considerFling(VelocityEstimate estimate, PointerDeviceKind kind) {
if (!isFlingGesture(estimate, kind)) {
return null;
}
final double maxVelocity = maxFlingVelocity ?? kMaxFlingVelocity;
final double dx = clampDouble(estimate.pixelsPerSecond.dx, -maxVelocity, maxVelocity);
return DragEndDetails(
velocity: Velocity(pixelsPerSecond: Offset(dx, 0)),
primaryVelocity: dx,
globalPosition: _finalPosition.global,
localPosition: _finalPosition.local,
);
}
@override
bool _hasSufficientGlobalDistanceToAccept(PointerDeviceKind pointerDeviceKind, double? deviceTouchSlop) {
return _globalDistanceMoved.abs() > computeHitSlop(pointerDeviceKind, gestureSettings);
}
@override
Offset _getDeltaForDetails(Offset delta) => Offset(delta.dx, 0.0);
@override
double _getPrimaryValueFromOffset(Offset value) => value.dx;
@override
_DragDirection? _getPrimaryDragAxis() => _DragDirection.horizontal;
@override
String get debugDescription => 'horizontal drag';
}
/// Recognizes movement both horizontally and vertically.
///
/// See also:
///
/// * [ImmediateMultiDragGestureRecognizer], for a similar recognizer that
/// tracks each touch point independently.
/// * [DelayedMultiDragGestureRecognizer], for a similar recognizer that
/// tracks each touch point independently, but that doesn't start until
/// some time has passed.
class PanGestureRecognizer extends DragGestureRecognizer {
/// Create a gesture recognizer for tracking movement on a plane.
PanGestureRecognizer({
super.debugOwner,
super.supportedDevices,
super.allowedButtonsFilter,
});
@override
bool isFlingGesture(VelocityEstimate estimate, PointerDeviceKind kind) {
final double minVelocity = minFlingVelocity ?? kMinFlingVelocity;
final double minDistance = minFlingDistance ?? computeHitSlop(kind, gestureSettings);
return estimate.pixelsPerSecond.distanceSquared > minVelocity * minVelocity
&& estimate.offset.distanceSquared > minDistance * minDistance;
}
@override
DragEndDetails? _considerFling(VelocityEstimate estimate, PointerDeviceKind kind) {
if (!isFlingGesture(estimate, kind)) {
return null;
}
final Velocity velocity = Velocity(pixelsPerSecond: estimate.pixelsPerSecond)
.clampMagnitude(minFlingVelocity ?? kMinFlingVelocity, maxFlingVelocity ?? kMaxFlingVelocity);
return DragEndDetails(
velocity: velocity,
globalPosition: _finalPosition.global,
localPosition: _finalPosition.local,
);
}
@override
bool _hasSufficientGlobalDistanceToAccept(PointerDeviceKind pointerDeviceKind, double? deviceTouchSlop) {
return _globalDistanceMoved.abs() > computePanSlop(pointerDeviceKind, gestureSettings);
}
@override
Offset _getDeltaForDetails(Offset delta) => delta;
@override
double? _getPrimaryValueFromOffset(Offset value) => null;
@override
String get debugDescription => 'pan';
}
enum _DragDirection {
horizontal,
vertical,
}
| flutter/packages/flutter/lib/src/gestures/monodrag.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/gestures/monodrag.dart",
"repo_id": "flutter",
"token_count": 12768
} | 618 |
// 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 'debug.dart';
import 'desktop_text_selection_toolbar.dart';
import 'desktop_text_selection_toolbar_button.dart';
import 'material_localizations.dart';
import 'text_selection_toolbar.dart';
import 'text_selection_toolbar_text_button.dart';
import 'theme.dart';
/// The default context menu for text selection for the current platform.
///
/// {@template flutter.material.AdaptiveTextSelectionToolbar.contextMenuBuilders}
/// Typically, this widget would be passed to `contextMenuBuilder` in a
/// supported parent widget, such as:
///
/// * [EditableText.contextMenuBuilder]
/// * [TextField.contextMenuBuilder]
/// * [CupertinoTextField.contextMenuBuilder]
/// * [SelectionArea.contextMenuBuilder]
/// * [SelectableText.contextMenuBuilder]
/// {@endtemplate}
///
/// See also:
///
/// * [EditableText.getEditableButtonItems], which returns the default
/// [ContextMenuButtonItem]s for [EditableText] on the platform.
/// * [AdaptiveTextSelectionToolbar.getAdaptiveButtons], which builds the button
/// Widgets for the current platform given [ContextMenuButtonItem]s.
/// * [CupertinoAdaptiveTextSelectionToolbar], which does the same thing as this
/// widget but only for Cupertino context menus.
/// * [TextSelectionToolbar], the default toolbar for Android.
/// * [DesktopTextSelectionToolbar], the default toolbar for desktop platforms
/// other than MacOS.
/// * [CupertinoTextSelectionToolbar], the default toolbar for iOS.
/// * [CupertinoDesktopTextSelectionToolbar], the default toolbar for MacOS.
class AdaptiveTextSelectionToolbar extends StatelessWidget {
/// Create an instance of [AdaptiveTextSelectionToolbar] with the
/// given [children].
///
/// See also:
///
/// {@template flutter.material.AdaptiveTextSelectionToolbar.buttonItems}
/// * [AdaptiveTextSelectionToolbar.buttonItems], which takes a list of
/// [ContextMenuButtonItem]s instead of [children] widgets.
/// {@endtemplate}
/// {@template flutter.material.AdaptiveTextSelectionToolbar.editable}
/// * [AdaptiveTextSelectionToolbar.editable], which builds the default
/// children for an editable field.
/// {@endtemplate}
/// {@template flutter.material.AdaptiveTextSelectionToolbar.editableText}
/// * [AdaptiveTextSelectionToolbar.editableText], which builds the default
/// children for an [EditableText].
/// {@endtemplate}
/// {@template flutter.material.AdaptiveTextSelectionToolbar.selectable}
/// * [AdaptiveTextSelectionToolbar.selectable], which builds the default
/// children for content that is selectable but not editable.
/// {@endtemplate}
const AdaptiveTextSelectionToolbar({
super.key,
required this.children,
required this.anchors,
}) : buttonItems = null;
/// Create an instance of [AdaptiveTextSelectionToolbar] whose children will
/// be built from the given [buttonItems].
///
/// See also:
///
/// {@template flutter.material.AdaptiveTextSelectionToolbar.new}
/// * [AdaptiveTextSelectionToolbar.new], which takes the children directly as
/// a list of widgets.
/// {@endtemplate}
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.editable}
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.editableText}
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.selectable}
const AdaptiveTextSelectionToolbar.buttonItems({
super.key,
required this.buttonItems,
required this.anchors,
}) : children = null;
/// Create an instance of [AdaptiveTextSelectionToolbar] with the default
/// children for an editable field.
///
/// If a callback is null, then its corresponding button will not be built.
///
/// See also:
///
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.new}
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.editableText}
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.buttonItems}
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.selectable}
AdaptiveTextSelectionToolbar.editable({
super.key,
required ClipboardStatus clipboardStatus,
required VoidCallback? onCopy,
required VoidCallback? onCut,
required VoidCallback? onPaste,
required VoidCallback? onSelectAll,
required VoidCallback? onLookUp,
required VoidCallback? onSearchWeb,
required VoidCallback? onShare,
required VoidCallback? onLiveTextInput,
required this.anchors,
}) : children = null,
buttonItems = EditableText.getEditableButtonItems(
clipboardStatus: clipboardStatus,
onCopy: onCopy,
onCut: onCut,
onPaste: onPaste,
onSelectAll: onSelectAll,
onLookUp: onLookUp,
onSearchWeb: onSearchWeb,
onShare: onShare,
onLiveTextInput: onLiveTextInput
);
/// Create an instance of [AdaptiveTextSelectionToolbar] with the default
/// children for an [EditableText].
///
/// See also:
///
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.new}
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.editable}
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.buttonItems}
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.selectable}
AdaptiveTextSelectionToolbar.editableText({
super.key,
required EditableTextState editableTextState,
}) : children = null,
buttonItems = editableTextState.contextMenuButtonItems,
anchors = editableTextState.contextMenuAnchors;
/// Create an instance of [AdaptiveTextSelectionToolbar] with the default
/// children for selectable, but not editable, content.
///
/// See also:
///
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.new}
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.buttonItems}
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.editable}
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.editableText}
AdaptiveTextSelectionToolbar.selectable({
super.key,
required VoidCallback onCopy,
required VoidCallback onSelectAll,
required VoidCallback? onShare,
required SelectionGeometry selectionGeometry,
required this.anchors,
}) : children = null,
buttonItems = SelectableRegion.getSelectableButtonItems(
selectionGeometry: selectionGeometry,
onCopy: onCopy,
onSelectAll: onSelectAll,
onShare: onShare,
);
/// Create an instance of [AdaptiveTextSelectionToolbar] with the default
/// children for a [SelectableRegion].
///
/// See also:
///
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.new}
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.buttonItems}
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.editable}
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.editableText}
/// {@macro flutter.material.AdaptiveTextSelectionToolbar.selectable}
AdaptiveTextSelectionToolbar.selectableRegion({
super.key,
required SelectableRegionState selectableRegionState,
}) : children = null,
buttonItems = selectableRegionState.contextMenuButtonItems,
anchors = selectableRegionState.contextMenuAnchors;
/// {@template flutter.material.AdaptiveTextSelectionToolbar.buttonItems}
/// The [ContextMenuButtonItem]s that will be turned into the correct button
/// widgets for the current platform.
/// {@endtemplate}
final List<ContextMenuButtonItem>? buttonItems;
/// The children of the toolbar, typically buttons.
final List<Widget>? children;
/// {@template flutter.material.AdaptiveTextSelectionToolbar.anchors}
/// The location on which to anchor the menu.
/// {@endtemplate}
final TextSelectionToolbarAnchors anchors;
/// Returns the default button label String for the button of the given
/// [ContextMenuButtonType] on any platform.
static String getButtonLabel(BuildContext context, ContextMenuButtonItem buttonItem) {
if (buttonItem.label != null) {
return buttonItem.label!;
}
switch (Theme.of(context).platform) {
case TargetPlatform.iOS:
case TargetPlatform.macOS:
return CupertinoTextSelectionToolbarButton.getButtonLabel(
context,
buttonItem,
);
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
assert(debugCheckHasMaterialLocalizations(context));
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
return switch (buttonItem.type) {
ContextMenuButtonType.cut => localizations.cutButtonLabel,
ContextMenuButtonType.copy => localizations.copyButtonLabel,
ContextMenuButtonType.paste => localizations.pasteButtonLabel,
ContextMenuButtonType.selectAll => localizations.selectAllButtonLabel,
ContextMenuButtonType.delete => localizations.deleteButtonTooltip.toUpperCase(),
ContextMenuButtonType.lookUp => localizations.lookUpButtonLabel,
ContextMenuButtonType.searchWeb => localizations.searchWebButtonLabel,
ContextMenuButtonType.share => localizations.shareButtonLabel,
ContextMenuButtonType.liveTextInput => localizations.scanTextButtonLabel,
ContextMenuButtonType.custom => '',
};
}
}
/// Returns a List of Widgets generated by turning [buttonItems] into the
/// default context menu buttons for the current platform.
///
/// This is useful when building a text selection toolbar with the default
/// button appearance for the given platform, but where the toolbar and/or the
/// button actions and labels may be custom.
///
/// {@tool dartpad}
/// This sample demonstrates how to use `getAdaptiveButtons` to generate
/// default button widgets in a custom toolbar.
///
/// ** See code in examples/api/lib/material/context_menu/editable_text_toolbar_builder.2.dart **
/// {@end-tool}
///
/// See also:
///
/// * [CupertinoAdaptiveTextSelectionToolbar.getAdaptiveButtons], which is the
/// Cupertino equivalent of this class and builds only the Cupertino
/// buttons.
static Iterable<Widget> getAdaptiveButtons(BuildContext context, List<ContextMenuButtonItem> buttonItems) {
switch (Theme.of(context).platform) {
case TargetPlatform.iOS:
return buttonItems.map((ContextMenuButtonItem buttonItem) {
return CupertinoTextSelectionToolbarButton.buttonItem(
buttonItem: buttonItem,
);
});
case TargetPlatform.fuchsia:
case TargetPlatform.android:
final List<Widget> buttons = <Widget>[];
for (int i = 0; i < buttonItems.length; i++) {
final ContextMenuButtonItem buttonItem = buttonItems[i];
buttons.add(TextSelectionToolbarTextButton(
padding: TextSelectionToolbarTextButton.getPadding(i, buttonItems.length),
onPressed: buttonItem.onPressed,
alignment: AlignmentDirectional.centerStart,
child: Text(getButtonLabel(context, buttonItem)),
));
}
return buttons;
case TargetPlatform.linux:
case TargetPlatform.windows:
return buttonItems.map((ContextMenuButtonItem buttonItem) {
return DesktopTextSelectionToolbarButton.text(
context: context,
onPressed: buttonItem.onPressed,
text: getButtonLabel(context, buttonItem),
);
});
case TargetPlatform.macOS:
return buttonItems.map((ContextMenuButtonItem buttonItem) {
return CupertinoDesktopTextSelectionToolbarButton.text(
onPressed: buttonItem.onPressed,
text: getButtonLabel(context, buttonItem),
);
});
}
}
@override
Widget build(BuildContext context) {
// If there aren't any buttons to build, build an empty toolbar.
if ((children != null && children!.isEmpty)
|| (buttonItems != null && buttonItems!.isEmpty)) {
return const SizedBox.shrink();
}
final List<Widget> resultChildren = children != null
? children!
: getAdaptiveButtons(context, buttonItems!).toList();
switch (Theme.of(context).platform) {
case TargetPlatform.iOS:
return CupertinoTextSelectionToolbar(
anchorAbove: anchors.primaryAnchor,
anchorBelow: anchors.secondaryAnchor == null ? anchors.primaryAnchor : anchors.secondaryAnchor!,
children: resultChildren,
);
case TargetPlatform.android:
return TextSelectionToolbar(
anchorAbove: anchors.primaryAnchor,
anchorBelow: anchors.secondaryAnchor == null ? anchors.primaryAnchor : anchors.secondaryAnchor!,
children: resultChildren,
);
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
return DesktopTextSelectionToolbar(
anchor: anchors.primaryAnchor,
children: resultChildren,
);
case TargetPlatform.macOS:
return CupertinoDesktopTextSelectionToolbar(
anchor: anchors.primaryAnchor,
children: resultChildren,
);
}
}
}
| flutter/packages/flutter/lib/src/material/adaptive_text_selection_toolbar.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/adaptive_text_selection_toolbar.dart",
"repo_id": "flutter",
"token_count": 4520
} | 619 |
// 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.
// AUTOGENERATED FILE DO NOT EDIT!
// This file was generated by vitool.
part of material_animated_icons; // ignore: use_string_in_part_of_directives
const _AnimatedIconData _$search_ellipsis = _AnimatedIconData(
Size(96.0, 96.0),
<_PathFrames>[
_PathFrames(
opacities: <double>[
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
],
commands: <_PathCommand>[
_PathMoveTo(
<Offset>[
Offset(56.63275314854877, 53.416307677358),
Offset(56.63275314854877, 53.416307677358),
Offset(56.63275314854877, 53.416307677358),
Offset(56.63275314854877, 53.416307677358),
Offset(56.63275314854877, 53.416307677358),
Offset(56.63275314854877, 53.416307677358),
Offset(56.63275314854877, 53.416307677358),
Offset(56.63275314854877, 53.416307677358),
Offset(56.63275314854877, 53.416307677358),
Offset(56.63275314854877, 53.416307677358),
Offset(57.069606004928445, 53.86609044856987),
Offset(59.09460654800288, 55.971023159415935),
Offset(60.89239811736094, 57.88133187802052),
Offset(62.39435194501161, 59.538230172598404),
Offset(63.48463970399173, 60.8425011369294),
Offset(63.932061433030945, 61.59610215538352),
Offset(63.07663991080549, 61.23370607747795),
Offset(59.89718017699878, 58.88057174806894),
Offset(61.21880612019878, 60.239014522068935),
Offset(61.09896916359878, 60.11473915976894),
Offset(60.97913220709878, 59.99046379736894),
Offset(60.85929525059878, 59.866188435068935),
Offset(60.73945829409878, 59.74191307276894),
Offset(60.61962133759878, 59.61763771046894),
Offset(60.49978438099878, 59.49336234816894),
Offset(60.37994742449878, 59.36908698586894),
Offset(60.26011046799878, 59.24481162346894),
Offset(60.140273511498776, 59.12053626116894),
Offset(60.02043655499878, 58.99626089886894),
Offset(59.90059959839878, 58.871985536568936),
Offset(59.78076264189878, 58.74771017426894),
Offset(59.66092568539878, 58.62343481186894),
Offset(59.54108872889878, 58.499159449568936),
Offset(59.42125177229878, 58.37488408726894),
Offset(59.30141481579878, 58.250608724968934),
Offset(59.18157785929878, 58.12633336266894),
Offset(59.06174090279878, 58.00205800026894),
Offset(58.94190394629878, 57.877782637968934),
Offset(58.822066989698776, 57.75350727566894),
Offset(58.70223003319878, 57.62923191336894),
Offset(58.58239307669878, 57.504956551068936),
Offset(58.46255612019878, 57.38068118876894),
Offset(58.34271916359878, 57.25640582636894),
Offset(58.22288220709878, 57.132130464068936),
Offset(58.10304525059878, 57.00785510176894),
Offset(57.98320829409878, 56.883579739468935),
Offset(57.86337133759878, 56.75930437716894),
Offset(57.74353438099878, 56.63502901476894),
Offset(57.62369742449878, 56.510753652468935),
],
),
_PathCubicTo(
<Offset>[
Offset(60.57565945470678, 48.849785482535665),
Offset(60.57565945470678, 48.849785482535665),
Offset(60.57565945470678, 48.849785482535665),
Offset(60.57565945470678, 48.849785482535665),
Offset(60.57565945470678, 48.849785482535665),
Offset(60.57565945470678, 48.849785482535665),
Offset(60.57565945470678, 48.849785482535665),
Offset(60.57565945470678, 48.849785482535665),
Offset(60.57565945470678, 48.849785482535665),
Offset(60.57565945470678, 48.849785482535665),
Offset(61.01177894139154, 49.30041761427725),
Offset(63.01014446522872, 51.43619797836744),
Offset(64.73600505254888, 53.42981438943695),
Offset(66.10705023046606, 55.238326039262105),
Offset(66.98436034991653, 56.78925950135372),
Offset(67.09064385091588, 57.93795367416795),
Offset(65.63435166794956, 58.2714628487421),
Offset(61.39070529296772, 57.15082849245442),
Offset(62.71233123616772, 58.50927126645442),
Offset(62.592494279567724, 58.38499590415442),
Offset(62.47265732306772, 58.260720541754424),
Offset(62.35282036656772, 58.13644517945442),
Offset(62.232983410067725, 58.01216981715442),
Offset(62.11314645356772, 57.887894454854425),
Offset(61.993309496967726, 57.76361909255442),
Offset(61.87347254046772, 57.639343730254424),
Offset(61.75363558396772, 57.515068367854425),
Offset(61.63379862746772, 57.39079300555442),
Offset(61.513961670967724, 57.266517643254424),
Offset(61.39412471436772, 57.14224228095442),
Offset(61.274287757867725, 57.01796691865442),
Offset(61.15445080136772, 56.893691556254424),
Offset(61.03461384486772, 56.76941619395442),
Offset(60.914776888267724, 56.64514083165442),
Offset(60.79493993176772, 56.52086546935442),
Offset(60.67510297526772, 56.39659010705442),
Offset(60.555266018767725, 56.27231474465442),
Offset(60.43542906226772, 56.14803938235442),
Offset(60.31559210566772, 56.02376402005442),
Offset(60.195755149167724, 55.899488657754425),
Offset(60.07591819266772, 55.77521329545442),
Offset(59.95608123616772, 55.650937933154424),
Offset(59.83624427956772, 55.526662570754425),
Offset(59.71640732306772, 55.40238720845442),
Offset(59.596570366567725, 55.278111846154424),
Offset(59.47673341006772, 55.15383648385442),
Offset(59.35689645356772, 55.02956112155442),
Offset(59.237059496967724, 54.905285759154424),
Offset(59.11722254046772, 54.78101039685442),
],
<Offset>[
Offset(62.94942712071989, 42.915335621700216),
Offset(62.94942712071989, 42.915335621700216),
Offset(62.94942712071989, 42.915335621700216),
Offset(62.94942712071989, 42.915335621700216),
Offset(62.94942712071989, 42.915335621700216),
Offset(62.94942712071989, 42.915335621700216),
Offset(62.94942712071989, 42.915335621700216),
Offset(62.94942712071989, 42.915335621700216),
Offset(62.94942712071989, 42.915335621700216),
Offset(62.94942712071989, 42.915335621700216),
Offset(63.38510509316773, 43.36707154474344),
Offset(65.36743540273916, 45.5429401518535),
Offset(67.04999102004787, 47.644819547939385),
Offset(68.34222460676555, 49.6503611948963),
Offset(69.09131472932955, 51.52184630725002),
Offset(68.99222107132888, 53.18398603334939),
Offset(67.17418370976294, 54.42186283224286),
Offset(62.28985971191208, 54.90293081789554),
Offset(63.61148565511208, 56.261373591895534),
Offset(63.49164869851208, 56.13709822959554),
Offset(63.37181174201208, 56.01282286719554),
Offset(63.251974785512076, 55.88854750489554),
Offset(63.13213782901208, 55.764272142595544),
Offset(63.01230087251208, 55.63999678029555),
Offset(62.89246391591208, 55.515721417995536),
Offset(62.77262695941208, 55.39144605569554),
Offset(62.65279000291208, 55.26717069329554),
Offset(62.532953046412075, 55.14289533099554),
Offset(62.41311608991208, 55.018619968695546),
Offset(62.293279133312076, 54.894344606395535),
Offset(62.17344217681208, 54.77006924409554),
Offset(62.05360522031208, 54.64579388169554),
Offset(61.93376826381208, 54.52151851939554),
Offset(61.81393130721208, 54.397243157095545),
Offset(61.69409435071208, 54.272967794795534),
Offset(61.574257394212076, 54.14869243249554),
Offset(61.45442043771208, 54.02441707009554),
Offset(61.33458348121208, 53.90014170779554),
Offset(61.214746524612075, 53.775866345495544),
Offset(61.09490956811208, 53.65159098319555),
Offset(60.97507261161208, 53.527315620895536),
Offset(60.855235655112075, 53.40304025859554),
Offset(60.73539869851208, 53.27876489619554),
Offset(60.615561742012076, 53.15448953389554),
Offset(60.49572478551208, 53.030214171595546),
Offset(60.37588782901208, 52.905938809295534),
Offset(60.25605087251208, 52.78166344699554),
Offset(60.13621391591208, 52.65738808459554),
Offset(60.01637695941208, 52.53311272229554),
],
<Offset>[
Offset(62.94942712071989, 36.41758712071989),
Offset(62.94942712071989, 36.41758712071989),
Offset(62.94942712071989, 36.41758712071989),
Offset(62.94942712071989, 36.41758712071989),
Offset(62.94942712071989, 36.41758712071989),
Offset(62.94942712071989, 36.41758712071989),
Offset(62.94942712071989, 36.41758712071989),
Offset(62.94942712071989, 36.41758712071989),
Offset(62.94942712071989, 36.41758712071989),
Offset(62.94942712071989, 36.41758712071989),
Offset(63.38510509316773, 36.87053160705772),
Offset(65.36743540273916, 39.09029363766916),
Offset(67.04999102004787, 41.31071235333787),
Offset(68.34222460676555, 43.531986106645554),
Offset(69.09131472932955, 45.754449667519545),
Offset(68.99222107132888, 47.97877125586888),
Offset(67.17418370976294, 50.206858354462945),
Offset(62.28985971191208, 52.44166244631208),
Offset(63.61148565511208, 53.800105220312076),
Offset(63.49164869851208, 53.67582985801208),
Offset(63.37181174201208, 53.55155449561208),
Offset(63.251974785512076, 53.42727913331208),
Offset(63.13213782901208, 53.30300377101208),
Offset(63.01230087251208, 53.17872840871208),
Offset(62.89246391591208, 53.05445304641208),
Offset(62.77262695941208, 52.93017768411208),
Offset(62.65279000291208, 52.80590232171208),
Offset(62.532953046412075, 52.68162695941208),
Offset(62.41311608991208, 52.55735159711208),
Offset(62.293279133312076, 52.43307623481208),
Offset(62.17344217681208, 52.30880087251208),
Offset(62.05360522031208, 52.18452551011208),
Offset(61.93376826381208, 52.06025014781208),
Offset(61.81393130721208, 51.93597478551208),
Offset(61.69409435071208, 51.811699423212076),
Offset(61.574257394212076, 51.68742406091208),
Offset(61.45442043771208, 51.56314869851208),
Offset(61.33458348121208, 51.438873336212076),
Offset(61.214746524612075, 51.31459797391208),
Offset(61.09490956811208, 51.19032261161208),
Offset(60.97507261161208, 51.06604724931208),
Offset(60.855235655112075, 50.94177188701208),
Offset(60.73539869851208, 50.81749652461208),
Offset(60.615561742012076, 50.69322116231208),
Offset(60.49572478551208, 50.56894580001208),
Offset(60.37588782901208, 50.44467043771208),
Offset(60.25605087251208, 50.32039507541208),
Offset(60.13621391591208, 50.19611971301208),
Offset(60.01637695941208, 50.07184435071208),
],
),
_PathCubicTo(
<Offset>[
Offset(62.94942712071989, 21.97373945470677),
Offset(62.94942712071989, 21.97373945470677),
Offset(62.94942712071989, 21.97373945470677),
Offset(62.94942712071989, 21.97373945470677),
Offset(62.94942712071989, 21.97373945470677),
Offset(62.94942712071989, 21.97373945470677),
Offset(62.94942712071989, 21.97373945470677),
Offset(62.94942712071989, 21.97373945470677),
Offset(62.94942712071989, 21.97373945470677),
Offset(62.94942712071989, 21.97373945470677),
Offset(63.38510509316773, 22.429370456861527),
Offset(65.36743540273916, 24.74670319561872),
Offset(67.04999102004787, 27.230623010818878),
Offset(68.34222460676555, 29.931447747106052),
Offset(69.09131472932955, 32.934101437486525),
Offset(68.99222107132888, 36.408097305735886),
Offset(67.17418370976294, 40.83732326404956),
Offset(62.28985971191208, 46.97050802736772),
Offset(63.61148565511208, 48.32895080136772),
Offset(63.49164869851208, 48.20467543906772),
Offset(63.37181174201208, 48.08040007666772),
Offset(63.251974785512076, 47.95612471436772),
Offset(63.13213782901208, 47.83184935206772),
Offset(63.01230087251208, 47.707573989767724),
Offset(62.89246391591208, 47.58329862746772),
Offset(62.77262695941208, 47.45902326516772),
Offset(62.65279000291208, 47.334747902767724),
Offset(62.532953046412075, 47.21047254046772),
Offset(62.41311608991208, 47.08619717816772),
Offset(62.293279133312076, 46.96192181586772),
Offset(62.17344217681208, 46.83764645356772),
Offset(62.05360522031208, 46.71337109116772),
Offset(61.93376826381208, 46.58909572886772),
Offset(61.81393130721208, 46.46482036656772),
Offset(61.69409435071208, 46.34054500426772),
Offset(61.574257394212076, 46.21626964196772),
Offset(61.45442043771208, 46.09199427956772),
Offset(61.33458348121208, 45.96771891726772),
Offset(61.214746524612075, 45.84344355496772),
Offset(61.09490956811208, 45.71916819266772),
Offset(60.97507261161208, 45.59489283036772),
Offset(60.855235655112075, 45.47061746806772),
Offset(60.73539869851208, 45.34634210566772),
Offset(60.615561742012076, 45.22206674336772),
Offset(60.49572478551208, 45.09779138106772),
Offset(60.37588782901208, 44.97351601876772),
Offset(60.25605087251208, 44.84924065646772),
Offset(60.13621391591208, 44.72496529406772),
Offset(60.01637695941208, 44.60068993176772),
],
<Offset>[
Offset(51.241465482535666, 10.265747120719887),
Offset(51.241465482535666, 10.265747120719887),
Offset(51.241465482535666, 10.265747120719887),
Offset(51.241465482535666, 10.265747120719887),
Offset(51.241465482535666, 10.265747120719887),
Offset(51.241465482535666, 10.265747120719887),
Offset(51.241465482535666, 10.265747120719887),
Offset(51.241465482535666, 10.265747120719887),
Offset(51.241465482535666, 10.265747120719887),
Offset(51.241465482535666, 10.265747120719887),
Offset(51.67932110354725, 10.723555777147723),
Offset(53.74074073435744, 13.11997804449917),
Offset(55.636886306106945, 15.817488374127876),
Offset(57.3178365729021, 18.90703080962556),
Offset(58.69933686192372, 22.542096324509547),
Offset(59.61321003018795, 27.02906167480888),
Offset(59.5793821068421, 33.242501749162955),
Offset(57.855025758054424, 42.53566244631208),
Offset(59.17665170125442, 43.89410522031208),
Offset(59.056814744654424, 43.76982985801208),
Offset(58.93697778815442, 43.64555449561208),
Offset(58.81714083165442, 43.52127913331208),
Offset(58.697303875154425, 43.39700377101208),
Offset(58.57746691865442, 43.272728408712084),
Offset(58.457629962054426, 43.14845304641208),
Offset(58.337793005554424, 43.02417768411208),
Offset(58.21795604905442, 42.899902321712084),
Offset(58.09811909255442, 42.77562695941208),
Offset(57.978282136054425, 42.65135159711208),
Offset(57.85844517945442, 42.52707623481208),
Offset(57.738608222954426, 42.40280087251208),
Offset(57.618771266454424, 42.27852551011208),
Offset(57.49893430995442, 42.15425014781208),
Offset(57.379097353354425, 42.02997478551208),
Offset(57.25926039685442, 41.90569942321208),
Offset(57.13942344035442, 41.78142406091208),
Offset(57.019586483854425, 41.65714869851208),
Offset(56.89974952735442, 41.53287333621208),
Offset(56.77991257075442, 41.40859797391208),
Offset(56.660075614254424, 41.28432261161208),
Offset(56.54023865775442, 41.16004724931208),
Offset(56.42040170125442, 41.03577188701208),
Offset(56.30056474465442, 40.91149652461208),
Offset(56.18072778815442, 40.78722116231208),
Offset(56.060890831654426, 40.66294580001208),
Offset(55.941053875154424, 40.53867043771208),
Offset(55.82121691865442, 40.41439507541208),
Offset(55.701379962054425, 40.29011971301208),
Offset(55.58154300555442, 40.16584435071208),
],
<Offset>[
Offset(36.79758712071989, 10.265747120719887),
Offset(36.79758712071989, 10.265747120719887),
Offset(36.79758712071989, 10.265747120719887),
Offset(36.79758712071989, 10.265747120719887),
Offset(36.79758712071989, 10.265747120719887),
Offset(36.79758712071989, 10.265747120719887),
Offset(36.79758712071989, 10.265747120719887),
Offset(36.79758712071989, 10.265747120719887),
Offset(36.79758712071989, 10.265747120719887),
Offset(36.79758712071989, 10.265747120719887),
Offset(37.238129263257726, 10.723555777147723),
Offset(39.39711980956916, 13.11997804449917),
Offset(41.55676704083787, 15.817488374127876),
Offset(43.717269309745554, 18.90703080962556),
Offset(45.878961386319546, 22.542096324509547),
Offset(48.04251149026888, 27.02906167480888),
Offset(50.209827104462946, 33.242501749162955),
Offset(52.38385971191208, 42.53566244631208),
Offset(53.70548565511208, 43.89410522031208),
Offset(53.58564869851208, 43.76982985801208),
Offset(53.46581174201208, 43.64555449561208),
Offset(53.34597478551208, 43.52127913331208),
Offset(53.22613782901208, 43.39700377101208),
Offset(53.10630087251208, 43.272728408712084),
Offset(52.98646391591208, 43.14845304641208),
Offset(52.86662695941208, 43.02417768411208),
Offset(52.74679000291208, 42.899902321712084),
Offset(52.626953046412076, 42.77562695941208),
Offset(52.50711608991208, 42.65135159711208),
Offset(52.38727913331208, 42.52707623481208),
Offset(52.26744217681208, 42.40280087251208),
Offset(52.14760522031208, 42.27852551011208),
Offset(52.02776826381208, 42.15425014781208),
Offset(51.90793130721208, 42.02997478551208),
Offset(51.78809435071208, 41.90569942321208),
Offset(51.66825739421208, 41.78142406091208),
Offset(51.54842043771208, 41.65714869851208),
Offset(51.42858348121208, 41.53287333621208),
Offset(51.308746524612076, 41.40859797391208),
Offset(51.18890956811208, 41.28432261161208),
Offset(51.06907261161208, 41.16004724931208),
Offset(50.949235655112076, 41.03577188701208),
Offset(50.82939869851208, 40.91149652461208),
Offset(50.70956174201208, 40.78722116231208),
Offset(50.58972478551208, 40.66294580001208),
Offset(50.46988782901208, 40.53867043771208),
Offset(50.35005087251208, 40.41439507541208),
Offset(50.23021391591208, 40.29011971301208),
Offset(50.11037695941208, 40.16584435071208),
],
),
_PathCubicTo(
<Offset>[
Offset(22.353739454706773, 10.265747120719887),
Offset(22.353739454706773, 10.265747120719887),
Offset(22.353739454706773, 10.265747120719887),
Offset(22.353739454706773, 10.265747120719887),
Offset(22.353739454706773, 10.265747120719887),
Offset(22.353739454706773, 10.265747120719887),
Offset(22.353739454706773, 10.265747120719887),
Offset(22.353739454706773, 10.265747120719887),
Offset(22.353739454706773, 10.265747120719887),
Offset(22.353739454706773, 10.265747120719887),
Offset(22.79696811306153, 10.723555777147723),
Offset(25.05352936751872, 13.11997804449917),
Offset(27.476677698318877, 15.817488374127876),
Offset(30.11673095020605, 18.90703080962556),
Offset(33.058613156286526, 22.542096324509547),
Offset(36.47183754013589, 27.02906167480888),
Offset(40.84029201404956, 33.242501749162955),
Offset(46.91270529296772, 42.53566244631208),
Offset(48.23433123616772, 43.89410522031208),
Offset(48.11449427956772, 43.76982985801208),
Offset(47.99465732306772, 43.64555449561208),
Offset(47.87482036656772, 43.52127913331208),
Offset(47.75498341006772, 43.39700377101208),
Offset(47.63514645356772, 43.272728408712084),
Offset(47.515309496967724, 43.14845304641208),
Offset(47.39547254046772, 43.02417768411208),
Offset(47.27563558396772, 42.899902321712084),
Offset(47.15579862746772, 42.77562695941208),
Offset(47.03596167096772, 42.65135159711208),
Offset(46.91612471436772, 42.52707623481208),
Offset(46.796287757867724, 42.40280087251208),
Offset(46.67645080136772, 42.27852551011208),
Offset(46.55661384486772, 42.15425014781208),
Offset(46.43677688826772, 42.02997478551208),
Offset(46.31693993176772, 41.90569942321208),
Offset(46.19710297526772, 41.78142406091208),
Offset(46.07726601876772, 41.65714869851208),
Offset(45.95742906226772, 41.53287333621208),
Offset(45.83759210566772, 41.40859797391208),
Offset(45.71775514916772, 41.28432261161208),
Offset(45.59791819266772, 41.16004724931208),
Offset(45.47808123616772, 41.03577188701208),
Offset(45.35824427956772, 40.91149652461208),
Offset(45.23840732306772, 40.78722116231208),
Offset(45.118570366567724, 40.66294580001208),
Offset(44.99873341006772, 40.53867043771208),
Offset(44.87889645356772, 40.41439507541208),
Offset(44.75905949696772, 40.29011971301208),
Offset(44.63922254046772, 40.16584435071208),
],
<Offset>[
Offset(10.64574712071989, 21.973739454706777),
Offset(10.64574712071989, 21.973739454706777),
Offset(10.64574712071989, 21.973739454706777),
Offset(10.64574712071989, 21.973739454706777),
Offset(10.64574712071989, 21.973739454706777),
Offset(10.64574712071989, 21.973739454706777),
Offset(10.64574712071989, 21.973739454706777),
Offset(10.64574712071989, 21.973739454706777),
Offset(10.64574712071989, 21.973739454706777),
Offset(10.64574712071989, 21.973739454706777),
Offset(11.091153433347728, 22.429370456861534),
Offset(13.42680421639917, 24.74670319561873),
Offset(16.063543061627875, 27.230623010818885),
Offset(19.09231401272556, 29.93144774710606),
Offset(22.666608043309548, 32.93410143748653),
Offset(27.09280190920888, 36.40809730573589),
Offset(33.24547049916295, 40.83732326404956),
Offset(42.47785971191208, 46.97050802736772),
Offset(43.79948565511208, 48.32895080136772),
Offset(43.67964869851208, 48.20467543906772),
Offset(43.55981174201208, 48.08040007666772),
Offset(43.43997478551208, 47.95612471436772),
Offset(43.32013782901208, 47.83184935206772),
Offset(43.20030087251208, 47.707573989767724),
Offset(43.080463915912084, 47.58329862746772),
Offset(42.96062695941208, 47.45902326516772),
Offset(42.84079000291208, 47.334747902767724),
Offset(42.72095304641208, 47.21047254046772),
Offset(42.60111608991208, 47.08619717816772),
Offset(42.48127913331208, 46.96192181586772),
Offset(42.36144217681208, 46.83764645356772),
Offset(42.24160522031208, 46.71337109116772),
Offset(42.12176826381208, 46.58909572886772),
Offset(42.00193130721208, 46.46482036656772),
Offset(41.88209435071208, 46.34054500426772),
Offset(41.76225739421208, 46.21626964196772),
Offset(41.64242043771208, 46.09199427956772),
Offset(41.52258348121208, 45.96771891726772),
Offset(41.40274652461208, 45.84344355496772),
Offset(41.28290956811208, 45.71916819266772),
Offset(41.16307261161208, 45.59489283036772),
Offset(41.04323565511208, 45.47061746806772),
Offset(40.92339869851208, 45.34634210566772),
Offset(40.80356174201208, 45.22206674336772),
Offset(40.683724785512084, 45.09779138106772),
Offset(40.56388782901208, 44.97351601876772),
Offset(40.44405087251208, 44.84924065646772),
Offset(40.32421391591208, 44.72496529406772),
Offset(40.20437695941208, 44.60068993176772),
],
<Offset>[
Offset(10.64574712071989, 36.41758712071989),
Offset(10.64574712071989, 36.41758712071989),
Offset(10.64574712071989, 36.41758712071989),
Offset(10.64574712071989, 36.41758712071989),
Offset(10.64574712071989, 36.41758712071989),
Offset(10.64574712071989, 36.41758712071989),
Offset(10.64574712071989, 36.41758712071989),
Offset(10.64574712071989, 36.41758712071989),
Offset(10.64574712071989, 36.41758712071989),
Offset(10.64574712071989, 36.41758712071989),
Offset(11.091153433347728, 36.87053160705773),
Offset(13.42680421639917, 39.09029363766917),
Offset(16.063543061627875, 41.31071235333788),
Offset(19.09231401272556, 43.53198610664556),
Offset(22.666608043309548, 45.75444966751955),
Offset(27.09280190920888, 47.97877125586888),
Offset(33.24547049916295, 50.20685835446295),
Offset(42.47785971191208, 52.44166244631208),
Offset(43.79948565511208, 53.800105220312076),
Offset(43.67964869851208, 53.67582985801208),
Offset(43.55981174201208, 53.55155449561208),
Offset(43.43997478551208, 53.42727913331208),
Offset(43.32013782901208, 53.30300377101208),
Offset(43.20030087251208, 53.17872840871208),
Offset(43.080463915912084, 53.05445304641208),
Offset(42.96062695941208, 52.93017768411208),
Offset(42.84079000291208, 52.80590232171208),
Offset(42.72095304641208, 52.68162695941208),
Offset(42.60111608991208, 52.55735159711208),
Offset(42.48127913331208, 52.43307623481208),
Offset(42.36144217681208, 52.30880087251208),
Offset(42.24160522031208, 52.18452551011208),
Offset(42.12176826381208, 52.06025014781208),
Offset(42.00193130721208, 51.93597478551208),
Offset(41.88209435071208, 51.811699423212076),
Offset(41.76225739421208, 51.68742406091208),
Offset(41.64242043771208, 51.56314869851208),
Offset(41.52258348121208, 51.438873336212076),
Offset(41.40274652461208, 51.31459797391208),
Offset(41.28290956811208, 51.19032261161208),
Offset(41.16307261161208, 51.06604724931208),
Offset(41.04323565511208, 50.94177188701208),
Offset(40.92339869851208, 50.81749652461208),
Offset(40.80356174201208, 50.69322116231208),
Offset(40.683724785512084, 50.56894580001208),
Offset(40.56388782901208, 50.44467043771208),
Offset(40.44405087251208, 50.32039507541208),
Offset(40.32421391591208, 50.19611971301208),
Offset(40.20437695941208, 50.07184435071208),
],
),
_PathCubicTo(
<Offset>[
Offset(10.64574712071989, 50.861465482535664),
Offset(10.64574712071989, 50.861465482535664),
Offset(10.64574712071989, 50.861465482535664),
Offset(10.64574712071989, 50.861465482535664),
Offset(10.64574712071989, 50.861465482535664),
Offset(10.64574712071989, 50.861465482535664),
Offset(10.64574712071989, 50.861465482535664),
Offset(10.64574712071989, 50.861465482535664),
Offset(10.64574712071989, 50.861465482535664),
Offset(10.64574712071989, 50.861465482535664),
Offset(11.091153433347728, 51.311723447347255),
Offset(13.42680421639917, 53.433914562457446),
Offset(16.063543061627875, 55.39083161860695),
Offset(19.09231401272556, 57.13255336980211),
Offset(22.666608043309548, 58.574825143123725),
Offset(27.09280190920888, 59.54946979578796),
Offset(33.24547049916295, 59.5764133568421),
Offset(42.47785971191208, 57.91282849245442),
Offset(43.79948565511208, 59.27127126645442),
Offset(43.67964869851208, 59.14699590415442),
Offset(43.55981174201208, 59.022720541754424),
Offset(43.43997478551208, 58.89844517945442),
Offset(43.32013782901208, 58.77416981715442),
Offset(43.20030087251208, 58.649894454854426),
Offset(43.080463915912084, 58.52561909255442),
Offset(42.96062695941208, 58.401343730254425),
Offset(42.84079000291208, 58.277068367854426),
Offset(42.72095304641208, 58.15279300555442),
Offset(42.60111608991208, 58.028517643254425),
Offset(42.48127913331208, 57.90424228095442),
Offset(42.36144217681208, 57.779966918654424),
Offset(42.24160522031208, 57.655691556254425),
Offset(42.12176826381208, 57.53141619395442),
Offset(42.00193130721208, 57.407140831654424),
Offset(41.88209435071208, 57.28286546935442),
Offset(41.76225739421208, 57.15859010705442),
Offset(41.64242043771208, 57.034314744654424),
Offset(41.52258348121208, 56.91003938235442),
Offset(41.40274652461208, 56.78576402005442),
Offset(41.28290956811208, 56.661488657754425),
Offset(41.16307261161208, 56.53721329545442),
Offset(41.04323565511208, 56.412937933154424),
Offset(40.92339869851208, 56.288662570754425),
Offset(40.80356174201208, 56.16438720845442),
Offset(40.683724785512084, 56.040111846154424),
Offset(40.56388782901208, 55.91583648385442),
Offset(40.44405087251208, 55.79156112155442),
Offset(40.32421391591208, 55.667285759154424),
Offset(40.20437695941208, 55.54301039685442),
],
<Offset>[
Offset(22.35373945470678, 62.569427120719894),
Offset(22.35373945470678, 62.569427120719894),
Offset(22.35373945470678, 62.569427120719894),
Offset(22.35373945470678, 62.569427120719894),
Offset(22.35373945470678, 62.569427120719894),
Offset(22.35373945470678, 62.569427120719894),
Offset(22.35373945470678, 62.569427120719894),
Offset(22.35373945470678, 62.569427120719894),
Offset(22.35373945470678, 62.569427120719894),
Offset(22.35373945470678, 62.569427120719894),
Offset(22.79696811306154, 63.01750743696773),
Offset(25.053529367518728, 65.06060923083916),
Offset(27.476677698318884, 66.80393633254788),
Offset(30.11673095020606, 68.15694140366556),
Offset(33.05861315628653, 68.96680301052955),
Offset(36.471837540135894, 68.92848083692888),
Offset(40.84029201404956, 67.17121495976295),
Offset(46.91270529296772, 62.347662446312086),
Offset(48.23433123616772, 63.70610522031208),
Offset(48.11449427956772, 63.581829858012085),
Offset(47.99465732306772, 63.45755449561209),
Offset(47.87482036656772, 63.33327913331208),
Offset(47.75498341006772, 63.209003771012085),
Offset(47.63514645356772, 63.08472840871209),
Offset(47.515309496967724, 62.960453046412084),
Offset(47.39547254046772, 62.83617768411209),
Offset(47.27563558396772, 62.71190232171209),
Offset(47.15579862746772, 62.587626959412084),
Offset(47.03596167096772, 62.46335159711209),
Offset(46.91612471436772, 62.33907623481208),
Offset(46.796287757867724, 62.214800872512086),
Offset(46.67645080136772, 62.09052551011209),
Offset(46.55661384486772, 61.96625014781208),
Offset(46.43677688826772, 61.841974785512086),
Offset(46.31693993176772, 61.71769942321208),
Offset(46.19710297526772, 61.593424060912085),
Offset(46.07726601876772, 61.469148698512086),
Offset(45.95742906226772, 61.34487333621208),
Offset(45.83759210566772, 61.220597973912085),
Offset(45.71775514916772, 61.09632261161209),
Offset(45.59791819266772, 60.972047249312084),
Offset(45.47808123616772, 60.84777188701209),
Offset(45.35824427956772, 60.72349652461209),
Offset(45.23840732306772, 60.599221162312084),
Offset(45.118570366567724, 60.47494580001209),
Offset(44.99873341006772, 60.35067043771208),
Offset(44.87889645356772, 60.226395075412086),
Offset(44.75905949696772, 60.10211971301209),
Offset(44.63922254046772, 59.97784435071208),
],
<Offset>[
Offset(36.79758712071989, 62.569427120719894),
Offset(36.79758712071989, 62.569427120719894),
Offset(36.79758712071989, 62.569427120719894),
Offset(36.79758712071989, 62.569427120719894),
Offset(36.79758712071989, 62.569427120719894),
Offset(36.79758712071989, 62.569427120719894),
Offset(36.79758712071989, 62.569427120719894),
Offset(36.79758712071989, 62.569427120719894),
Offset(36.79758712071989, 62.569427120719894),
Offset(36.79758712071989, 62.569427120719894),
Offset(37.23812926325773, 63.01750743696773),
Offset(39.39711980956917, 65.06060923083916),
Offset(41.556767040837876, 66.80393633254788),
Offset(43.71726930974556, 68.15694140366556),
Offset(45.878961386319546, 68.96680301052955),
Offset(48.04251149026888, 68.92848083692888),
Offset(50.20982710446295, 67.17121495976295),
Offset(52.38385971191208, 62.347662446312086),
Offset(53.70548565511208, 63.70610522031208),
Offset(53.58564869851208, 63.581829858012085),
Offset(53.46581174201208, 63.45755449561209),
Offset(53.34597478551208, 63.33327913331208),
Offset(53.22613782901208, 63.209003771012085),
Offset(53.10630087251208, 63.08472840871209),
Offset(52.98646391591208, 62.960453046412084),
Offset(52.86662695941208, 62.83617768411209),
Offset(52.74679000291208, 62.71190232171209),
Offset(52.626953046412076, 62.587626959412084),
Offset(52.50711608991208, 62.46335159711209),
Offset(52.38727913331208, 62.33907623481208),
Offset(52.26744217681208, 62.214800872512086),
Offset(52.14760522031208, 62.09052551011209),
Offset(52.02776826381208, 61.96625014781208),
Offset(51.90793130721208, 61.841974785512086),
Offset(51.78809435071208, 61.71769942321208),
Offset(51.66825739421208, 61.593424060912085),
Offset(51.54842043771208, 61.469148698512086),
Offset(51.42858348121208, 61.34487333621208),
Offset(51.308746524612076, 61.220597973912085),
Offset(51.18890956811208, 61.09632261161209),
Offset(51.06907261161208, 60.972047249312084),
Offset(50.949235655112076, 60.84777188701209),
Offset(50.82939869851208, 60.72349652461209),
Offset(50.70956174201208, 60.599221162312084),
Offset(50.58972478551208, 60.47494580001209),
Offset(50.46988782901208, 60.35067043771208),
Offset(50.35005087251208, 60.226395075412086),
Offset(50.23021391591208, 60.10211971301209),
Offset(50.11037695941208, 59.97784435071208),
],
),
_PathCubicTo(
<Offset>[
Offset(43.295335621700225, 62.569427120719894),
Offset(43.295335621700225, 62.569427120719894),
Offset(43.295335621700225, 62.569427120719894),
Offset(43.295335621700225, 62.569427120719894),
Offset(43.295335621700225, 62.569427120719894),
Offset(43.295335621700225, 62.569427120719894),
Offset(43.295335621700225, 62.569427120719894),
Offset(43.295335621700225, 62.569427120719894),
Offset(43.295335621700225, 62.569427120719894),
Offset(43.295335621700225, 62.569427120719894),
Offset(43.73466920094344, 63.01750743696773),
Offset(45.84976632375351, 65.06060923083916),
Offset(47.89087423543939, 66.80393633254788),
Offset(49.835644397996305, 68.15694140366556),
Offset(51.646358026050024, 68.96680301052955),
Offset(53.24772626774939, 68.92848083692888),
Offset(54.42483158224287, 67.17121495976295),
Offset(54.845128083495545, 62.347662446312086),
Offset(56.16675402669554, 63.70610522031208),
Offset(56.046917070095546, 63.581829858012085),
Offset(55.927080113595544, 63.45755449561209),
Offset(55.80724315709554, 63.33327913331208),
Offset(55.68740620059555, 63.209003771012085),
Offset(55.567569244095544, 63.08472840871209),
Offset(55.44773228749555, 62.960453046412084),
Offset(55.327895330995545, 62.83617768411209),
Offset(55.20805837449554, 62.71190232171209),
Offset(55.08822141799554, 62.587626959412084),
Offset(54.968384461495546, 62.46335159711209),
Offset(54.84854750489554, 62.33907623481208),
Offset(54.72871054839555, 62.214800872512086),
Offset(54.608873591895545, 62.09052551011209),
Offset(54.48903663539554, 61.96625014781208),
Offset(54.369199678795546, 61.841974785512086),
Offset(54.249362722295544, 61.71769942321208),
Offset(54.12952576579554, 61.593424060912085),
Offset(54.00968880929555, 61.469148698512086),
Offset(53.889851852795545, 61.34487333621208),
Offset(53.77001489619554, 61.220597973912085),
Offset(53.650177939695546, 61.09632261161209),
Offset(53.53034098319554, 60.972047249312084),
Offset(53.41050402669554, 60.84777188701209),
Offset(53.290667070095544, 60.72349652461209),
Offset(53.17083011359554, 60.599221162312084),
Offset(53.05099315709555, 60.47494580001209),
Offset(52.931156200595545, 60.35067043771208),
Offset(52.81131924409554, 60.226395075412086),
Offset(52.691482287495546, 60.10211971301209),
Offset(52.571645330995544, 59.97784435071208),
],
<Offset>[
Offset(49.22978548253567, 60.19565945470678),
Offset(49.22978548253567, 60.19565945470678),
Offset(49.22978548253567, 60.19565945470678),
Offset(49.22978548253567, 60.19565945470678),
Offset(49.22978548253567, 60.19565945470678),
Offset(49.22978548253567, 60.19565945470678),
Offset(49.22978548253567, 60.19565945470678),
Offset(49.22978548253567, 60.19565945470678),
Offset(49.22978548253567, 60.19565945470678),
Offset(49.22978548253567, 60.19565945470678),
Offset(49.668015270477255, 60.644181285191536),
Offset(51.743024150267445, 62.70331829332873),
Offset(53.67586907693695, 64.48995036504888),
Offset(55.423609242362105, 65.92176702736606),
Offset(56.91377122015372, 66.85984863111653),
Offset(58.00169390856796, 67.0269036165159),
Offset(58.274431598742105, 65.63138291794957),
Offset(57.093025758054424, 61.44850802736772),
Offset(58.41465170125442, 62.80695080136772),
Offset(58.294814744654424, 62.68267543906772),
Offset(58.17497778815442, 62.55840007666772),
Offset(58.05514083165442, 62.43412471436772),
Offset(57.935303875154425, 62.30984935206772),
Offset(57.81546691865442, 62.185573989767725),
Offset(57.695629962054426, 62.06129862746772),
Offset(57.575793005554424, 61.937023265167724),
Offset(57.45595604905442, 61.812747902767725),
Offset(57.33611909255442, 61.68847254046772),
Offset(57.216282136054424, 61.564197178167724),
Offset(57.09644517945442, 61.43992181586772),
Offset(56.976608222954425, 61.31564645356772),
Offset(56.85677126645442, 61.191371091167724),
Offset(56.73693430995442, 61.06709572886772),
Offset(56.617097353354424, 60.94282036656772),
Offset(56.49726039685442, 60.81854500426772),
Offset(56.37742344035442, 60.69426964196772),
Offset(56.257586483854425, 60.56999427956772),
Offset(56.13774952735442, 60.44571891726772),
Offset(56.01791257075442, 60.32144355496772),
Offset(55.898075614254424, 60.197168192667725),
Offset(55.77823865775442, 60.07289283036772),
Offset(55.65840170125442, 59.948617468067724),
Offset(55.53856474465442, 59.824342105667725),
Offset(55.41872778815442, 59.70006674336772),
Offset(55.298890831654425, 59.575791381067724),
Offset(55.17905387515442, 59.45151601876772),
Offset(55.05921691865442, 59.32724065646772),
Offset(54.939379962054424, 59.202965294067724),
Offset(54.81954300555442, 59.07868993176772),
],
<Offset>[
Offset(53.796307677358, 56.272889593871334),
Offset(53.796307677358, 56.272889593871334),
Offset(53.796307677358, 56.272889593871334),
Offset(53.796307677358, 56.272889593871334),
Offset(53.796307677358, 56.272889593871334),
Offset(53.796307677358, 56.272889593871334),
Offset(53.796307677358, 56.272889593871334),
Offset(53.796307677358, 56.272889593871334),
Offset(53.796307677358, 56.272889593871334),
Offset(53.796307677358, 56.272889593871334),
Offset(54.233688104769875, 56.72214104872773),
Offset(56.27784933131594, 58.80777705090479),
Offset(58.127386565520524, 60.66597275272132),
Offset(59.7235133756984, 62.22802951354025),
Offset(60.96701285572941, 63.37800107878284),
Offset(61.65984238978352, 63.88445209731733),
Offset(61.23667482747795, 63.08673340955032),
Offset(58.822769013668946, 59.962610352808845),
Offset(60.14439495686894, 61.32105312680884),
Offset(60.02455800026895, 61.196777764508845),
Offset(59.904721043768944, 61.072502402108846),
Offset(59.78488408726894, 60.94822703980884),
Offset(59.66504713076895, 60.823951677508845),
Offset(59.545210174268945, 60.69967631520885),
Offset(59.42537321766895, 60.57540095290884),
Offset(59.305536261168946, 60.45112559060885),
Offset(59.185699304668944, 60.32685022820885),
Offset(59.06586234816894, 60.20257486590884),
Offset(58.94602539166895, 60.07829950360885),
Offset(58.82618843506894, 59.95402414130884),
Offset(58.70635147856895, 59.829748779008845),
Offset(58.586514522068946, 59.70547341660885),
Offset(58.46667756556894, 59.58119805430884),
Offset(58.34684060896895, 59.456922692008845),
Offset(58.227003652468944, 59.33264732970884),
Offset(58.10716669596894, 59.208371967408844),
Offset(57.98732973946895, 59.084096605008845),
Offset(57.867492782968945, 58.95982124270884),
Offset(57.74765582636894, 58.835545880408844),
Offset(57.627818869868946, 58.71127051810885),
Offset(57.507981913368944, 58.58699515580884),
Offset(57.38814495686894, 58.462719793508846),
Offset(57.268308000268945, 58.33844443110885),
Offset(57.14847104376894, 58.21416906880884),
Offset(57.02863408726895, 58.089893706508846),
Offset(56.908797130768946, 57.96561834420884),
Offset(56.788960174268944, 57.841342981908845),
Offset(56.66912321766895, 57.717067619508846),
Offset(56.549286261168945, 57.59279225720884),
],
),
_PathCubicTo(
<Offset>[
Offset(53.796307677358, 56.272889593871334),
Offset(53.796307677358, 56.272889593871334),
Offset(53.796307677358, 56.272889593871334),
Offset(53.796307677358, 56.272889593871334),
Offset(53.796307677358, 56.272889593871334),
Offset(53.796307677358, 56.272889593871334),
Offset(53.796307677358, 56.272889593871334),
Offset(53.796307677358, 56.272889593871334),
Offset(53.796307677358, 56.272889593871334),
Offset(53.796307677358, 56.272889593871334),
Offset(54.233688104769875, 56.72214104872773),
Offset(56.27784933131594, 58.80777705090479),
Offset(58.127386565520524, 60.66597275272132),
Offset(59.7235133756984, 62.22802951354025),
Offset(60.96701285572941, 63.37800107878284),
Offset(61.65984238978352, 63.88445209731733),
Offset(61.23667482747795, 63.08673340955032),
Offset(58.822769013668946, 59.962610352808845),
Offset(60.14439495686894, 61.32105312680884),
Offset(60.02455800026895, 61.196777764508845),
Offset(59.904721043768944, 61.072502402108846),
Offset(59.78488408726894, 60.94822703980884),
Offset(59.66504713076895, 60.823951677508845),
Offset(59.545210174268945, 60.69967631520885),
Offset(59.42537321766895, 60.57540095290884),
Offset(59.305536261168946, 60.45112559060885),
Offset(59.185699304668944, 60.32685022820885),
Offset(59.06586234816894, 60.20257486590884),
Offset(58.94602539166895, 60.07829950360885),
Offset(58.82618843506894, 59.95402414130884),
Offset(58.70635147856895, 59.829748779008845),
Offset(58.586514522068946, 59.70547341660885),
Offset(58.46667756556894, 59.58119805430884),
Offset(58.34684060896895, 59.456922692008845),
Offset(58.227003652468944, 59.33264732970884),
Offset(58.10716669596894, 59.208371967408844),
Offset(57.98732973946895, 59.084096605008845),
Offset(57.867492782968945, 58.95982124270884),
Offset(57.74765582636894, 58.835545880408844),
Offset(57.627818869868946, 58.71127051810885),
Offset(57.507981913368944, 58.58699515580884),
Offset(57.38814495686894, 58.462719793508846),
Offset(57.268308000268945, 58.33844443110885),
Offset(57.14847104376894, 58.21416906880884),
Offset(57.02863408726895, 58.089893706508846),
Offset(56.908797130768946, 57.96561834420884),
Offset(56.788960174268944, 57.841342981908845),
Offset(56.66912321766895, 57.717067619508846),
Offset(56.549286261168945, 57.59279225720884),
],
<Offset>[
Offset(56.63275314854878, 53.416307677358),
Offset(56.63275314854878, 53.416307677358),
Offset(56.63275314854878, 53.416307677358),
Offset(56.63275314854878, 53.416307677358),
Offset(56.63275314854878, 53.416307677358),
Offset(56.63275314854878, 53.416307677358),
Offset(56.63275314854878, 53.416307677358),
Offset(56.63275314854878, 53.416307677358),
Offset(56.63275314854878, 53.416307677358),
Offset(56.63275314854878, 53.416307677358),
Offset(57.069606004928445, 53.86609044856987),
Offset(59.094606548002886, 55.97102315941594),
Offset(60.89239811736094, 57.881331878020525),
Offset(62.39435194501161, 59.538230172598404),
Offset(63.48463970399174, 60.8425011369294),
Offset(63.932061433030945, 61.59610215538352),
Offset(63.07663991080549, 61.23370607747795),
Offset(59.89718017699878, 58.880571748068945),
Offset(61.21880612019878, 60.23901452206894),
Offset(61.09896916359878, 60.114739159768945),
Offset(60.97913220709878, 59.990463797368946),
Offset(60.85929525059878, 59.86618843506894),
Offset(60.73945829409878, 59.741913072768945),
Offset(60.61962133759878, 59.61763771046895),
Offset(60.49978438099878, 59.493362348168944),
Offset(60.37994742449878, 59.36908698586895),
Offset(60.26011046799878, 59.24481162346895),
Offset(60.140273511498776, 59.120536261168944),
Offset(60.02043655499878, 58.99626089886895),
Offset(59.90059959839878, 58.87198553656894),
Offset(59.78076264189878, 58.747710174268946),
Offset(59.66092568539878, 58.62343481186895),
Offset(59.54108872889878, 58.49915944956894),
Offset(59.42125177229878, 58.374884087268946),
Offset(59.30141481579878, 58.25060872496894),
Offset(59.18157785929878, 58.126333362668944),
Offset(59.06174090279878, 58.002058000268946),
Offset(58.94190394629878, 57.87778263796894),
Offset(58.822066989698776, 57.753507275668944),
Offset(58.70223003319878, 57.62923191336895),
Offset(58.58239307669878, 57.50495655106894),
Offset(58.46255612019878, 57.380681188768946),
Offset(58.34271916359878, 57.25640582636895),
Offset(58.22288220709878, 57.13213046406894),
Offset(58.10304525059878, 57.007855101768946),
Offset(57.98320829409878, 56.88357973946894),
Offset(57.86337133759878, 56.759304377168945),
Offset(57.74353438099878, 56.635029014768946),
Offset(57.62369742449878, 56.51075365246894),
],
<Offset>[
Offset(56.63275314854878, 53.416307677358),
Offset(56.63275314854878, 53.416307677358),
Offset(56.63275314854878, 53.416307677358),
Offset(56.63275314854878, 53.416307677358),
Offset(56.63275314854878, 53.416307677358),
Offset(56.63275314854878, 53.416307677358),
Offset(56.63275314854878, 53.416307677358),
Offset(56.63275314854878, 53.416307677358),
Offset(56.63275314854878, 53.416307677358),
Offset(56.63275314854878, 53.416307677358),
Offset(57.069606004928445, 53.86609044856987),
Offset(59.094606548002886, 55.97102315941594),
Offset(60.89239811736094, 57.881331878020525),
Offset(62.39435194501161, 59.538230172598404),
Offset(63.48463970399174, 60.8425011369294),
Offset(63.932061433030945, 61.59610215538352),
Offset(63.07663991080549, 61.23370607747795),
Offset(59.89718017699878, 58.880571748068945),
Offset(61.21880612019878, 60.23901452206894),
Offset(61.09896916359878, 60.114739159768945),
Offset(60.97913220709878, 59.990463797368946),
Offset(60.85929525059878, 59.86618843506894),
Offset(60.73945829409878, 59.741913072768945),
Offset(60.61962133759878, 59.61763771046895),
Offset(60.49978438099878, 59.493362348168944),
Offset(60.37994742449878, 59.36908698586895),
Offset(60.26011046799878, 59.24481162346895),
Offset(60.140273511498776, 59.120536261168944),
Offset(60.02043655499878, 58.99626089886895),
Offset(59.90059959839878, 58.87198553656894),
Offset(59.78076264189878, 58.747710174268946),
Offset(59.66092568539878, 58.62343481186895),
Offset(59.54108872889878, 58.49915944956894),
Offset(59.42125177229878, 58.374884087268946),
Offset(59.30141481579878, 58.25060872496894),
Offset(59.18157785929878, 58.126333362668944),
Offset(59.06174090279878, 58.002058000268946),
Offset(58.94190394629878, 57.87778263796894),
Offset(58.822066989698776, 57.753507275668944),
Offset(58.70223003319878, 57.62923191336895),
Offset(58.58239307669878, 57.50495655106894),
Offset(58.46255612019878, 57.380681188768946),
Offset(58.34271916359878, 57.25640582636895),
Offset(58.22288220709878, 57.13213046406894),
Offset(58.10304525059878, 57.007855101768946),
Offset(57.98320829409878, 56.88357973946894),
Offset(57.86337133759878, 56.759304377168945),
Offset(57.74353438099878, 56.635029014768946),
Offset(57.62369742449878, 56.51075365246894),
],
),
_PathClose(
),
_PathMoveTo(
<Offset>[
Offset(36.79758712071989, 54.522707120719886),
Offset(36.79758712071989, 54.522707120719886),
Offset(36.79758712071989, 54.522707120719886),
Offset(36.79758712071989, 54.522707120719886),
Offset(36.79758712071989, 54.522707120719886),
Offset(36.79758712071989, 54.522707120719886),
Offset(36.79758712071989, 54.522707120719886),
Offset(36.79758712071989, 54.522707120719886),
Offset(36.79758712071989, 54.522707120719886),
Offset(36.79758712071989, 54.522707120719886),
Offset(37.238129263257726, 54.34772049679427),
Offset(39.39711980956916, 53.40971455122347),
Offset(41.55676704083787, 52.38323260637452),
Offset(43.717269309745554, 51.34517214659979),
Offset(45.878961386319546, 50.4025549847652),
Offset(48.04251149026888, 49.72174872023579),
Offset(50.209827104462946, 50.28103042236462),
Offset(52.38385971191208, 52.48497375612058),
Offset(53.70548565511208, 53.84341653012058),
Offset(53.58564869851208, 53.71914116782058),
Offset(53.46581174201208, 53.59486580542058),
Offset(53.34597478551208, 53.47059044312058),
Offset(53.22613782901208, 53.34631508082058),
Offset(53.10630087251208, 53.222039718520584),
Offset(52.98646391591208, 53.09776435622058),
Offset(52.86662695941208, 52.97348899392058),
Offset(52.74679000291208, 52.849213631520584),
Offset(52.626953046412076, 52.72493826922058),
Offset(52.50711608991208, 52.60066290692058),
Offset(52.38727913331208, 52.47638754462058),
Offset(52.26744217681208, 52.35211218232058),
Offset(52.14760522031208, 52.22783681992058),
Offset(52.02776826381208, 52.10356145762058),
Offset(51.90793130721208, 51.97928609532058),
Offset(51.78809435071208, 51.85501073302058),
Offset(51.66825739421208, 51.73073537072058),
Offset(51.54842043771208, 51.60646000832058),
Offset(51.42858348121208, 51.48218464602058),
Offset(51.308746524612076, 51.35790928372058),
Offset(51.18890956811208, 51.233633921420584),
Offset(51.06907261161208, 51.10935855912058),
Offset(50.949235655112076, 50.98508319682058),
Offset(50.82939869851208, 50.860807834420584),
Offset(50.70956174201208, 50.73653247212058),
Offset(50.58972478551208, 50.61225710982058),
Offset(50.46988782901208, 50.48798174752058),
Offset(50.35005087251208, 50.36370638522058),
Offset(50.23021391591208, 50.23943102282058),
Offset(50.11037695941208, 50.11515566052058),
],
),
_PathCubicTo(
<Offset>[
Offset(26.79953506506211, 54.522707120719886),
Offset(26.79953506506211, 54.522707120719886),
Offset(26.79953506506211, 54.522707120719886),
Offset(26.79953506506211, 54.522707120719886),
Offset(26.79953506506211, 54.522707120719886),
Offset(26.79953506506211, 54.522707120719886),
Offset(26.79953506506211, 54.522707120719886),
Offset(26.79953506506211, 54.522707120719886),
Offset(26.79953506506211, 54.522707120719886),
Offset(26.79953506506211, 54.522707120719886),
Offset(27.586834836005405, 54.34772049679427),
Offset(31.489615606172315, 53.40971455122347),
Offset(35.442274116666454, 52.38323260637452),
Offset(39.402653738040314, 51.34517214659979),
Offset(43.31217425963652, 50.4025549847652),
Offset(47.08000098098459, 49.72174872023579),
Offset(50.16886819340391, 50.28103042236462),
Offset(52.35994256713666, 52.48497375612058),
Offset(53.68156851033666, 53.84341653012058),
Offset(53.561731553736664, 53.71914116782058),
Offset(53.44189459723666, 53.59486580542058),
Offset(53.32205764073666, 53.47059044312058),
Offset(53.202220684236664, 53.34631508082058),
Offset(53.08238372773666, 53.222039718520584),
Offset(52.962546771136665, 53.09776435622058),
Offset(52.84270981463666, 52.97348899392058),
Offset(52.72287285813666, 52.849213631520584),
Offset(52.60303590163666, 52.72493826922058),
Offset(52.483198945136664, 52.60066290692058),
Offset(52.36336198853666, 52.47638754462058),
Offset(52.243525032036665, 52.35211218232058),
Offset(52.12368807553666, 52.22783681992058),
Offset(52.00385111903666, 52.10356145762058),
Offset(51.884014162436664, 51.97928609532058),
Offset(51.76417720593666, 51.85501073302058),
Offset(51.64434024943666, 51.73073537072058),
Offset(51.524503292936664, 51.60646000832058),
Offset(51.40466633643666, 51.48218464602058),
Offset(51.28482937983666, 51.35790928372058),
Offset(51.16499242333666, 51.233633921420584),
Offset(51.04515546683666, 51.10935855912058),
Offset(50.92531851033666, 50.98508319682058),
Offset(50.80548155373666, 50.860807834420584),
Offset(50.68564459723666, 50.73653247212058),
Offset(50.565807640736665, 50.61225710982058),
Offset(50.44597068423666, 50.48798174752058),
Offset(50.32613372773666, 50.36370638522058),
Offset(50.206296771136664, 50.23943102282058),
Offset(50.08645981463666, 50.11515566052058),
],
<Offset>[
Offset(18.692467120719886, 46.41563917637766),
Offset(18.692467120719886, 46.41563917637766),
Offset(18.692467120719886, 46.41563917637766),
Offset(18.692467120719886, 46.41563917637766),
Offset(18.692467120719886, 46.41563917637766),
Offset(18.692467120719886, 46.41563917637766),
Offset(18.692467120719886, 46.41563917637766),
Offset(18.692467120719886, 46.41563917637766),
Offset(18.692467120719886, 46.41563917637766),
Offset(18.692467120719886, 46.41563917637766),
Offset(19.76094037350107, 46.52182603428993),
Offset(25.077698896014848, 46.99779784106601),
Offset(30.48424678780122, 47.42520527750929),
Offset(35.90408326978374, 47.84660167834321),
Offset(41.23085606905603, 48.32123679418471),
Offset(46.299534025885855, 48.94128176514349),
Offset(50.13565503655109, 50.247817265511806),
Offset(52.34054840209764, 52.46557959108156),
Offset(53.662174345297636, 53.824022365081554),
Offset(53.54233738869764, 53.69974700278156),
Offset(53.42250043219764, 53.57547164038156),
Offset(53.302663475697635, 53.451196278081554),
Offset(53.18282651919764, 53.32692091578156),
Offset(53.06298956269764, 53.20264555348156),
Offset(52.94315260609764, 53.078370191181556),
Offset(52.82331564959764, 52.95409482888156),
Offset(52.70347869309764, 52.82981946648156),
Offset(52.583641736597635, 52.705544104181556),
Offset(52.46380478009764, 52.58126874188156),
Offset(52.343967823497636, 52.456993379581554),
Offset(52.22413086699764, 52.33271801728156),
Offset(52.10429391049764, 52.20844265488156),
Offset(51.984456953997636, 52.084167292581554),
Offset(51.86461999739764, 51.95989193028156),
Offset(51.74478304089764, 51.83561656798155),
Offset(51.624946084397635, 51.711341205681556),
Offset(51.50510912789764, 51.58706584328156),
Offset(51.38527217139764, 51.46279048098155),
Offset(51.265435214797634, 51.338515118681556),
Offset(51.14559825829764, 51.21423975638156),
Offset(51.02576130179764, 51.089964394081555),
Offset(50.905924345297635, 50.96568903178156),
Offset(50.78608738869764, 50.84141366938156),
Offset(50.666250432197636, 50.717138307081555),
Offset(50.54641347569764, 50.59286294478156),
Offset(50.42657651919764, 50.468587582481554),
Offset(50.306739562697636, 50.34431222018156),
Offset(50.18690260609764, 50.22003685778156),
Offset(50.06706564959764, 50.095761495481554),
],
<Offset>[
Offset(18.692467120719886, 36.41758712071989),
Offset(18.692467120719886, 36.41758712071989),
Offset(18.692467120719886, 36.41758712071989),
Offset(18.692467120719886, 36.41758712071989),
Offset(18.692467120719886, 36.41758712071989),
Offset(18.692467120719886, 36.41758712071989),
Offset(18.692467120719886, 36.41758712071989),
Offset(18.692467120719886, 36.41758712071989),
Offset(18.692467120719886, 36.41758712071989),
Offset(18.692467120719886, 36.41758712071989),
Offset(19.76094037350107, 36.87053160703761),
Offset(25.077698896014848, 39.09029363766916),
Offset(30.48424678780122, 41.31071235333787),
Offset(35.90408326978374, 43.53198610663798),
Offset(41.23085606905603, 45.75444966750169),
Offset(46.299534025885855, 47.97877125585276),
Offset(50.13565503655109, 50.20685835445277),
Offset(52.34054840209764, 52.44166244630614),
Offset(53.662174345297636, 53.800105220306136),
Offset(53.54233738869764, 53.67582985800614),
Offset(53.42250043219764, 53.55155449560614),
Offset(53.302663475697635, 53.427279133306136),
Offset(53.18282651919764, 53.30300377100614),
Offset(53.06298956269764, 53.17872840870614),
Offset(52.94315260609764, 53.05445304640614),
Offset(52.82331564959764, 52.93017768410614),
Offset(52.70347869309764, 52.80590232170614),
Offset(52.583641736597635, 52.68162695940614),
Offset(52.46380478009764, 52.55735159710614),
Offset(52.343967823497636, 52.43307623480614),
Offset(52.22413086699764, 52.30880087250614),
Offset(52.10429391049764, 52.18452551010614),
Offset(51.984456953997636, 52.06025014780614),
Offset(51.86461999739764, 51.93597478550614),
Offset(51.74478304089764, 51.811699423206136),
Offset(51.624946084397635, 51.68742406090614),
Offset(51.50510912789764, 51.56314869850614),
Offset(51.38527217139764, 51.438873336206136),
Offset(51.265435214797634, 51.31459797390614),
Offset(51.14559825829764, 51.19032261160614),
Offset(51.02576130179764, 51.06604724930614),
Offset(50.905924345297635, 50.94177188700614),
Offset(50.78608738869764, 50.81749652460614),
Offset(50.666250432197636, 50.69322116230614),
Offset(50.54641347569764, 50.56894580000614),
Offset(50.42657651919764, 50.44467043770614),
Offset(50.306739562697636, 50.32039507540614),
Offset(50.18690260609764, 50.19611971300614),
Offset(50.06706564959764, 50.07184435070614),
],
),
_PathCubicTo(
<Offset>[
Offset(18.692467120719886, 26.419565760864774),
Offset(18.692467120719886, 26.419565760864774),
Offset(18.692467120719886, 26.419565760864774),
Offset(18.692467120719886, 26.419565760864774),
Offset(18.692467120719886, 26.419565760864774),
Offset(18.692467120719886, 26.419565760864774),
Offset(18.692467120719886, 26.419565760864774),
Offset(18.692467120719886, 26.419565760864774),
Offset(18.692467120719886, 26.419565760864774),
Offset(18.692467120719886, 26.419565760864774),
Offset(19.76094037350107, 27.219266804248566),
Offset(25.077698896014848, 31.18281367228795),
Offset(30.48424678780122, 35.1962381308779),
Offset(35.90408326978374, 39.21738368206378),
Offset(41.23085606905603, 43.187670298244306),
Offset(46.299534025885855, 47.016263564148105),
Offset(50.13565503655109, 50.165899443393734),
Offset(52.34054840209764, 52.417745301530715),
Offset(53.662174345297636, 53.77618807553071),
Offset(53.54233738869764, 53.651912713230715),
Offset(53.42250043219764, 53.527637350830716),
Offset(53.302663475697635, 53.40336198853072),
Offset(53.18282651919764, 53.27908662623072),
Offset(53.06298956269764, 53.154811263930725),
Offset(52.94315260609764, 53.030535901630714),
Offset(52.82331564959764, 52.90626053933072),
Offset(52.70347869309764, 52.78198517693072),
Offset(52.583641736597635, 52.65770981463072),
Offset(52.46380478009764, 52.533434452330724),
Offset(52.343967823497636, 52.40915909003071),
Offset(52.22413086699764, 52.284883727730715),
Offset(52.10429391049764, 52.16060836533072),
Offset(51.984456953997636, 52.03633300303072),
Offset(51.86461999739764, 51.91205764073072),
Offset(51.74478304089764, 51.78778227843071),
Offset(51.624946084397635, 51.663506916130714),
Offset(51.50510912789764, 51.539231553730716),
Offset(51.38527217139764, 51.41495619143072),
Offset(51.265435214797634, 51.29068082913072),
Offset(51.14559825829764, 51.166405466830724),
Offset(51.02576130179764, 51.04213010453071),
Offset(50.905924345297635, 50.917854742230716),
Offset(50.78608738869764, 50.79357937983072),
Offset(50.666250432197636, 50.66930401753072),
Offset(50.54641347569764, 50.54502865523072),
Offset(50.42657651919764, 50.42075329293071),
Offset(50.306739562697636, 50.296477930630715),
Offset(50.18690260609764, 50.172202568230716),
Offset(50.06706564959764, 50.04792720593072),
],
<Offset>[
Offset(26.79953506506211, 18.312467120719884),
Offset(26.79953506506211, 18.312467120719884),
Offset(26.79953506506211, 18.312467120719884),
Offset(26.79953506506211, 18.312467120719884),
Offset(26.79953506506211, 18.312467120719884),
Offset(26.79953506506211, 18.312467120719884),
Offset(26.79953506506211, 18.312467120719884),
Offset(26.79953506506211, 18.312467120719884),
Offset(26.79953506506211, 18.312467120719884),
Offset(26.79953506506211, 18.312467120719884),
Offset(27.58683483600541, 19.393342717280955),
Offset(31.489615606172315, 24.77087272411485),
Offset(35.442274116666454, 30.23819210030122),
Offset(39.40265373804032, 35.71880006667617),
Offset(43.31217425963652, 41.106344350238174),
Offset(47.08000098097815, 46.23579379146974),
Offset(50.16886819340391, 50.13268628654091),
Offset(52.35994256713666, 52.3983511364917),
Offset(53.68156851033666, 53.756793910491695),
Offset(53.561731553736664, 53.6325185481917),
Offset(53.44189459723666, 53.5082431857917),
Offset(53.32205764073666, 53.38396782349169),
Offset(53.202220684236664, 53.25969246119169),
Offset(53.08238372773666, 53.13541709889169),
Offset(52.962546771136665, 53.011141736591696),
Offset(52.84270981463666, 52.8868663742917),
Offset(52.72287285813666, 52.7625910118917),
Offset(52.60303590163666, 52.63831564959169),
Offset(52.483198945136664, 52.51404028729169),
Offset(52.36336198853666, 52.389764924991695),
Offset(52.243525032036665, 52.2654895626917),
Offset(52.12368807553666, 52.1412142002917),
Offset(52.00385111903666, 52.01693883799169),
Offset(51.884014162436664, 51.89266347569169),
Offset(51.76417720593666, 51.768388113391694),
Offset(51.64434024943666, 51.6441127510917),
Offset(51.524503292936664, 51.5198373886917),
Offset(51.40466633643666, 51.39556202639169),
Offset(51.28482937983666, 51.27128666409169),
Offset(51.16499242333666, 51.14701130179169),
Offset(51.04515546683666, 51.022735939491696),
Offset(50.92531851033666, 50.8984605771917),
Offset(50.80548155373666, 50.7741852147917),
Offset(50.68564459723666, 50.64990985249169),
Offset(50.565807640736665, 50.52563449019169),
Offset(50.44597068423666, 50.401359127891695),
Offset(50.32613372773666, 50.2770837655917),
Offset(50.206296771136664, 50.1528084031917),
Offset(50.08645981463666, 50.02853304089169),
],
<Offset>[
Offset(36.79758712071989, 18.312467120719884),
Offset(36.79758712071989, 18.312467120719884),
Offset(36.79758712071989, 18.312467120719884),
Offset(36.79758712071989, 18.312467120719884),
Offset(36.79758712071989, 18.312467120719884),
Offset(36.79758712071989, 18.312467120719884),
Offset(36.79758712071989, 18.312467120719884),
Offset(36.79758712071989, 18.312467120719884),
Offset(36.79758712071989, 18.312467120719884),
Offset(36.79758712071989, 18.312467120719884),
Offset(37.238129263257726, 19.393342717280955),
Offset(39.39711980956916, 24.77087272411485),
Offset(41.55676704083787, 30.23819210030122),
Offset(43.717269309745554, 35.71880006667617),
Offset(45.878961386319546, 41.106344350238174),
Offset(48.04251149026888, 46.23579379146974),
Offset(50.209827104462946, 50.13268628654091),
Offset(52.38385971191208, 52.3983511364917),
Offset(53.70548565511208, 53.756793910491695),
Offset(53.58564869851208, 53.6325185481917),
Offset(53.46581174201208, 53.5082431857917),
Offset(53.34597478551208, 53.38396782349169),
Offset(53.22613782901208, 53.25969246119169),
Offset(53.10630087251208, 53.13541709889169),
Offset(52.98646391591208, 53.011141736591696),
Offset(52.86662695941208, 52.8868663742917),
Offset(52.74679000291208, 52.7625910118917),
Offset(52.626953046412076, 52.63831564959169),
Offset(52.50711608991208, 52.51404028729169),
Offset(52.38727913331208, 52.389764924991695),
Offset(52.26744217681208, 52.2654895626917),
Offset(52.14760522031208, 52.1412142002917),
Offset(52.02776826381208, 52.01693883799169),
Offset(51.90793130721208, 51.89266347569169),
Offset(51.78809435071208, 51.768388113391694),
Offset(51.66825739421208, 51.6441127510917),
Offset(51.54842043771208, 51.5198373886917),
Offset(51.42858348121208, 51.39556202639169),
Offset(51.308746524612076, 51.27128666409169),
Offset(51.18890956811208, 51.14701130179169),
Offset(51.06907261161208, 51.022735939491696),
Offset(50.949235655112076, 50.8984605771917),
Offset(50.82939869851208, 50.7741852147917),
Offset(50.70956174201208, 50.64990985249169),
Offset(50.58972478551208, 50.52563449019169),
Offset(50.46988782901208, 50.401359127891695),
Offset(50.35005087251208, 50.2770837655917),
Offset(50.23021391591208, 50.1528084031917),
Offset(50.11037695941208, 50.02853304089169),
],
),
_PathCubicTo(
<Offset>[
Offset(46.79563917637766, 18.312467120719884),
Offset(46.79563917637766, 18.312467120719884),
Offset(46.79563917637766, 18.312467120719884),
Offset(46.79563917637766, 18.312467120719884),
Offset(46.79563917637766, 18.312467120719884),
Offset(46.79563917637766, 18.312467120719884),
Offset(46.79563917637766, 18.312467120719884),
Offset(46.79563917637766, 18.312467120719884),
Offset(46.79563917637766, 18.312467120719884),
Offset(46.79563917637766, 18.312467120719884),
Offset(46.88942369051005, 19.393342717280955),
Offset(47.30462401296601, 24.77087272411485),
Offset(47.67125996500929, 30.23819210030122),
Offset(48.031884881450786, 35.71880006667617),
Offset(48.44574851300257, 41.106344350238174),
Offset(49.005021999553165, 46.23579379146974),
Offset(50.25078601552198, 50.13268628654091),
Offset(52.4077768566875, 52.3983511364917),
Offset(53.729402799887495, 53.756793910491695),
Offset(53.6095658432875, 53.6325185481917),
Offset(53.489728886787496, 53.5082431857917),
Offset(53.369891930287494, 53.38396782349169),
Offset(53.2500549737875, 53.25969246119169),
Offset(53.1302180172875, 53.13541709889169),
Offset(53.0103810606875, 53.011141736591696),
Offset(52.8905441041875, 52.8868663742917),
Offset(52.770707147687496, 52.7625910118917),
Offset(52.650870191187494, 52.63831564959169),
Offset(52.5310332346875, 52.51404028729169),
Offset(52.411196278087495, 52.389764924991695),
Offset(52.2913593215875, 52.2654895626917),
Offset(52.1715223650875, 52.1412142002917),
Offset(52.051685408587495, 52.01693883799169),
Offset(51.9318484519875, 51.89266347569169),
Offset(51.812011495487496, 51.768388113391694),
Offset(51.692174538987494, 51.6441127510917),
Offset(51.5723375824875, 51.5198373886917),
Offset(51.4525006259875, 51.39556202639169),
Offset(51.33266366938749, 51.27128666409169),
Offset(51.2128267128875, 51.14701130179169),
Offset(51.092989756387496, 51.022735939491696),
Offset(50.973152799887494, 50.8984605771917),
Offset(50.8533158432875, 50.7741852147917),
Offset(50.733478886787495, 50.64990985249169),
Offset(50.6136419302875, 50.52563449019169),
Offset(50.4938049737875, 50.401359127891695),
Offset(50.373968017287496, 50.2770837655917),
Offset(50.2541310606875, 50.1528084031917),
Offset(50.1342941041875, 50.02853304089169),
],
<Offset>[
Offset(54.90270712071989, 26.419565760864774),
Offset(54.90270712071989, 26.419565760864774),
Offset(54.90270712071989, 26.419565760864774),
Offset(54.90270712071989, 26.419565760864774),
Offset(54.90270712071989, 26.419565760864774),
Offset(54.90270712071989, 26.419565760864774),
Offset(54.90270712071989, 26.419565760864774),
Offset(54.90270712071989, 26.419565760864774),
Offset(54.90270712071989, 26.419565760864774),
Offset(54.90270712071989, 26.419565760864774),
Offset(54.71531815301439, 27.21926680424857),
Offset(53.71654072312347, 31.18281367228795),
Offset(52.62928729387452, 35.1962381308779),
Offset(51.53045534970737, 39.21738368206378),
Offset(50.52706670358306, 43.187670298244306),
Offset(49.7854889546519, 47.01626356414165),
Offset(50.283999172374806, 50.165899443393734),
Offset(52.42717102172652, 52.417745301530715),
Offset(53.74879696492653, 53.77618807553071),
Offset(53.62896000832653, 53.651912713230715),
Offset(53.50912305182652, 53.527637350830716),
Offset(53.389286095326526, 53.40336198853072),
Offset(53.26944913882653, 53.27908662623072),
Offset(53.14961218232652, 53.154811263930725),
Offset(53.029775225726524, 53.030535901630714),
Offset(52.90993826922653, 52.90626053933072),
Offset(52.79010131272652, 52.78198517693072),
Offset(52.670264356226525, 52.65770981463072),
Offset(52.55042739972653, 52.533434452330724),
Offset(52.43059044312652, 52.40915909003071),
Offset(52.310753486626524, 52.284883727730715),
Offset(52.19091653012653, 52.16060836533072),
Offset(52.07107957362652, 52.03633300303072),
Offset(51.95124261702652, 51.91205764073072),
Offset(51.83140566052653, 51.78778227843071),
Offset(51.71156870402652, 51.663506916130714),
Offset(51.591731747526524, 51.539231553730716),
Offset(51.47189479102653, 51.41495619143072),
Offset(51.35205783442652, 51.29068082913072),
Offset(51.23222087792652, 51.166405466830724),
Offset(51.11238392142653, 51.04213010453071),
Offset(50.99254696492652, 50.917854742230716),
Offset(50.87271000832652, 50.79357937983072),
Offset(50.752873051826526, 50.66930401753072),
Offset(50.63303609532653, 50.54502865523072),
Offset(50.51319913882652, 50.42075329293071),
Offset(50.39336218232653, 50.296477930630715),
Offset(50.27352522572653, 50.172202568230716),
Offset(50.15368826922652, 50.04792720593072),
],
<Offset>[
Offset(54.90270712071989, 36.41758712071989),
Offset(54.90270712071989, 36.41758712071989),
Offset(54.90270712071989, 36.41758712071989),
Offset(54.90270712071989, 36.41758712071989),
Offset(54.90270712071989, 36.41758712071989),
Offset(54.90270712071989, 36.41758712071989),
Offset(54.90270712071989, 36.41758712071989),
Offset(54.90270712071989, 36.41758712071989),
Offset(54.90270712071989, 36.41758712071989),
Offset(54.90270712071989, 36.41758712071989),
Offset(54.71531815301439, 36.87053160703761),
Offset(53.71654072312347, 39.09029363766916),
Offset(52.62928729387452, 41.31071235333787),
Offset(51.53045534970737, 43.53198610663798),
Offset(50.52706670358306, 45.75444966750169),
Offset(49.7854889546519, 47.97877125585276),
Offset(50.283999172374806, 50.20685835445277),
Offset(52.42717102172652, 52.44166244630614),
Offset(53.74879696492653, 53.800105220306136),
Offset(53.62896000832653, 53.67582985800614),
Offset(53.50912305182652, 53.55155449560614),
Offset(53.389286095326526, 53.427279133306136),
Offset(53.26944913882653, 53.30300377100614),
Offset(53.14961218232652, 53.17872840870614),
Offset(53.029775225726524, 53.05445304640614),
Offset(52.90993826922653, 52.93017768410614),
Offset(52.79010131272652, 52.80590232170614),
Offset(52.670264356226525, 52.68162695940614),
Offset(52.55042739972653, 52.55735159710614),
Offset(52.43059044312652, 52.43307623480614),
Offset(52.310753486626524, 52.30880087250614),
Offset(52.19091653012653, 52.18452551010614),
Offset(52.07107957362652, 52.06025014780614),
Offset(51.95124261702652, 51.93597478550614),
Offset(51.83140566052653, 51.811699423206136),
Offset(51.71156870402652, 51.68742406090614),
Offset(51.591731747526524, 51.56314869850614),
Offset(51.47189479102653, 51.438873336206136),
Offset(51.35205783442652, 51.31459797390614),
Offset(51.23222087792652, 51.19032261160614),
Offset(51.11238392142653, 51.06604724930614),
Offset(50.99254696492652, 50.94177188700614),
Offset(50.87271000832652, 50.81749652460614),
Offset(50.752873051826526, 50.69322116230614),
Offset(50.63303609532653, 50.56894580000614),
Offset(50.51319913882652, 50.44467043770614),
Offset(50.39336218232653, 50.32039507540614),
Offset(50.27352522572653, 50.19611971300614),
Offset(50.15368826922652, 50.07184435070614),
],
),
_PathCubicTo(
<Offset>[
Offset(54.90270712071989, 46.41563917637766),
Offset(54.90270712071989, 46.41563917637766),
Offset(54.90270712071989, 46.41563917637766),
Offset(54.90270712071989, 46.41563917637766),
Offset(54.90270712071989, 46.41563917637766),
Offset(54.90270712071989, 46.41563917637766),
Offset(54.90270712071989, 46.41563917637766),
Offset(54.90270712071989, 46.41563917637766),
Offset(54.90270712071989, 46.41563917637766),
Offset(54.90270712071989, 46.41563917637766),
Offset(54.71531815301439, 46.52182603428994),
Offset(53.71654072312347, 46.99779784106601),
Offset(52.62928729387452, 47.42520527750929),
Offset(51.53045534970737, 47.84660167834321),
Offset(50.52706670358306, 48.32123679418471),
Offset(49.7854889546519, 48.94128176513705),
Offset(50.283999172374806, 50.247817265511806),
Offset(52.42717102172652, 52.46557959108156),
Offset(53.74879696492653, 53.824022365081554),
Offset(53.62896000832653, 53.69974700278156),
Offset(53.50912305182652, 53.57547164038156),
Offset(53.389286095326526, 53.451196278081554),
Offset(53.26944913882653, 53.32692091578156),
Offset(53.14961218232652, 53.20264555348156),
Offset(53.029775225726524, 53.078370191181556),
Offset(52.90993826922653, 52.95409482888156),
Offset(52.79010131272652, 52.82981946648156),
Offset(52.670264356226525, 52.705544104181556),
Offset(52.55042739972653, 52.58126874188156),
Offset(52.43059044312652, 52.456993379581554),
Offset(52.310753486626524, 52.33271801728156),
Offset(52.19091653012653, 52.20844265488156),
Offset(52.07107957362652, 52.084167292581554),
Offset(51.95124261702652, 51.95989193028156),
Offset(51.83140566052653, 51.83561656798155),
Offset(51.71156870402652, 51.711341205681556),
Offset(51.591731747526524, 51.58706584328156),
Offset(51.47189479102653, 51.46279048098155),
Offset(51.35205783442652, 51.338515118681556),
Offset(51.23222087792652, 51.21423975638156),
Offset(51.11238392142653, 51.089964394081555),
Offset(50.99254696492652, 50.96568903178156),
Offset(50.87271000832652, 50.84141366938156),
Offset(50.752873051826526, 50.717138307081555),
Offset(50.63303609532653, 50.59286294478156),
Offset(50.51319913882652, 50.468587582481554),
Offset(50.39336218232653, 50.34431222018156),
Offset(50.27352522572653, 50.22003685778156),
Offset(50.15368826922652, 50.095761495481554),
],
<Offset>[
Offset(46.79563917637766, 54.522707120719886),
Offset(46.79563917637766, 54.522707120719886),
Offset(46.79563917637766, 54.522707120719886),
Offset(46.79563917637766, 54.522707120719886),
Offset(46.79563917637766, 54.522707120719886),
Offset(46.79563917637766, 54.522707120719886),
Offset(46.79563917637766, 54.522707120719886),
Offset(46.79563917637766, 54.522707120719886),
Offset(46.79563917637766, 54.522707120719886),
Offset(46.79563917637766, 54.522707120719886),
Offset(46.88942369051005, 54.34772049679427),
Offset(47.30462401296601, 53.40971455122347),
Offset(47.67125996500929, 52.38323260637452),
Offset(48.031884881450786, 51.34517214659979),
Offset(48.44574851300257, 50.4025549847652),
Offset(49.00502199955961, 49.72174872023579),
Offset(50.25078601552198, 50.28103042236462),
Offset(52.4077768566875, 52.48497375612058),
Offset(53.729402799887495, 53.84341653012058),
Offset(53.6095658432875, 53.71914116782058),
Offset(53.489728886787496, 53.59486580542058),
Offset(53.369891930287494, 53.47059044312058),
Offset(53.2500549737875, 53.34631508082058),
Offset(53.1302180172875, 53.222039718520584),
Offset(53.0103810606875, 53.09776435622058),
Offset(52.8905441041875, 52.97348899392058),
Offset(52.770707147687496, 52.849213631520584),
Offset(52.650870191187494, 52.72493826922058),
Offset(52.5310332346875, 52.60066290692058),
Offset(52.411196278087495, 52.47638754462058),
Offset(52.2913593215875, 52.35211218232058),
Offset(52.1715223650875, 52.22783681992058),
Offset(52.051685408587495, 52.10356145762058),
Offset(51.9318484519875, 51.97928609532058),
Offset(51.812011495487496, 51.85501073302058),
Offset(51.692174538987494, 51.73073537072058),
Offset(51.5723375824875, 51.60646000832058),
Offset(51.4525006259875, 51.48218464602058),
Offset(51.33266366938749, 51.35790928372058),
Offset(51.2128267128875, 51.233633921420584),
Offset(51.092989756387496, 51.10935855912058),
Offset(50.973152799887494, 50.98508319682058),
Offset(50.8533158432875, 50.860807834420584),
Offset(50.733478886787495, 50.73653247212058),
Offset(50.6136419302875, 50.61225710982058),
Offset(50.4938049737875, 50.48798174752058),
Offset(50.373968017287496, 50.36370638522058),
Offset(50.2541310606875, 50.23943102282058),
Offset(50.1342941041875, 50.11515566052058),
],
<Offset>[
Offset(36.79758712071989, 54.522707120719886),
Offset(36.79758712071989, 54.522707120719886),
Offset(36.79758712071989, 54.522707120719886),
Offset(36.79758712071989, 54.522707120719886),
Offset(36.79758712071989, 54.522707120719886),
Offset(36.79758712071989, 54.522707120719886),
Offset(36.79758712071989, 54.522707120719886),
Offset(36.79758712071989, 54.522707120719886),
Offset(36.79758712071989, 54.522707120719886),
Offset(36.79758712071989, 54.522707120719886),
Offset(37.238129263257726, 54.34772049679427),
Offset(39.39711980956916, 53.40971455122347),
Offset(41.55676704083787, 52.38323260637452),
Offset(43.717269309745554, 51.34517214659979),
Offset(45.878961386319546, 50.4025549847652),
Offset(48.04251149026888, 49.72174872023579),
Offset(50.209827104462946, 50.28103042236462),
Offset(52.38385971191208, 52.48497375612058),
Offset(53.70548565511208, 53.84341653012058),
Offset(53.58564869851208, 53.71914116782058),
Offset(53.46581174201208, 53.59486580542058),
Offset(53.34597478551208, 53.47059044312058),
Offset(53.22613782901208, 53.34631508082058),
Offset(53.10630087251208, 53.222039718520584),
Offset(52.98646391591208, 53.09776435622058),
Offset(52.86662695941208, 52.97348899392058),
Offset(52.74679000291208, 52.849213631520584),
Offset(52.626953046412076, 52.72493826922058),
Offset(52.50711608991208, 52.60066290692058),
Offset(52.38727913331208, 52.47638754462058),
Offset(52.26744217681208, 52.35211218232058),
Offset(52.14760522031208, 52.22783681992058),
Offset(52.02776826381208, 52.10356145762058),
Offset(51.90793130721208, 51.97928609532058),
Offset(51.78809435071208, 51.85501073302058),
Offset(51.66825739421208, 51.73073537072058),
Offset(51.54842043771208, 51.60646000832058),
Offset(51.42858348121208, 51.48218464602058),
Offset(51.308746524612076, 51.35790928372058),
Offset(51.18890956811208, 51.233633921420584),
Offset(51.06907261161208, 51.10935855912058),
Offset(50.949235655112076, 50.98508319682058),
Offset(50.82939869851208, 50.860807834420584),
Offset(50.70956174201208, 50.73653247212058),
Offset(50.58972478551208, 50.61225710982058),
Offset(50.46988782901208, 50.48798174752058),
Offset(50.35005087251208, 50.36370638522058),
Offset(50.23021391591208, 50.23943102282058),
Offset(50.11037695941208, 50.11515566052058),
],
),
_PathClose(
),
],
),
_PathFrames(
opacities: <double>[
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
],
commands: <_PathCommand>[
_PathMoveTo(
<Offset>[
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
],
),
_PathCubicTo(
<Offset>[
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
Offset(60.937745291919896, 54.52270224391989),
],
<Offset>[
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
],
<Offset>[
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
],
),
_PathCubicTo(
<Offset>[
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
Offset(57.739181458913336, 54.52270224391989),
],
<Offset>[
Offset(56.3827647181903, 53.16631619899751),
Offset(56.3827647181903, 53.16631619899751),
Offset(56.3827647181903, 53.16631619899751),
Offset(56.3827647181903, 53.16631619899751),
Offset(56.3827647181903, 53.16631619899751),
Offset(56.3827647181903, 53.16631619899751),
Offset(56.3827647181903, 53.16631619899751),
Offset(56.3827647181903, 53.16631619899751),
Offset(56.3827647181903, 53.16631619899751),
Offset(56.3827647181903, 53.16631619899751),
Offset(56.39144480852299, 53.174996289330196),
Offset(56.43397725114974, 53.217528731956946),
Offset(56.47650969377649, 53.2600611745837),
Offset(56.51904213640324, 53.30259361721045),
Offset(56.561574579029994, 53.3451260598372),
Offset(56.604107021656745, 53.38765850246395),
Offset(56.62684855989554, 53.41109453319635),
Offset(56.60877135783367, 53.39514421439123),
Offset(56.5906941557718, 53.37919389558813),
Offset(56.572616953707914, 53.363243576785024),
Offset(56.55453975164605, 53.347293257979906),
Offset(56.53646254958216, 53.33134293917681),
Offset(56.518385347520294, 53.3153926203737),
Offset(56.50030814545842, 53.29944230156859),
Offset(56.48223094339454, 53.28349198276548),
Offset(56.464153741332666, 53.267541663962376),
Offset(56.44607653927079, 53.251591345157266),
Offset(56.42799933720691, 53.23564102635416),
Offset(56.40992213514504, 53.21969070755106),
Offset(56.39184493308116, 53.20374038874594),
Offset(56.373767731019285, 53.187790069942835),
Offset(56.35569052895741, 53.171839751139736),
Offset(56.33761332689353, 53.15588943233462),
Offset(56.31953612483166, 53.13993911353152),
Offset(56.30145892276979, 53.12398879472841),
Offset(56.283381720705904, 53.108038475923294),
Offset(56.26530451864404, 53.092088157120195),
Offset(56.24722731658217, 53.07613783831709),
Offset(56.22915011451828, 53.06018751951198),
Offset(56.211072912456416, 53.04423720070887),
Offset(56.19299571039253, 53.02828688190577),
Offset(56.174918508330656, 53.012336563100654),
Offset(56.15684130626879, 52.996386244297554),
Offset(56.1387641042049, 52.98043592549445),
Offset(56.120686902143035, 52.96448560668933),
Offset(56.10260970008116, 52.94853528788623),
Offset(56.08453249801728, 52.93258496908312),
Offset(56.06645529595541, 52.916634650278006),
Offset(56.04837809389354, 52.900684331474906),
],
<Offset>[
Offset(56.3827647181903, 53.16631619899751),
Offset(56.3827647181903, 53.16631619899751),
Offset(56.3827647181903, 53.16631619899751),
Offset(56.3827647181903, 53.16631619899751),
Offset(56.3827647181903, 53.16631619899751),
Offset(56.3827647181903, 53.16631619899751),
Offset(56.3827647181903, 53.16631619899751),
Offset(56.3827647181903, 53.16631619899751),
Offset(56.3827647181903, 53.16631619899751),
Offset(56.3827647181903, 53.16631619899751),
Offset(56.39144480852299, 53.174996289330196),
Offset(56.43397725114974, 53.217528731956946),
Offset(56.47650969377649, 53.2600611745837),
Offset(56.51904213640324, 53.30259361721045),
Offset(56.561574579029994, 53.3451260598372),
Offset(56.604107021656745, 53.38765850246395),
Offset(56.62684855989554, 53.41109453319635),
Offset(56.60877135783367, 53.39514421439123),
Offset(56.5906941557718, 53.37919389558813),
Offset(56.572616953707914, 53.363243576785024),
Offset(56.55453975164605, 53.347293257979906),
Offset(56.53646254958216, 53.33134293917681),
Offset(56.518385347520294, 53.3153926203737),
Offset(56.50030814545842, 53.29944230156859),
Offset(56.48223094339454, 53.28349198276548),
Offset(56.464153741332666, 53.267541663962376),
Offset(56.44607653927079, 53.251591345157266),
Offset(56.42799933720691, 53.23564102635416),
Offset(56.40992213514504, 53.21969070755106),
Offset(56.39184493308116, 53.20374038874594),
Offset(56.373767731019285, 53.187790069942835),
Offset(56.35569052895741, 53.171839751139736),
Offset(56.33761332689353, 53.15588943233462),
Offset(56.31953612483166, 53.13993911353152),
Offset(56.30145892276979, 53.12398879472841),
Offset(56.283381720705904, 53.108038475923294),
Offset(56.26530451864404, 53.092088157120195),
Offset(56.24722731658217, 53.07613783831709),
Offset(56.22915011451828, 53.06018751951198),
Offset(56.211072912456416, 53.04423720070887),
Offset(56.19299571039253, 53.02828688190577),
Offset(56.174918508330656, 53.012336563100654),
Offset(56.15684130626879, 52.996386244297554),
Offset(56.1387641042049, 52.98043592549445),
Offset(56.120686902143035, 52.96448560668933),
Offset(56.10260970008116, 52.94853528788623),
Offset(56.08453249801728, 52.93258496908312),
Offset(56.06645529595541, 52.916634650278006),
Offset(56.04837809389354, 52.900684331474906),
],
),
_PathCubicTo(
<Offset>[
Offset(56.3827647181903, 53.16627596539751),
Offset(56.3827647181903, 53.16627596539751),
Offset(56.3827647181903, 53.16627596539751),
Offset(56.3827647181903, 53.16627596539751),
Offset(56.3827647181903, 53.16627596539751),
Offset(56.3827647181903, 53.16627596539751),
Offset(56.3827647181903, 53.16627596539751),
Offset(56.3827647181903, 53.16627596539751),
Offset(56.3827647181903, 53.16627596539751),
Offset(56.3827647181903, 53.16627596539751),
Offset(56.39144480852299, 53.1749560557302),
Offset(56.43397725114974, 53.21748849835695),
Offset(56.47650969377649, 53.2600209409837),
Offset(56.51904213640324, 53.302553383610444),
Offset(56.561574579029994, 53.345085826237195),
Offset(56.604107021656745, 53.387618268863946),
Offset(56.62684855989554, 53.411054299596344),
Offset(56.60877135783367, 53.395103980791234),
Offset(56.5906941557718, 53.37915366198813),
Offset(56.572616953707914, 53.36320334318502),
Offset(56.55453975164605, 53.34725302437991),
Offset(56.53646254958216, 53.3313027055768),
Offset(56.518385347520294, 53.315352386773704),
Offset(56.50030814545842, 53.299402067968586),
Offset(56.48223094339454, 53.28345174916548),
Offset(56.464153741332666, 53.26750143036238),
Offset(56.44607653927079, 53.25155111155726),
Offset(56.42799933720691, 53.23560079275416),
Offset(56.40992213514504, 53.219650473951056),
Offset(56.39184493308116, 53.20370015514594),
Offset(56.373767731019285, 53.18774983634284),
Offset(56.35569052895741, 53.17179951753973),
Offset(56.33761332689353, 53.15584919873462),
Offset(56.31953612483166, 53.139898879931515),
Offset(56.30145892276979, 53.123948561128415),
Offset(56.283381720705904, 53.1079982423233),
Offset(56.26530451864404, 53.0920479235202),
Offset(56.24722731658217, 53.07609760471709),
Offset(56.22915011451828, 53.060147285911974),
Offset(56.211072912456416, 53.044196967108874),
Offset(56.19299571039253, 53.02824664830577),
Offset(56.174918508330656, 53.01229632950065),
Offset(56.15684130626879, 52.99634601069755),
Offset(56.1387641042049, 52.980395691894444),
Offset(56.120686902143035, 52.96444537308933),
Offset(56.10260970008116, 52.94849505428623),
Offset(56.08453249801728, 52.93254473548313),
Offset(56.06645529595541, 52.91659441667801),
Offset(56.04837809389354, 52.9006440978749),
],
<Offset>[
Offset(53.54631924699953, 56.02289811551084),
Offset(53.54631924699953, 56.02289811551084),
Offset(53.54631924699953, 56.02289811551084),
Offset(53.54631924699953, 56.02289811551084),
Offset(53.54631924699953, 56.02289811551084),
Offset(53.54631924699953, 56.02289811551084),
Offset(53.54631924699953, 56.02289811551084),
Offset(53.54631924699953, 56.02289811551084),
Offset(53.54631924699953, 56.02289811551084),
Offset(53.54631924699953, 56.02289811551084),
Offset(53.55499933733222, 56.03157820584353),
Offset(53.59753177995896, 56.07411064847028),
Offset(53.64006422258572, 56.11664309109703),
Offset(53.682596665212465, 56.15917553372378),
Offset(53.725129107839216, 56.201707976350534),
Offset(53.76766155046597, 56.244240418977284),
Offset(53.790403088704764, 56.26767644970968),
Offset(53.77232588664289, 56.251726130904565),
Offset(53.75424868458102, 56.235775812101465),
Offset(53.736171482517136, 56.21982549329836),
Offset(53.71809428045527, 56.20387517449325),
Offset(53.70001707839138, 56.18792485569014),
Offset(53.68193987632951, 56.171974536887035),
Offset(53.66386267426764, 56.156024218081924),
Offset(53.645785472203755, 56.14007389927882),
Offset(53.62770827014189, 56.12412358047571),
Offset(53.60963106808002, 56.1081732616706),
Offset(53.591553866016135, 56.092222942867494),
Offset(53.57347666395426, 56.076272624064394),
Offset(53.55539946189038, 56.06032230525928),
Offset(53.53732225982851, 56.04437198645618),
Offset(53.51924505776664, 56.02842166765307),
Offset(53.501167855702754, 56.01247134884795),
Offset(53.483090653640886, 55.99652103004485),
Offset(53.46501345157901, 55.980570711241754),
Offset(53.44693624951513, 55.964620392436636),
Offset(53.42885904745326, 55.94867007363353),
Offset(53.41078184539139, 55.93271975483043),
Offset(53.392704643327505, 55.91676943602531),
Offset(53.37462744126564, 55.90081911722221),
Offset(53.35655023920175, 55.884868798419106),
Offset(53.33847303713988, 55.86891847961399),
Offset(53.32039583507801, 55.85296816081089),
Offset(53.302318633014124, 55.83701784200778),
Offset(53.28424143095226, 55.821067523202665),
Offset(53.26616422889038, 55.805117204399565),
Offset(53.248087026826504, 55.78916688559646),
Offset(53.23000982476463, 55.77321656679135),
Offset(53.21193262270276, 55.75726624798824),
],
<Offset>[
Offset(53.54628855119686, 56.02289811551084),
Offset(53.54628855119686, 56.02289811551084),
Offset(53.54628855119686, 56.02289811551084),
Offset(53.54628855119686, 56.02289811551084),
Offset(53.54628855119686, 56.02289811551084),
Offset(53.54628855119686, 56.02289811551084),
Offset(53.54628855119686, 56.02289811551084),
Offset(53.54628855119686, 56.02289811551084),
Offset(53.54628855119686, 56.02289811551084),
Offset(53.54628855119686, 56.02289811551084),
Offset(53.55496864152955, 56.03157820584353),
Offset(53.5975010841563, 56.07411064847028),
Offset(53.64003352678305, 56.11664309109703),
Offset(53.6825659694098, 56.15917553372378),
Offset(53.72509841203655, 56.201707976350534),
Offset(53.7676308546633, 56.244240418977284),
Offset(53.79037239290209, 56.26767644970968),
Offset(53.772295190840225, 56.251726130904565),
Offset(53.75421798877835, 56.235775812101465),
Offset(53.73614078671447, 56.21982549329836),
Offset(53.7180635846526, 56.20387517449325),
Offset(53.69998638258872, 56.18792485569014),
Offset(53.681909180526844, 56.171974536887035),
Offset(53.66383197846497, 56.156024218081924),
Offset(53.64575477640109, 56.14007389927882),
Offset(53.62767757433922, 56.12412358047571),
Offset(53.60960037227735, 56.1081732616706),
Offset(53.59152317021346, 56.092222942867494),
Offset(53.573445968151596, 56.076272624064394),
Offset(53.55536876608771, 56.06032230525928),
Offset(53.53729156402584, 56.04437198645618),
Offset(53.51921436196397, 56.02842166765307),
Offset(53.50113715990009, 56.01247134884795),
Offset(53.483059957838215, 55.99652103004485),
Offset(53.46498275577635, 55.980570711241754),
Offset(53.44690555371246, 55.964620392436636),
Offset(53.428828351650594, 55.94867007363353),
Offset(53.41075114958872, 55.93271975483043),
Offset(53.392673947524834, 55.91676943602531),
Offset(53.374596745462966, 55.90081911722221),
Offset(53.35651954339908, 55.884868798419106),
Offset(53.33844234133721, 55.86891847961399),
Offset(53.32036513927534, 55.85296816081089),
Offset(53.30228793721146, 55.83701784200778),
Offset(53.284210735149586, 55.821067523202665),
Offset(53.26613353308772, 55.805117204399565),
Offset(53.24805633102383, 55.78916688559646),
Offset(53.229979128961965, 55.77321656679135),
Offset(53.21190192690009, 55.75726624798824),
],
),
_PathCubicTo(
<Offset>[
Offset(53.54628855119686, 56.022857881910845),
Offset(53.54628855119686, 56.022857881910845),
Offset(53.54628855119686, 56.022857881910845),
Offset(53.54628855119686, 56.022857881910845),
Offset(53.54628855119686, 56.022857881910845),
Offset(53.54628855119686, 56.022857881910845),
Offset(53.54628855119686, 56.022857881910845),
Offset(53.54628855119686, 56.022857881910845),
Offset(53.54628855119686, 56.022857881910845),
Offset(53.54628855119686, 56.022857881910845),
Offset(53.55496864152955, 56.031537972243534),
Offset(53.5975010841563, 56.074070414870285),
Offset(53.64003352678305, 56.116602857497035),
Offset(53.6825659694098, 56.159135300123786),
Offset(53.72509841203655, 56.20166774275054),
Offset(53.7676308546633, 56.24420018537729),
Offset(53.79037239290209, 56.26763621610968),
Offset(53.772295190840225, 56.25168589730457),
Offset(53.75421798877835, 56.23573557850146),
Offset(53.73614078671447, 56.21978525969836),
Offset(53.7180635846526, 56.203834940893245),
Offset(53.69998638258872, 56.18788462209014),
Offset(53.681909180526844, 56.17193430328704),
Offset(53.66383197846497, 56.15598398448192),
Offset(53.64575477640109, 56.14003366567882),
Offset(53.62767757433922, 56.124083346875715),
Offset(53.60960037227735, 56.1081330280706),
Offset(53.59152317021346, 56.0921827092675),
Offset(53.573445968151596, 56.0762323904644),
Offset(53.55536876608771, 56.06028207165928),
Offset(53.53729156402584, 56.04433175285617),
Offset(53.51921436196397, 56.028381434053074),
Offset(53.50113715990009, 56.012431115247956),
Offset(53.483059957838215, 55.99648079644485),
Offset(53.46498275577635, 55.98053047764175),
Offset(53.44690555371246, 55.96458015883663),
Offset(53.428828351650594, 55.94862984003353),
Offset(53.41075114958872, 55.932679521230426),
Offset(53.392673947524834, 55.916729202425316),
Offset(53.374596745462966, 55.90077888362221),
Offset(53.35651954339908, 55.8848285648191),
Offset(53.33844234133721, 55.86887824601399),
Offset(53.32036513927534, 55.852927927210885),
Offset(53.30228793721146, 55.83697760840778),
Offset(53.284210735149586, 55.82102728960267),
Offset(53.26613353308772, 55.80507697079956),
Offset(53.24805633102383, 55.78912665199646),
Offset(53.229979128961965, 55.773176333191344),
Offset(53.21190192690009, 55.75722601438824),
],
<Offset>[
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
],
<Offset>[
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291921905, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
],
),
_PathCubicTo(
<Offset>[
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291921905, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.379314856233876),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.37931485623388),
Offset(54.902705291919894, 57.379314856233876),
],
<Offset>[
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291921905, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
],
<Offset>[
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291921905, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
],
),
_PathCubicTo(
<Offset>[
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291921905, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
Offset(54.902705291919894, 60.557742243937994),
],
<Offset>[
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(74.32497336367568, 79.93649262312883),
Offset(70.92176691523076, 76.5170858263241),
Offset(67.51856046678586, 73.09767902951937),
Offset(64.11535401834094, 69.67827223271463),
Offset(60.71214756989602, 66.25886543593002),
Offset(57.30894112147122, 62.83945863912528),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.01698575823052, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
],
<Offset>[
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(74.32497336367568, 79.93649262312883),
Offset(70.92176691523076, 76.5170858263241),
Offset(67.51856046678586, 73.09767902951937),
Offset(64.11535401834094, 69.67827223271463),
Offset(60.71214756989602, 66.25886543593002),
Offset(57.30894112147122, 62.83945863912528),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.01698575823052, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
],
),
_PathCubicTo(
<Offset>[
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(75.0195052919199, 80.63433074491833),
Offset(74.32497336367568, 79.93649262312883),
Offset(70.92176691523076, 76.5170858263241),
Offset(67.51856046678586, 73.09767902951937),
Offset(64.11535401834094, 69.67827223271463),
Offset(60.71214756989602, 66.25886543593002),
Offset(57.30894112147122, 62.83945863912528),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.01698575823052, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
Offset(55.016985758228515, 60.536592837199635),
],
<Offset>[
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(80.31980186465601, 73.9416641221485),
Offset(76.9165954162111, 70.52225732534376),
Offset(73.51338896776619, 67.10285052853904),
Offset(70.11018251932127, 63.6834437317343),
Offset(66.70697607087635, 60.26403693494969),
Offset(63.30376962245156, 56.84463013814495),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425921086, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
],
<Offset>[
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(80.31980186465601, 73.9416641221485),
Offset(76.9165954162111, 70.52225732534376),
Offset(73.51338896776619, 67.10285052853904),
Offset(70.11018251932127, 63.6834437317343),
Offset(66.70697607087635, 60.26403693494969),
Offset(63.30376962245156, 56.84463013814495),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425921086, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
],
),
_PathCubicTo(
<Offset>[
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(81.01433379290023, 74.639502243938),
Offset(80.31980186465601, 73.9416641221485),
Offset(76.9165954162111, 70.52225732534376),
Offset(73.51338896776619, 67.10285052853904),
Offset(70.11018251932127, 63.6834437317343),
Offset(66.70697607087635, 60.26403693494969),
Offset(63.30376962245156, 56.84463013814495),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425921086, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
Offset(61.01181425920885, 54.5417643362193),
],
<Offset>[
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529194001, 54.52270224393799),
Offset(60.937745291919896, 54.52270224393799),
Offset(60.937745291919896, 54.52270224393799),
Offset(60.937745291919896, 54.52270224391788),
Offset(60.937745291919896, 54.52270224393799),
Offset(60.93774529194001, 54.52270224393799),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192572, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
],
<Offset>[
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529191989, 54.52270224393799),
Offset(60.93774529194001, 54.52270224393799),
Offset(60.937745291919896, 54.52270224393799),
Offset(60.937745291919896, 54.52270224393799),
Offset(60.937745291919896, 54.52270224391788),
Offset(60.937745291919896, 54.52270224393799),
Offset(60.93774529194001, 54.52270224393799),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192572, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
Offset(60.93774529192372, 54.52270224393415),
],
),
_PathClose(
),
],
),
_PathFrames(
opacities: <double>[
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
],
commands: <_PathCommand>[
_PathMoveTo(
<Offset>[
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 54.754867779413956),
Offset(48.0, 51.604258802513954),
Offset(48.0, 48.45364982561395),
Offset(48.0, 45.30304084871395),
Offset(48.0, 42.15243187181395),
Offset(48.0, 39.00182289491395),
Offset(48.0, 35.85121391801395),
Offset(48.0, 34.05512107195435),
Offset(48.0, 33.540905901349916),
Offset(48.0, 33.12129231086275),
Offset(48.0, 32.781503706824346),
Offset(48.0, 32.50949551311259),
Offset(48.0, 32.29485026134325),
Offset(48.0, 32.1283960707288),
Offset(48.0, 32.00233286349681),
Offset(48.0, 31.909924001704802),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
],
),
_PathCubicTo(
<Offset>[
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 55.9765324848),
Offset(52.445826306158004, 54.754867779413956),
Offset(52.445826306158004, 51.604258802513954),
Offset(52.445826306158004, 48.45364982561395),
Offset(52.445826306158004, 45.30304084871395),
Offset(52.445826306158004, 42.15243187181395),
Offset(52.445826306158004, 39.00182289491395),
Offset(52.445826306158004, 35.85121391801395),
Offset(52.445826306158004, 34.05512107195435),
Offset(52.445826306158004, 33.540905901349916),
Offset(52.445826306158004, 33.12129231086275),
Offset(52.445826306158004, 32.781503706824346),
Offset(52.445826306158004, 32.50949551311259),
Offset(52.445826306158004, 32.29485026134325),
Offset(52.445826306158004, 32.1283960707288),
Offset(52.445826306158004, 32.00233286349681),
Offset(52.445826306158004, 31.909924001704802),
Offset(52.445826306158004, 31.90656),
Offset(52.445826306158004, 31.90656),
Offset(52.445826306158004, 31.90656),
Offset(52.445826306158004, 31.90656),
Offset(52.445826306158004, 31.90656),
Offset(52.445826306158004, 31.90656),
Offset(52.445826306158004, 31.90656),
Offset(52.445826306158004, 31.90656),
Offset(52.445826306158004, 31.90656),
Offset(52.445826306158004, 31.90656),
Offset(52.445826306158004, 31.90656),
Offset(52.445826306158004, 31.90656),
Offset(52.445826306158004, 31.90656),
Offset(52.445826306158004, 31.90656),
],
<Offset>[
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 52.37560809515534),
Offset(56.04672, 51.153943389769296),
Offset(56.04672, 48.00333441286929),
Offset(56.04672, 44.85272543596929),
Offset(56.04672, 41.70211645906929),
Offset(56.04672, 38.551507482169285),
Offset(56.04672, 35.40089850526928),
Offset(56.04672, 32.25028952836928),
Offset(56.04672, 30.45419668230969),
Offset(56.04672, 29.939981511705252),
Offset(56.04672, 29.520367921218085),
Offset(56.04672, 29.18057931717968),
Offset(56.04672, 28.908571123467926),
Offset(56.04672, 28.693925871698585),
Offset(56.04672, 28.527471681084133),
Offset(56.04672, 28.401408473852147),
Offset(56.04672, 28.308999612060138),
Offset(56.04672, 28.305635610355335),
Offset(56.04672, 28.305635610355335),
Offset(56.04672, 28.305635610355335),
Offset(56.04672, 28.305635610355335),
Offset(56.04672, 28.305635610355335),
Offset(56.04672, 28.305635610355335),
Offset(56.04672, 28.305635610355335),
Offset(56.04672, 28.305635610355335),
Offset(56.04672, 28.305635610355335),
Offset(56.04672, 28.305635610355335),
Offset(56.04672, 28.305635610355335),
Offset(56.04672, 28.305635610355335),
Offset(56.04672, 28.305635610355335),
Offset(56.04672, 28.305635610355335),
],
<Offset>[
Offset(56.04672, 47.9298124848),
Offset(56.04672, 47.9298124848),
Offset(56.04672, 47.9298124848),
Offset(56.04672, 47.9298124848),
Offset(56.04672, 47.9298124848),
Offset(56.04672, 47.9298124848),
Offset(56.04672, 47.9298124848),
Offset(56.04672, 47.9298124848),
Offset(56.04672, 47.9298124848),
Offset(56.04672, 47.9298124848),
Offset(56.04672, 47.9298124848),
Offset(56.04672, 47.9298124848),
Offset(56.04672, 47.9298124848),
Offset(56.04672, 47.9298124848),
Offset(56.04672, 47.9298124848),
Offset(56.04672, 47.9298124848),
Offset(56.04672, 47.9298124848),
Offset(56.04672, 47.9298124848),
Offset(56.04672, 47.9298124848),
Offset(56.04672, 46.708147779413956),
Offset(56.04672, 43.55753880251395),
Offset(56.04672, 40.40692982561395),
Offset(56.04672, 37.25632084871395),
Offset(56.04672, 34.10571187181395),
Offset(56.04672, 30.95510289491395),
Offset(56.04672, 27.804493918013947),
Offset(56.04672, 26.008401071954353),
Offset(56.04672, 25.494185901349915),
Offset(56.04672, 25.07457231086275),
Offset(56.04672, 24.734783706824345),
Offset(56.04672, 24.46277551311259),
Offset(56.04672, 24.24813026134325),
Offset(56.04672, 24.081676070728797),
Offset(56.04672, 23.95561286349681),
Offset(56.04672, 23.8632040017048),
Offset(56.04672, 23.85984),
Offset(56.04672, 23.85984),
Offset(56.04672, 23.85984),
Offset(56.04672, 23.85984),
Offset(56.04672, 23.85984),
Offset(56.04672, 23.85984),
Offset(56.04672, 23.85984),
Offset(56.04672, 23.85984),
Offset(56.04672, 23.85984),
Offset(56.04672, 23.85984),
Offset(56.04672, 23.85984),
Offset(56.04672, 23.85984),
Offset(56.04672, 23.85984),
Offset(56.04672, 23.85984),
],
),
_PathCubicTo(
<Offset>[
Offset(56.04672, 43.483986178642),
Offset(56.04672, 43.483986178642),
Offset(56.04672, 43.483986178642),
Offset(56.04672, 43.483986178642),
Offset(56.04672, 43.483986178642),
Offset(56.04672, 43.483986178642),
Offset(56.04672, 43.483986178642),
Offset(56.04672, 43.483986178642),
Offset(56.04672, 43.483986178642),
Offset(56.04672, 43.483986178642),
Offset(56.04672, 43.483986178642),
Offset(56.04672, 43.483986178642),
Offset(56.04672, 43.483986178642),
Offset(56.04672, 43.483986178642),
Offset(56.04672, 43.483986178642),
Offset(56.04672, 43.483986178642),
Offset(56.04672, 43.483986178642),
Offset(56.04672, 43.483986178642),
Offset(56.04672, 43.483986178642),
Offset(56.04672, 42.26232147325595),
Offset(56.04672, 39.11171249635595),
Offset(56.04672, 35.961103519455946),
Offset(56.04672, 32.810494542555944),
Offset(56.04672, 29.65988556565595),
Offset(56.04672, 26.50927658875595),
Offset(56.04672, 23.358667611855946),
Offset(56.04672, 21.562574765796352),
Offset(56.04672, 21.048359595191915),
Offset(56.04672, 20.628746004704748),
Offset(56.04672, 20.288957400666344),
Offset(56.04672, 20.01694920695459),
Offset(56.04672, 19.80230395518525),
Offset(56.04672, 19.635849764570796),
Offset(56.04672, 19.50978655733881),
Offset(56.04672, 19.4173776955468),
Offset(56.04672, 19.414013693841998),
Offset(56.04672, 19.414013693841998),
Offset(56.04672, 19.414013693841998),
Offset(56.04672, 19.414013693841998),
Offset(56.04672, 19.414013693841998),
Offset(56.04672, 19.414013693841998),
Offset(56.04672, 19.414013693841998),
Offset(56.04672, 19.414013693841998),
Offset(56.04672, 19.414013693841998),
Offset(56.04672, 19.414013693841998),
Offset(56.04672, 19.414013693841998),
Offset(56.04672, 19.414013693841998),
Offset(56.04672, 19.414013693841998),
Offset(56.04672, 19.414013693841998),
],
<Offset>[
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 39.8830924848),
Offset(52.445826306158004, 38.661427779413955),
Offset(52.445826306158004, 35.51081880251395),
Offset(52.445826306158004, 32.36020982561395),
Offset(52.445826306158004, 29.209600848713947),
Offset(52.445826306158004, 26.05899187181395),
Offset(52.445826306158004, 22.90838289491395),
Offset(52.445826306158004, 19.757773918013946),
Offset(52.445826306158004, 17.961681071954352),
Offset(52.445826306158004, 17.447465901349915),
Offset(52.445826306158004, 17.027852310862748),
Offset(52.445826306158004, 16.688063706824344),
Offset(52.445826306158004, 16.41605551311259),
Offset(52.445826306158004, 16.20141026134325),
Offset(52.445826306158004, 16.034956070728796),
Offset(52.445826306158004, 15.90889286349681),
Offset(52.445826306158004, 15.8164840017048),
Offset(52.445826306158004, 15.813119999999998),
Offset(52.445826306158004, 15.813119999999998),
Offset(52.445826306158004, 15.813119999999998),
Offset(52.445826306158004, 15.813119999999998),
Offset(52.445826306158004, 15.813119999999998),
Offset(52.445826306158004, 15.813119999999998),
Offset(52.445826306158004, 15.813119999999998),
Offset(52.445826306158004, 15.813119999999998),
Offset(52.445826306158004, 15.813119999999998),
Offset(52.445826306158004, 15.813119999999998),
Offset(52.445826306158004, 15.813119999999998),
Offset(52.445826306158004, 15.813119999999998),
Offset(52.445826306158004, 15.813119999999998),
Offset(52.445826306158004, 15.813119999999998),
],
<Offset>[
Offset(48.0, 39.8830924848),
Offset(48.0, 39.8830924848),
Offset(48.0, 39.8830924848),
Offset(48.0, 39.8830924848),
Offset(48.0, 39.8830924848),
Offset(48.0, 39.8830924848),
Offset(48.0, 39.8830924848),
Offset(48.0, 39.8830924848),
Offset(48.0, 39.8830924848),
Offset(48.0, 39.8830924848),
Offset(48.0, 39.8830924848),
Offset(48.0, 39.8830924848),
Offset(48.0, 39.8830924848),
Offset(48.0, 39.8830924848),
Offset(48.0, 39.8830924848),
Offset(48.0, 39.8830924848),
Offset(48.0, 39.8830924848),
Offset(48.0, 39.8830924848),
Offset(48.0, 39.8830924848),
Offset(48.0, 38.661427779413955),
Offset(48.0, 35.51081880251395),
Offset(48.0, 32.36020982561395),
Offset(48.0, 29.209600848713947),
Offset(48.0, 26.05899187181395),
Offset(48.0, 22.90838289491395),
Offset(48.0, 19.757773918013946),
Offset(48.0, 17.961681071954352),
Offset(48.0, 17.447465901349915),
Offset(48.0, 17.027852310862748),
Offset(48.0, 16.688063706824344),
Offset(48.0, 16.41605551311259),
Offset(48.0, 16.20141026134325),
Offset(48.0, 16.034956070728796),
Offset(48.0, 15.90889286349681),
Offset(48.0, 15.8164840017048),
Offset(48.0, 15.813119999999998),
Offset(48.0, 15.813119999999998),
Offset(48.0, 15.813119999999998),
Offset(48.0, 15.813119999999998),
Offset(48.0, 15.813119999999998),
Offset(48.0, 15.813119999999998),
Offset(48.0, 15.813119999999998),
Offset(48.0, 15.813119999999998),
Offset(48.0, 15.813119999999998),
Offset(48.0, 15.813119999999998),
Offset(48.0, 15.813119999999998),
Offset(48.0, 15.813119999999998),
Offset(48.0, 15.813119999999998),
Offset(48.0, 15.813119999999998),
],
),
_PathCubicTo(
<Offset>[
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 39.8830924848),
Offset(43.554173693841996, 38.661427779413955),
Offset(43.554173693841996, 35.51081880251395),
Offset(43.554173693841996, 32.36020982561395),
Offset(43.554173693841996, 29.209600848713947),
Offset(43.554173693841996, 26.05899187181395),
Offset(43.554173693841996, 22.90838289491395),
Offset(43.554173693841996, 19.757773918013946),
Offset(43.554173693841996, 17.961681071954352),
Offset(43.554173693841996, 17.447465901349915),
Offset(43.554173693841996, 17.027852310862748),
Offset(43.554173693841996, 16.688063706824344),
Offset(43.554173693841996, 16.41605551311259),
Offset(43.554173693841996, 16.20141026134325),
Offset(43.554173693841996, 16.034956070728796),
Offset(43.554173693841996, 15.90889286349681),
Offset(43.554173693841996, 15.8164840017048),
Offset(43.554173693841996, 15.813119999999998),
Offset(43.554173693841996, 15.813119999999998),
Offset(43.554173693841996, 15.813119999999998),
Offset(43.554173693841996, 15.813119999999998),
Offset(43.554173693841996, 15.813119999999998),
Offset(43.554173693841996, 15.813119999999998),
Offset(43.554173693841996, 15.813119999999998),
Offset(43.554173693841996, 15.813119999999998),
Offset(43.554173693841996, 15.813119999999998),
Offset(43.554173693841996, 15.813119999999998),
Offset(43.554173693841996, 15.813119999999998),
Offset(43.554173693841996, 15.813119999999998),
Offset(43.554173693841996, 15.813119999999998),
Offset(43.554173693841996, 15.813119999999998),
],
<Offset>[
Offset(39.95328, 43.483986178642),
Offset(39.95328, 43.483986178642),
Offset(39.95328, 43.483986178642),
Offset(39.95328, 43.483986178642),
Offset(39.95328, 43.483986178642),
Offset(39.95328, 43.483986178642),
Offset(39.95328, 43.483986178642),
Offset(39.95328, 43.483986178642),
Offset(39.95328, 43.483986178642),
Offset(39.95328, 43.483986178642),
Offset(39.95328, 43.483986178642),
Offset(39.95328, 43.483986178642),
Offset(39.95328, 43.483986178642),
Offset(39.95328, 43.483986178642),
Offset(39.95328, 43.483986178642),
Offset(39.95328, 43.483986178642),
Offset(39.95328, 43.483986178642),
Offset(39.95328, 43.483986178642),
Offset(39.95328, 43.483986178642),
Offset(39.95328, 42.26232147325595),
Offset(39.95328, 39.11171249635595),
Offset(39.95328, 35.961103519455946),
Offset(39.95328, 32.810494542555944),
Offset(39.95328, 29.65988556565595),
Offset(39.95328, 26.50927658875595),
Offset(39.95328, 23.358667611855946),
Offset(39.95328, 21.562574765796352),
Offset(39.95328, 21.048359595191915),
Offset(39.95328, 20.628746004704748),
Offset(39.95328, 20.288957400666344),
Offset(39.95328, 20.01694920695459),
Offset(39.95328, 19.80230395518525),
Offset(39.95328, 19.635849764570796),
Offset(39.95328, 19.50978655733881),
Offset(39.95328, 19.4173776955468),
Offset(39.95328, 19.414013693841998),
Offset(39.95328, 19.414013693841998),
Offset(39.95328, 19.414013693841998),
Offset(39.95328, 19.414013693841998),
Offset(39.95328, 19.414013693841998),
Offset(39.95328, 19.414013693841998),
Offset(39.95328, 19.414013693841998),
Offset(39.95328, 19.414013693841998),
Offset(39.95328, 19.414013693841998),
Offset(39.95328, 19.414013693841998),
Offset(39.95328, 19.414013693841998),
Offset(39.95328, 19.414013693841998),
Offset(39.95328, 19.414013693841998),
Offset(39.95328, 19.414013693841998),
],
<Offset>[
Offset(39.95328, 47.9298124848),
Offset(39.95328, 47.9298124848),
Offset(39.95328, 47.9298124848),
Offset(39.95328, 47.9298124848),
Offset(39.95328, 47.9298124848),
Offset(39.95328, 47.9298124848),
Offset(39.95328, 47.9298124848),
Offset(39.95328, 47.9298124848),
Offset(39.95328, 47.9298124848),
Offset(39.95328, 47.9298124848),
Offset(39.95328, 47.9298124848),
Offset(39.95328, 47.9298124848),
Offset(39.95328, 47.9298124848),
Offset(39.95328, 47.9298124848),
Offset(39.95328, 47.9298124848),
Offset(39.95328, 47.9298124848),
Offset(39.95328, 47.9298124848),
Offset(39.95328, 47.9298124848),
Offset(39.95328, 47.9298124848),
Offset(39.95328, 46.708147779413956),
Offset(39.95328, 43.55753880251395),
Offset(39.95328, 40.40692982561395),
Offset(39.95328, 37.25632084871395),
Offset(39.95328, 34.10571187181395),
Offset(39.95328, 30.95510289491395),
Offset(39.95328, 27.804493918013947),
Offset(39.95328, 26.008401071954353),
Offset(39.95328, 25.494185901349915),
Offset(39.95328, 25.07457231086275),
Offset(39.95328, 24.734783706824345),
Offset(39.95328, 24.46277551311259),
Offset(39.95328, 24.24813026134325),
Offset(39.95328, 24.081676070728797),
Offset(39.95328, 23.95561286349681),
Offset(39.95328, 23.8632040017048),
Offset(39.95328, 23.85984),
Offset(39.95328, 23.85984),
Offset(39.95328, 23.85984),
Offset(39.95328, 23.85984),
Offset(39.95328, 23.85984),
Offset(39.95328, 23.85984),
Offset(39.95328, 23.85984),
Offset(39.95328, 23.85984),
Offset(39.95328, 23.85984),
Offset(39.95328, 23.85984),
Offset(39.95328, 23.85984),
Offset(39.95328, 23.85984),
Offset(39.95328, 23.85984),
Offset(39.95328, 23.85984),
],
),
_PathCubicTo(
<Offset>[
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 52.37560809515534),
Offset(39.95328, 51.153943389769296),
Offset(39.95328, 48.00333441286929),
Offset(39.95328, 44.85272543596929),
Offset(39.95328, 41.70211645906929),
Offset(39.95328, 38.551507482169285),
Offset(39.95328, 35.40089850526928),
Offset(39.95328, 32.25028952836928),
Offset(39.95328, 30.45419668230969),
Offset(39.95328, 29.939981511705252),
Offset(39.95328, 29.520367921218085),
Offset(39.95328, 29.18057931717968),
Offset(39.95328, 28.908571123467926),
Offset(39.95328, 28.693925871698585),
Offset(39.95328, 28.527471681084133),
Offset(39.95328, 28.401408473852147),
Offset(39.95328, 28.308999612060138),
Offset(39.95328, 28.305635610355335),
Offset(39.95328, 28.305635610355335),
Offset(39.95328, 28.305635610355335),
Offset(39.95328, 28.305635610355335),
Offset(39.95328, 28.305635610355335),
Offset(39.95328, 28.305635610355335),
Offset(39.95328, 28.305635610355335),
Offset(39.95328, 28.305635610355335),
Offset(39.95328, 28.305635610355335),
Offset(39.95328, 28.305635610355335),
Offset(39.95328, 28.305635610355335),
Offset(39.95328, 28.305635610355335),
Offset(39.95328, 28.305635610355335),
Offset(39.95328, 28.305635610355335),
],
<Offset>[
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 55.9765324848),
Offset(43.554173693841996, 54.754867779413956),
Offset(43.554173693841996, 51.604258802513954),
Offset(43.554173693841996, 48.45364982561395),
Offset(43.554173693841996, 45.30304084871395),
Offset(43.554173693841996, 42.15243187181395),
Offset(43.554173693841996, 39.00182289491395),
Offset(43.554173693841996, 35.85121391801395),
Offset(43.554173693841996, 34.05512107195435),
Offset(43.554173693841996, 33.540905901349916),
Offset(43.554173693841996, 33.12129231086275),
Offset(43.554173693841996, 32.781503706824346),
Offset(43.554173693841996, 32.50949551311259),
Offset(43.554173693841996, 32.29485026134325),
Offset(43.554173693841996, 32.1283960707288),
Offset(43.554173693841996, 32.00233286349681),
Offset(43.554173693841996, 31.909924001704802),
Offset(43.554173693841996, 31.90656),
Offset(43.554173693841996, 31.90656),
Offset(43.554173693841996, 31.90656),
Offset(43.554173693841996, 31.90656),
Offset(43.554173693841996, 31.90656),
Offset(43.554173693841996, 31.90656),
Offset(43.554173693841996, 31.90656),
Offset(43.554173693841996, 31.90656),
Offset(43.554173693841996, 31.90656),
Offset(43.554173693841996, 31.90656),
Offset(43.554173693841996, 31.90656),
Offset(43.554173693841996, 31.90656),
Offset(43.554173693841996, 31.90656),
Offset(43.554173693841996, 31.90656),
],
<Offset>[
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 55.9765324848),
Offset(48.0, 54.754867779413956),
Offset(48.0, 51.604258802513954),
Offset(48.0, 48.45364982561395),
Offset(48.0, 45.30304084871395),
Offset(48.0, 42.15243187181395),
Offset(48.0, 39.00182289491395),
Offset(48.0, 35.85121391801395),
Offset(48.0, 34.05512107195435),
Offset(48.0, 33.540905901349916),
Offset(48.0, 33.12129231086275),
Offset(48.0, 32.781503706824346),
Offset(48.0, 32.50949551311259),
Offset(48.0, 32.29485026134325),
Offset(48.0, 32.1283960707288),
Offset(48.0, 32.00233286349681),
Offset(48.0, 31.909924001704802),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
Offset(48.0, 31.90656),
],
),
_PathClose(
),
],
),
_PathFrames(
opacities: <double>[
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
],
commands: <_PathCommand>[
_PathMoveTo(
<Offset>[
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
],
),
_PathCubicTo(
<Offset>[
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
Offset(43.554173693841996, 39.95328),
],
<Offset>[
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
Offset(39.95328, 43.554173693841996),
],
<Offset>[
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
Offset(39.95328, 48.0),
],
),
_PathCubicTo(
<Offset>[
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
Offset(39.95328, 52.445826306158004),
],
<Offset>[
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
Offset(43.554173693841996, 56.04672),
],
<Offset>[
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
Offset(48.0, 56.04672),
],
),
_PathCubicTo(
<Offset>[
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
Offset(52.445826306158004, 56.04672),
],
<Offset>[
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
Offset(56.04672, 52.445826306158004),
],
<Offset>[
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
Offset(56.04672, 48.0),
],
),
_PathCubicTo(
<Offset>[
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
Offset(56.04672, 43.554173693841996),
],
<Offset>[
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
Offset(52.445826306158004, 39.95328),
],
<Offset>[
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
Offset(48.0, 39.95328),
],
),
_PathClose(
),
],
),
_PathFrames(
opacities: <double>[
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
0.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
1.0,
],
commands: <_PathCommand>[
_PathMoveTo(
<Offset>[
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 41.2763342754),
Offset(48.0, 44.422639514400004),
Offset(48.0, 47.568944753400004),
Offset(48.0, 50.715249992400004),
Offset(48.0, 53.861555231400004),
Offset(48.0, 57.0078604704),
Offset(48.0, 60.154165709400004),
Offset(48.0, 61.94780621836377),
Offset(48.0, 62.46132080048674),
Offset(48.0, 62.88036269183587),
Offset(48.0, 63.219688353387404),
Offset(48.0, 63.491325951788546),
Offset(48.0, 63.70567876161293),
Offset(48.0, 63.87190616809776),
Offset(48.0, 63.997797621511204),
Offset(48.0, 64.09008058170691),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
],
),
_PathCubicTo(
<Offset>[
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 40.0563383664),
Offset(43.554173693841996, 41.2763342754),
Offset(43.554173693841996, 44.422639514400004),
Offset(43.554173693841996, 47.568944753400004),
Offset(43.554173693841996, 50.715249992400004),
Offset(43.554173693841996, 53.861555231400004),
Offset(43.554173693841996, 57.0078604704),
Offset(43.554173693841996, 60.154165709400004),
Offset(43.554173693841996, 61.94780621836377),
Offset(43.554173693841996, 62.46132080048674),
Offset(43.554173693841996, 62.88036269183587),
Offset(43.554173693841996, 63.219688353387404),
Offset(43.554173693841996, 63.491325951788546),
Offset(43.554173693841996, 63.70567876161293),
Offset(43.554173693841996, 63.87190616809776),
Offset(43.554173693841996, 63.997797621511204),
Offset(43.554173693841996, 64.09008058170691),
Offset(43.554173693841996, 64.09344),
Offset(43.554173693841996, 64.09344),
Offset(43.554173693841996, 64.09344),
Offset(43.554173693841996, 64.09344),
Offset(43.554173693841996, 64.09344),
Offset(43.554173693841996, 64.09344),
Offset(43.554173693841996, 64.09344),
Offset(43.554173693841996, 64.09344),
Offset(43.554173693841996, 64.09344),
Offset(43.554173693841996, 64.09344),
Offset(43.554173693841996, 64.09344),
Offset(43.554173693841996, 64.09344),
Offset(43.554173693841996, 64.09344),
Offset(43.554173693841996, 64.09344),
],
<Offset>[
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 43.65726275604466),
Offset(39.95328, 44.877258665044664),
Offset(39.95328, 48.023563904044664),
Offset(39.95328, 51.169869143044664),
Offset(39.95328, 54.316174382044665),
Offset(39.95328, 57.462479621044665),
Offset(39.95328, 60.608784860044665),
Offset(39.95328, 63.755090099044665),
Offset(39.95328, 65.54873060800844),
Offset(39.95328, 66.0622451901314),
Offset(39.95328, 66.48128708148053),
Offset(39.95328, 66.82061274303207),
Offset(39.95328, 67.09225034143321),
Offset(39.95328, 67.30660315125759),
Offset(39.95328, 67.47283055774243),
Offset(39.95328, 67.59872201115587),
Offset(39.95328, 67.69100497135157),
Offset(39.95328, 67.69436438964466),
Offset(39.95328, 67.69436438964466),
Offset(39.95328, 67.69436438964466),
Offset(39.95328, 67.69436438964466),
Offset(39.95328, 67.69436438964466),
Offset(39.95328, 67.69436438964466),
Offset(39.95328, 67.69436438964466),
Offset(39.95328, 67.69436438964466),
Offset(39.95328, 67.69436438964466),
Offset(39.95328, 67.69436438964466),
Offset(39.95328, 67.69436438964466),
Offset(39.95328, 67.69436438964466),
Offset(39.95328, 67.69436438964466),
Offset(39.95328, 67.69436438964466),
],
<Offset>[
Offset(39.95328, 48.1030583664),
Offset(39.95328, 48.1030583664),
Offset(39.95328, 48.1030583664),
Offset(39.95328, 48.1030583664),
Offset(39.95328, 48.1030583664),
Offset(39.95328, 48.1030583664),
Offset(39.95328, 48.1030583664),
Offset(39.95328, 48.1030583664),
Offset(39.95328, 48.1030583664),
Offset(39.95328, 48.1030583664),
Offset(39.95328, 48.1030583664),
Offset(39.95328, 48.1030583664),
Offset(39.95328, 48.1030583664),
Offset(39.95328, 48.1030583664),
Offset(39.95328, 48.1030583664),
Offset(39.95328, 48.1030583664),
Offset(39.95328, 48.1030583664),
Offset(39.95328, 48.1030583664),
Offset(39.95328, 48.1030583664),
Offset(39.95328, 49.3230542754),
Offset(39.95328, 52.4693595144),
Offset(39.95328, 55.6156647534),
Offset(39.95328, 58.761969992400005),
Offset(39.95328, 61.908275231400005),
Offset(39.95328, 65.0545804704),
Offset(39.95328, 68.20088570940001),
Offset(39.95328, 69.99452621836377),
Offset(39.95328, 70.50804080048674),
Offset(39.95328, 70.92708269183586),
Offset(39.95328, 71.2664083533874),
Offset(39.95328, 71.53804595178855),
Offset(39.95328, 71.75239876161294),
Offset(39.95328, 71.91862616809776),
Offset(39.95328, 72.0445176215112),
Offset(39.95328, 72.13680058170692),
Offset(39.95328, 72.14016000000001),
Offset(39.95328, 72.14016000000001),
Offset(39.95328, 72.14016000000001),
Offset(39.95328, 72.14016000000001),
Offset(39.95328, 72.14016000000001),
Offset(39.95328, 72.14016000000001),
Offset(39.95328, 72.14016000000001),
Offset(39.95328, 72.14016000000001),
Offset(39.95328, 72.14016000000001),
Offset(39.95328, 72.14016000000001),
Offset(39.95328, 72.14016000000001),
Offset(39.95328, 72.14016000000001),
Offset(39.95328, 72.14016000000001),
Offset(39.95328, 72.14016000000001),
],
),
_PathCubicTo(
<Offset>[
Offset(39.95328, 52.548884672558),
Offset(39.95328, 52.548884672558),
Offset(39.95328, 52.548884672558),
Offset(39.95328, 52.548884672558),
Offset(39.95328, 52.548884672558),
Offset(39.95328, 52.548884672558),
Offset(39.95328, 52.548884672558),
Offset(39.95328, 52.548884672558),
Offset(39.95328, 52.548884672558),
Offset(39.95328, 52.548884672558),
Offset(39.95328, 52.548884672558),
Offset(39.95328, 52.548884672558),
Offset(39.95328, 52.548884672558),
Offset(39.95328, 52.548884672558),
Offset(39.95328, 52.548884672558),
Offset(39.95328, 52.548884672558),
Offset(39.95328, 52.548884672558),
Offset(39.95328, 52.548884672558),
Offset(39.95328, 52.548884672558),
Offset(39.95328, 53.768880581558),
Offset(39.95328, 56.915185820558),
Offset(39.95328, 60.061491059558),
Offset(39.95328, 63.20779629855801),
Offset(39.95328, 66.35410153755801),
Offset(39.95328, 69.500406776558),
Offset(39.95328, 72.64671201555801),
Offset(39.95328, 74.44035252452177),
Offset(39.95328, 74.95386710664474),
Offset(39.95328, 75.37290899799387),
Offset(39.95328, 75.7122346595454),
Offset(39.95328, 75.98387225794654),
Offset(39.95328, 76.19822506777093),
Offset(39.95328, 76.36445247425576),
Offset(39.95328, 76.4903439276692),
Offset(39.95328, 76.58262688786492),
Offset(39.95328, 76.585986306158),
Offset(39.95328, 76.585986306158),
Offset(39.95328, 76.585986306158),
Offset(39.95328, 76.585986306158),
Offset(39.95328, 76.585986306158),
Offset(39.95328, 76.585986306158),
Offset(39.95328, 76.585986306158),
Offset(39.95328, 76.585986306158),
Offset(39.95328, 76.585986306158),
Offset(39.95328, 76.585986306158),
Offset(39.95328, 76.585986306158),
Offset(39.95328, 76.585986306158),
Offset(39.95328, 76.585986306158),
Offset(39.95328, 76.585986306158),
],
<Offset>[
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 56.1497783664),
Offset(43.554173693841996, 57.369774275400005),
Offset(43.554173693841996, 60.516079514400005),
Offset(43.554173693841996, 63.662384753400005),
Offset(43.554173693841996, 66.8086899924),
Offset(43.554173693841996, 69.9549952314),
Offset(43.554173693841996, 73.10130047039999),
Offset(43.554173693841996, 76.2476057094),
Offset(43.554173693841996, 78.04124621836377),
Offset(43.554173693841996, 78.55476080048675),
Offset(43.554173693841996, 78.97380269183587),
Offset(43.554173693841996, 79.31312835338741),
Offset(43.554173693841996, 79.58476595178854),
Offset(43.554173693841996, 79.79911876161293),
Offset(43.554173693841996, 79.96534616809777),
Offset(43.554173693841996, 80.0912376215112),
Offset(43.554173693841996, 80.18352058170692),
Offset(43.554173693841996, 80.18688),
Offset(43.554173693841996, 80.18688),
Offset(43.554173693841996, 80.18688),
Offset(43.554173693841996, 80.18688),
Offset(43.554173693841996, 80.18688),
Offset(43.554173693841996, 80.18688),
Offset(43.554173693841996, 80.18688),
Offset(43.554173693841996, 80.18688),
Offset(43.554173693841996, 80.18688),
Offset(43.554173693841996, 80.18688),
Offset(43.554173693841996, 80.18688),
Offset(43.554173693841996, 80.18688),
Offset(43.554173693841996, 80.18688),
Offset(43.554173693841996, 80.18688),
],
<Offset>[
Offset(48.0, 56.1497783664),
Offset(48.0, 56.1497783664),
Offset(48.0, 56.1497783664),
Offset(48.0, 56.1497783664),
Offset(48.0, 56.1497783664),
Offset(48.0, 56.1497783664),
Offset(48.0, 56.1497783664),
Offset(48.0, 56.1497783664),
Offset(48.0, 56.1497783664),
Offset(48.0, 56.1497783664),
Offset(48.0, 56.1497783664),
Offset(48.0, 56.1497783664),
Offset(48.0, 56.1497783664),
Offset(48.0, 56.1497783664),
Offset(48.0, 56.1497783664),
Offset(48.0, 56.1497783664),
Offset(48.0, 56.1497783664),
Offset(48.0, 56.1497783664),
Offset(48.0, 56.1497783664),
Offset(48.0, 57.369774275400005),
Offset(48.0, 60.516079514400005),
Offset(48.0, 63.662384753400005),
Offset(48.0, 66.8086899924),
Offset(48.0, 69.9549952314),
Offset(48.0, 73.10130047039999),
Offset(48.0, 76.2476057094),
Offset(48.0, 78.04124621836377),
Offset(48.0, 78.55476080048675),
Offset(48.0, 78.97380269183587),
Offset(48.0, 79.31312835338741),
Offset(48.0, 79.58476595178854),
Offset(48.0, 79.79911876161293),
Offset(48.0, 79.96534616809777),
Offset(48.0, 80.0912376215112),
Offset(48.0, 80.18352058170692),
Offset(48.0, 80.18688),
Offset(48.0, 80.18688),
Offset(48.0, 80.18688),
Offset(48.0, 80.18688),
Offset(48.0, 80.18688),
Offset(48.0, 80.18688),
Offset(48.0, 80.18688),
Offset(48.0, 80.18688),
Offset(48.0, 80.18688),
Offset(48.0, 80.18688),
Offset(48.0, 80.18688),
Offset(48.0, 80.18688),
Offset(48.0, 80.18688),
Offset(48.0, 80.18688),
],
),
_PathCubicTo(
<Offset>[
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 56.1497783664),
Offset(52.445826306158004, 57.369774275400005),
Offset(52.445826306158004, 60.516079514400005),
Offset(52.445826306158004, 63.662384753400005),
Offset(52.445826306158004, 66.8086899924),
Offset(52.445826306158004, 69.9549952314),
Offset(52.445826306158004, 73.10130047039999),
Offset(52.445826306158004, 76.2476057094),
Offset(52.445826306158004, 78.04124621836377),
Offset(52.445826306158004, 78.55476080048675),
Offset(52.445826306158004, 78.97380269183587),
Offset(52.445826306158004, 79.31312835338741),
Offset(52.445826306158004, 79.58476595178854),
Offset(52.445826306158004, 79.79911876161293),
Offset(52.445826306158004, 79.96534616809777),
Offset(52.445826306158004, 80.0912376215112),
Offset(52.445826306158004, 80.18352058170692),
Offset(52.445826306158004, 80.18688),
Offset(52.445826306158004, 80.18688),
Offset(52.445826306158004, 80.18688),
Offset(52.445826306158004, 80.18688),
Offset(52.445826306158004, 80.18688),
Offset(52.445826306158004, 80.18688),
Offset(52.445826306158004, 80.18688),
Offset(52.445826306158004, 80.18688),
Offset(52.445826306158004, 80.18688),
Offset(52.445826306158004, 80.18688),
Offset(52.445826306158004, 80.18688),
Offset(52.445826306158004, 80.18688),
Offset(52.445826306158004, 80.18688),
Offset(52.445826306158004, 80.18688),
],
<Offset>[
Offset(56.04672, 52.548884672558),
Offset(56.04672, 52.548884672558),
Offset(56.04672, 52.548884672558),
Offset(56.04672, 52.548884672558),
Offset(56.04672, 52.548884672558),
Offset(56.04672, 52.548884672558),
Offset(56.04672, 52.548884672558),
Offset(56.04672, 52.548884672558),
Offset(56.04672, 52.548884672558),
Offset(56.04672, 52.548884672558),
Offset(56.04672, 52.548884672558),
Offset(56.04672, 52.548884672558),
Offset(56.04672, 52.548884672558),
Offset(56.04672, 52.548884672558),
Offset(56.04672, 52.548884672558),
Offset(56.04672, 52.548884672558),
Offset(56.04672, 52.548884672558),
Offset(56.04672, 52.548884672558),
Offset(56.04672, 52.548884672558),
Offset(56.04672, 53.768880581558),
Offset(56.04672, 56.915185820558),
Offset(56.04672, 60.061491059558),
Offset(56.04672, 63.20779629855801),
Offset(56.04672, 66.35410153755801),
Offset(56.04672, 69.500406776558),
Offset(56.04672, 72.64671201555801),
Offset(56.04672, 74.44035252452177),
Offset(56.04672, 74.95386710664474),
Offset(56.04672, 75.37290899799387),
Offset(56.04672, 75.7122346595454),
Offset(56.04672, 75.98387225794654),
Offset(56.04672, 76.19822506777093),
Offset(56.04672, 76.36445247425576),
Offset(56.04672, 76.4903439276692),
Offset(56.04672, 76.58262688786492),
Offset(56.04672, 76.585986306158),
Offset(56.04672, 76.585986306158),
Offset(56.04672, 76.585986306158),
Offset(56.04672, 76.585986306158),
Offset(56.04672, 76.585986306158),
Offset(56.04672, 76.585986306158),
Offset(56.04672, 76.585986306158),
Offset(56.04672, 76.585986306158),
Offset(56.04672, 76.585986306158),
Offset(56.04672, 76.585986306158),
Offset(56.04672, 76.585986306158),
Offset(56.04672, 76.585986306158),
Offset(56.04672, 76.585986306158),
Offset(56.04672, 76.585986306158),
],
<Offset>[
Offset(56.04672, 48.1030583664),
Offset(56.04672, 48.1030583664),
Offset(56.04672, 48.1030583664),
Offset(56.04672, 48.1030583664),
Offset(56.04672, 48.1030583664),
Offset(56.04672, 48.1030583664),
Offset(56.04672, 48.1030583664),
Offset(56.04672, 48.1030583664),
Offset(56.04672, 48.1030583664),
Offset(56.04672, 48.1030583664),
Offset(56.04672, 48.1030583664),
Offset(56.04672, 48.1030583664),
Offset(56.04672, 48.1030583664),
Offset(56.04672, 48.1030583664),
Offset(56.04672, 48.1030583664),
Offset(56.04672, 48.1030583664),
Offset(56.04672, 48.1030583664),
Offset(56.04672, 48.1030583664),
Offset(56.04672, 48.1030583664),
Offset(56.04672, 49.3230542754),
Offset(56.04672, 52.4693595144),
Offset(56.04672, 55.6156647534),
Offset(56.04672, 58.761969992400005),
Offset(56.04672, 61.908275231400005),
Offset(56.04672, 65.0545804704),
Offset(56.04672, 68.20088570940001),
Offset(56.04672, 69.99452621836377),
Offset(56.04672, 70.50804080048674),
Offset(56.04672, 70.92708269183586),
Offset(56.04672, 71.2664083533874),
Offset(56.04672, 71.53804595178855),
Offset(56.04672, 71.75239876161294),
Offset(56.04672, 71.91862616809776),
Offset(56.04672, 72.0445176215112),
Offset(56.04672, 72.13680058170692),
Offset(56.04672, 72.14016000000001),
Offset(56.04672, 72.14016000000001),
Offset(56.04672, 72.14016000000001),
Offset(56.04672, 72.14016000000001),
Offset(56.04672, 72.14016000000001),
Offset(56.04672, 72.14016000000001),
Offset(56.04672, 72.14016000000001),
Offset(56.04672, 72.14016000000001),
Offset(56.04672, 72.14016000000001),
Offset(56.04672, 72.14016000000001),
Offset(56.04672, 72.14016000000001),
Offset(56.04672, 72.14016000000001),
Offset(56.04672, 72.14016000000001),
Offset(56.04672, 72.14016000000001),
],
),
_PathCubicTo(
<Offset>[
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 43.65726275604466),
Offset(56.04672, 44.877258665044664),
Offset(56.04672, 48.023563904044664),
Offset(56.04672, 51.169869143044664),
Offset(56.04672, 54.316174382044665),
Offset(56.04672, 57.462479621044665),
Offset(56.04672, 60.608784860044665),
Offset(56.04672, 63.755090099044665),
Offset(56.04672, 65.54873060800844),
Offset(56.04672, 66.0622451901314),
Offset(56.04672, 66.48128708148053),
Offset(56.04672, 66.82061274303207),
Offset(56.04672, 67.09225034143321),
Offset(56.04672, 67.30660315125759),
Offset(56.04672, 67.47283055774243),
Offset(56.04672, 67.59872201115587),
Offset(56.04672, 67.69100497135157),
Offset(56.04672, 67.69436438964466),
Offset(56.04672, 67.69436438964466),
Offset(56.04672, 67.69436438964466),
Offset(56.04672, 67.69436438964466),
Offset(56.04672, 67.69436438964466),
Offset(56.04672, 67.69436438964466),
Offset(56.04672, 67.69436438964466),
Offset(56.04672, 67.69436438964466),
Offset(56.04672, 67.69436438964466),
Offset(56.04672, 67.69436438964466),
Offset(56.04672, 67.69436438964466),
Offset(56.04672, 67.69436438964466),
Offset(56.04672, 67.69436438964466),
Offset(56.04672, 67.69436438964466),
],
<Offset>[
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 40.0563383664),
Offset(52.445826306158004, 41.2763342754),
Offset(52.445826306158004, 44.422639514400004),
Offset(52.445826306158004, 47.568944753400004),
Offset(52.445826306158004, 50.715249992400004),
Offset(52.445826306158004, 53.861555231400004),
Offset(52.445826306158004, 57.0078604704),
Offset(52.445826306158004, 60.154165709400004),
Offset(52.445826306158004, 61.94780621836377),
Offset(52.445826306158004, 62.46132080048674),
Offset(52.445826306158004, 62.88036269183587),
Offset(52.445826306158004, 63.219688353387404),
Offset(52.445826306158004, 63.491325951788546),
Offset(52.445826306158004, 63.70567876161293),
Offset(52.445826306158004, 63.87190616809776),
Offset(52.445826306158004, 63.997797621511204),
Offset(52.445826306158004, 64.09008058170691),
Offset(52.445826306158004, 64.09344),
Offset(52.445826306158004, 64.09344),
Offset(52.445826306158004, 64.09344),
Offset(52.445826306158004, 64.09344),
Offset(52.445826306158004, 64.09344),
Offset(52.445826306158004, 64.09344),
Offset(52.445826306158004, 64.09344),
Offset(52.445826306158004, 64.09344),
Offset(52.445826306158004, 64.09344),
Offset(52.445826306158004, 64.09344),
Offset(52.445826306158004, 64.09344),
Offset(52.445826306158004, 64.09344),
Offset(52.445826306158004, 64.09344),
Offset(52.445826306158004, 64.09344),
],
<Offset>[
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 40.0563383664),
Offset(48.0, 41.2763342754),
Offset(48.0, 44.422639514400004),
Offset(48.0, 47.568944753400004),
Offset(48.0, 50.715249992400004),
Offset(48.0, 53.861555231400004),
Offset(48.0, 57.0078604704),
Offset(48.0, 60.154165709400004),
Offset(48.0, 61.94780621836377),
Offset(48.0, 62.46132080048674),
Offset(48.0, 62.88036269183587),
Offset(48.0, 63.219688353387404),
Offset(48.0, 63.491325951788546),
Offset(48.0, 63.70567876161293),
Offset(48.0, 63.87190616809776),
Offset(48.0, 63.997797621511204),
Offset(48.0, 64.09008058170691),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
Offset(48.0, 64.09344),
],
),
_PathClose(
),
],
),
],
);
| flutter/packages/flutter/lib/src/material/animated_icons/data/search_ellipsis.g.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/animated_icons/data/search_ellipsis.g.dart",
"repo_id": "flutter",
"token_count": 154395
} | 620 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'bottom_sheet_theme.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'constants.dart';
import 'curves.dart';
import 'debug.dart';
import 'material.dart';
import 'material_localizations.dart';
import 'material_state.dart';
import 'scaffold.dart';
import 'theme.dart';
const Duration _bottomSheetEnterDuration = Duration(milliseconds: 250);
const Duration _bottomSheetExitDuration = Duration(milliseconds: 200);
const Curve _modalBottomSheetCurve = decelerateEasing;
const double _minFlingVelocity = 700.0;
const double _closeProgressThreshold = 0.5;
const double _defaultScrollControlDisabledMaxHeightRatio = 9.0 / 16.0;
/// A callback for when the user begins dragging the bottom sheet.
///
/// Used by [BottomSheet.onDragStart].
typedef BottomSheetDragStartHandler = void Function(DragStartDetails details);
/// A callback for when the user stops dragging the bottom sheet.
///
/// Used by [BottomSheet.onDragEnd].
typedef BottomSheetDragEndHandler = void Function(
DragEndDetails details, {
required bool isClosing,
});
/// A Material Design bottom sheet.
///
/// There are two kinds of bottom sheets in Material Design:
///
/// * _Persistent_. A persistent bottom sheet shows information that
/// supplements the primary content of the app. A persistent bottom sheet
/// remains visible even when the user interacts with other parts of the app.
/// Persistent bottom sheets can be created and displayed with the
/// [ScaffoldState.showBottomSheet] function or by specifying the
/// [Scaffold.bottomSheet] constructor parameter.
///
/// * _Modal_. A modal bottom sheet is an alternative to a menu or a dialog and
/// prevents the user from interacting with the rest of the app. Modal bottom
/// sheets can be created and displayed with the [showModalBottomSheet]
/// function.
///
/// The [BottomSheet] widget itself is rarely used directly. Instead, prefer to
/// create a persistent bottom sheet with [ScaffoldState.showBottomSheet] or
/// [Scaffold.bottomSheet], and a modal bottom sheet with [showModalBottomSheet].
///
/// See also:
///
/// * [showBottomSheet] and [ScaffoldState.showBottomSheet], for showing
/// non-modal "persistent" bottom sheets.
/// * [showModalBottomSheet], which can be used to display a modal bottom
/// sheet.
/// * [BottomSheetThemeData], which can be used to customize the default
/// bottom sheet property values.
/// * The Material 2 spec at <https://m2.material.io/components/sheets-bottom>.
/// * The Material 3 spec at <https://m3.material.io/components/bottom-sheets/overview>.
class BottomSheet extends StatefulWidget {
/// Creates a bottom sheet.
///
/// Typically, bottom sheets are created implicitly by
/// [ScaffoldState.showBottomSheet], for persistent bottom sheets, or by
/// [showModalBottomSheet], for modal bottom sheets.
const BottomSheet({
super.key,
this.animationController,
this.enableDrag = true,
this.showDragHandle,
this.dragHandleColor,
this.dragHandleSize,
this.onDragStart,
this.onDragEnd,
this.backgroundColor,
this.shadowColor,
this.elevation,
this.shape,
this.clipBehavior,
this.constraints,
required this.onClosing,
required this.builder,
}) : assert(elevation == null || elevation >= 0.0);
/// The animation controller that controls the bottom sheet's entrance and
/// exit animations.
///
/// The BottomSheet widget will manipulate the position of this animation, it
/// is not just a passive observer.
final AnimationController? animationController;
/// Called when the bottom sheet begins to close.
///
/// A bottom sheet might be prevented from closing (e.g., by user
/// interaction) even after this callback is called. For this reason, this
/// callback might be call multiple times for a given bottom sheet.
final VoidCallback onClosing;
/// A builder for the contents of the sheet.
///
/// The bottom sheet will wrap the widget produced by this builder in a
/// [Material] widget.
final WidgetBuilder builder;
/// If true, the bottom sheet can be dragged up and down and dismissed by
/// swiping downwards.
///
/// If [showDragHandle] is true, this only applies to the content below the drag handle,
/// because the drag handle is always draggable.
///
/// Default is true.
///
/// If this is true, the [animationController] must not be null.
/// Use [BottomSheet.createAnimationController] to create one, or provide
/// another AnimationController.
final bool enableDrag;
/// Specifies whether a drag handle is shown.
///
/// The drag handle appears at the top of the bottom sheet. The default color is
/// [ColorScheme.onSurfaceVariant] with an opacity of 0.4 and can be customized
/// using [dragHandleColor]. The default size is `Size(32,4)` and can be customized
/// with [dragHandleSize].
///
/// If null, then the value of [BottomSheetThemeData.showDragHandle] is used. If
/// that is also null, defaults to false.
///
/// If this is true, the [animationController] must not be null.
/// Use [BottomSheet.createAnimationController] to create one, or provide
/// another AnimationController.
final bool? showDragHandle;
/// The bottom sheet drag handle's color.
///
/// Defaults to [BottomSheetThemeData.dragHandleColor].
/// If that is also null, defaults to [ColorScheme.onSurfaceVariant].
final Color? dragHandleColor;
/// Defaults to [BottomSheetThemeData.dragHandleSize].
/// If that is also null, defaults to Size(32, 4).
final Size? dragHandleSize;
/// Called when the user begins dragging the bottom sheet vertically, if
/// [enableDrag] is true.
///
/// Would typically be used to change the bottom sheet animation curve so
/// that it tracks the user's finger accurately.
final BottomSheetDragStartHandler? onDragStart;
/// Called when the user stops dragging the bottom sheet, if [enableDrag]
/// is true.
///
/// Would typically be used to reset the bottom sheet animation curve, so
/// that it animates non-linearly. Called before [onClosing] if the bottom
/// sheet is closing.
final BottomSheetDragEndHandler? onDragEnd;
/// The bottom sheet's background color.
///
/// Defines the bottom sheet's [Material.color].
///
/// Defaults to null and falls back to [Material]'s default.
final Color? backgroundColor;
/// The color of the shadow below the sheet.
///
/// If this property is null, then [BottomSheetThemeData.shadowColor] of
/// [ThemeData.bottomSheetTheme] is used. If that is also null, the default value
/// is transparent.
///
/// See also:
///
/// * [elevation], which defines the size of the shadow below the sheet.
/// * [shape], which defines the shape of the sheet and its shadow.
final Color? shadowColor;
/// The z-coordinate at which to place this material relative to its parent.
///
/// This controls the size of the shadow below the material.
///
/// Defaults to 0. The value is non-negative.
final double? elevation;
/// The shape of the bottom sheet.
///
/// Defines the bottom sheet's [Material.shape].
///
/// Defaults to null and falls back to [Material]'s default.
final ShapeBorder? shape;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defines the bottom sheet's [Material.clipBehavior].
///
/// Use this property to enable clipping of content when the bottom sheet has
/// a custom [shape] and the content can extend past this shape. For example,
/// a bottom sheet with rounded corners and an edge-to-edge [Image] at the
/// top.
///
/// If this property is null then [BottomSheetThemeData.clipBehavior] of
/// [ThemeData.bottomSheetTheme] is used. If that's null then the behavior
/// will be [Clip.none].
final Clip? clipBehavior;
/// Defines minimum and maximum sizes for a [BottomSheet].
///
/// If null, then the ambient [ThemeData.bottomSheetTheme]'s
/// [BottomSheetThemeData.constraints] will be used. If that
/// is null and [ThemeData.useMaterial3] is true, then the bottom sheet
/// will have a max width of 640dp. If [ThemeData.useMaterial3] is false, then
/// the bottom sheet's size will be constrained by its parent
/// (usually a [Scaffold]). In this case, consider limiting the width by
/// setting smaller constraints for large screens.
///
/// If constraints are specified (either in this property or in the
/// theme), the bottom sheet will be aligned to the bottom-center of
/// the available space. Otherwise, no alignment is applied.
final BoxConstraints? constraints;
@override
State<BottomSheet> createState() => _BottomSheetState();
/// Creates an [AnimationController] suitable for a
/// [BottomSheet.animationController].
///
/// This API available as a convenience for a Material compliant bottom sheet
/// animation. If alternative animation durations are required, a different
/// animation controller could be provided.
static AnimationController createAnimationController(TickerProvider vsync) {
return AnimationController(
duration: _bottomSheetEnterDuration,
reverseDuration: _bottomSheetExitDuration,
debugLabel: 'BottomSheet',
vsync: vsync,
);
}
}
class _BottomSheetState extends State<BottomSheet> {
final GlobalKey _childKey = GlobalKey(debugLabel: 'BottomSheet child');
double get _childHeight {
final RenderBox renderBox = _childKey.currentContext!.findRenderObject()! as RenderBox;
return renderBox.size.height;
}
bool get _dismissUnderway => widget.animationController!.status == AnimationStatus.reverse;
Set<MaterialState> dragHandleMaterialState = <MaterialState>{};
void _handleDragStart(DragStartDetails details) {
setState(() {
dragHandleMaterialState.add(MaterialState.dragged);
});
widget.onDragStart?.call(details);
}
void _handleDragUpdate(DragUpdateDetails details) {
assert(
(widget.enableDrag || (widget.showDragHandle?? false)) && widget.animationController != null,
"'BottomSheet.animationController' cannot be null when 'BottomSheet.enableDrag' or 'BottomSheet.showDragHandle' is true. "
"Use 'BottomSheet.createAnimationController' to create one, or provide another AnimationController.",
);
if (_dismissUnderway) {
return;
}
widget.animationController!.value -= details.primaryDelta! / _childHeight;
}
void _handleDragEnd(DragEndDetails details) {
assert(
(widget.enableDrag || (widget.showDragHandle?? false)) && widget.animationController != null,
"'BottomSheet.animationController' cannot be null when 'BottomSheet.enableDrag' or 'BottomSheet.showDragHandle' is true. "
"Use 'BottomSheet.createAnimationController' to create one, or provide another AnimationController.",
);
if (_dismissUnderway) {
return;
}
setState(() {
dragHandleMaterialState.remove(MaterialState.dragged);
});
bool isClosing = false;
if (details.velocity.pixelsPerSecond.dy > _minFlingVelocity) {
final double flingVelocity = -details.velocity.pixelsPerSecond.dy / _childHeight;
if (widget.animationController!.value > 0.0) {
widget.animationController!.fling(velocity: flingVelocity);
}
if (flingVelocity < 0.0) {
isClosing = true;
}
} else if (widget.animationController!.value < _closeProgressThreshold) {
if (widget.animationController!.value > 0.0) {
widget.animationController!.fling(velocity: -1.0);
}
isClosing = true;
} else {
widget.animationController!.forward();
}
widget.onDragEnd?.call(
details,
isClosing: isClosing,
);
if (isClosing) {
widget.onClosing();
}
}
bool extentChanged(DraggableScrollableNotification notification) {
if (notification.extent == notification.minExtent && notification.shouldCloseOnMinExtent) {
widget.onClosing();
}
return false;
}
void _handleDragHandleHover(bool hovering) {
if (hovering != dragHandleMaterialState.contains(MaterialState.hovered)) {
setState(() {
if (hovering){
dragHandleMaterialState.add(MaterialState.hovered);
}
else{
dragHandleMaterialState.remove(MaterialState.hovered);
}
});
}
}
@override
Widget build(BuildContext context) {
final BottomSheetThemeData bottomSheetTheme = Theme.of(context).bottomSheetTheme;
final bool useMaterial3 = Theme.of(context).useMaterial3;
final BottomSheetThemeData defaults = useMaterial3 ? _BottomSheetDefaultsM3(context) : const BottomSheetThemeData();
final BoxConstraints? constraints = widget.constraints ?? bottomSheetTheme.constraints ?? defaults.constraints;
final Color? color = widget.backgroundColor ?? bottomSheetTheme.backgroundColor ?? defaults.backgroundColor;
final Color? surfaceTintColor = bottomSheetTheme.surfaceTintColor ?? defaults.surfaceTintColor;
final Color? shadowColor = widget.shadowColor ?? bottomSheetTheme.shadowColor ?? defaults.shadowColor;
final double elevation = widget.elevation ?? bottomSheetTheme.elevation ?? defaults.elevation ?? 0;
final ShapeBorder? shape = widget.shape ?? bottomSheetTheme.shape ?? defaults.shape;
final Clip clipBehavior = widget.clipBehavior ?? bottomSheetTheme.clipBehavior ?? Clip.none;
final bool showDragHandle = widget.showDragHandle ?? (widget.enableDrag && (bottomSheetTheme.showDragHandle ?? false));
Widget? dragHandle;
if (showDragHandle){
dragHandle = _DragHandle(
onSemanticsTap: widget.onClosing,
handleHover: _handleDragHandleHover,
materialState: dragHandleMaterialState,
dragHandleColor: widget.dragHandleColor,
dragHandleSize: widget.dragHandleSize,
);
// Only add [_BottomSheetGestureDetector] to the drag handle when the rest of the
// bottom sheet is not draggable. If the whole bottom sheet is draggable,
// no need to add it.
if (!widget.enableDrag) {
dragHandle = _BottomSheetGestureDetector(
onVerticalDragStart: _handleDragStart,
onVerticalDragUpdate: _handleDragUpdate,
onVerticalDragEnd: _handleDragEnd,
child: dragHandle,
);
}
}
Widget bottomSheet = Material(
key: _childKey,
color: color,
elevation: elevation,
surfaceTintColor: surfaceTintColor,
shadowColor: shadowColor,
shape: shape,
clipBehavior: clipBehavior,
child: NotificationListener<DraggableScrollableNotification>(
onNotification: extentChanged,
child: !showDragHandle
? widget.builder(context)
: Stack(
alignment: Alignment.topCenter,
children: <Widget>[
dragHandle!,
Padding(
padding: const EdgeInsets.only(top: kMinInteractiveDimension),
child: widget.builder(context),
),
],
),
),
);
if (constraints != null) {
bottomSheet = Align(
alignment: Alignment.bottomCenter,
heightFactor: 1.0,
child: ConstrainedBox(
constraints: constraints,
child: bottomSheet,
),
);
}
return !widget.enableDrag ? bottomSheet : _BottomSheetGestureDetector(
onVerticalDragStart: _handleDragStart,
onVerticalDragUpdate: _handleDragUpdate,
onVerticalDragEnd: _handleDragEnd,
child: bottomSheet,
);
}
}
// PERSISTENT BOTTOM SHEETS
// See scaffold.dart
typedef _SizeChangeCallback<Size> = void Function(Size size);
class _DragHandle extends StatelessWidget {
const _DragHandle({
required this.onSemanticsTap,
required this.handleHover,
required this.materialState,
this.dragHandleColor,
this.dragHandleSize,
});
final VoidCallback? onSemanticsTap;
final ValueChanged<bool> handleHover;
final Set<MaterialState> materialState;
final Color? dragHandleColor;
final Size? dragHandleSize;
@override
Widget build(BuildContext context) {
final BottomSheetThemeData bottomSheetTheme = Theme.of(context).bottomSheetTheme;
final BottomSheetThemeData m3Defaults = _BottomSheetDefaultsM3(context);
final Size handleSize = dragHandleSize ?? bottomSheetTheme.dragHandleSize ?? m3Defaults.dragHandleSize!;
return MouseRegion(
onEnter: (PointerEnterEvent event) => handleHover(true),
onExit: (PointerExitEvent event) => handleHover(false),
child: Semantics(
label: MaterialLocalizations.of(context).modalBarrierDismissLabel,
container: true,
onTap: onSemanticsTap,
child: SizedBox(
height: kMinInteractiveDimension,
width: kMinInteractiveDimension,
child: Center(
child: Container(
height: handleSize.height,
width: handleSize.width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(handleSize.height/2),
color: MaterialStateProperty.resolveAs<Color?>(dragHandleColor, materialState)
?? MaterialStateProperty.resolveAs<Color?>(bottomSheetTheme.dragHandleColor, materialState)
?? m3Defaults.dragHandleColor,
),
),
),
),
),
);
}
}
class _BottomSheetLayoutWithSizeListener extends SingleChildRenderObjectWidget {
const _BottomSheetLayoutWithSizeListener({
required this.onChildSizeChanged,
required this.animationValue,
required this.isScrollControlled,
required this.scrollControlDisabledMaxHeightRatio,
super.child,
});
final _SizeChangeCallback<Size> onChildSizeChanged;
final double animationValue;
final bool isScrollControlled;
final double scrollControlDisabledMaxHeightRatio;
@override
_RenderBottomSheetLayoutWithSizeListener createRenderObject(BuildContext context) {
return _RenderBottomSheetLayoutWithSizeListener(
onChildSizeChanged: onChildSizeChanged,
animationValue: animationValue,
isScrollControlled: isScrollControlled,
scrollControlDisabledMaxHeightRatio: scrollControlDisabledMaxHeightRatio,
);
}
@override
void updateRenderObject(BuildContext context, _RenderBottomSheetLayoutWithSizeListener renderObject) {
renderObject.onChildSizeChanged = onChildSizeChanged;
renderObject.animationValue = animationValue;
renderObject.isScrollControlled = isScrollControlled;
renderObject.scrollControlDisabledMaxHeightRatio = scrollControlDisabledMaxHeightRatio;
}
}
class _RenderBottomSheetLayoutWithSizeListener extends RenderShiftedBox {
_RenderBottomSheetLayoutWithSizeListener({
RenderBox? child,
required _SizeChangeCallback<Size> onChildSizeChanged,
required double animationValue,
required bool isScrollControlled,
required double scrollControlDisabledMaxHeightRatio,
}) : _onChildSizeChanged = onChildSizeChanged,
_animationValue = animationValue,
_isScrollControlled = isScrollControlled,
_scrollControlDisabledMaxHeightRatio = scrollControlDisabledMaxHeightRatio,
super(child);
Size _lastSize = Size.zero;
_SizeChangeCallback<Size> get onChildSizeChanged => _onChildSizeChanged;
_SizeChangeCallback<Size> _onChildSizeChanged;
set onChildSizeChanged(_SizeChangeCallback<Size> newCallback) {
if (_onChildSizeChanged == newCallback) {
return;
}
_onChildSizeChanged = newCallback;
markNeedsLayout();
}
double get animationValue => _animationValue;
double _animationValue;
set animationValue(double newValue) {
if (_animationValue == newValue) {
return;
}
_animationValue = newValue;
markNeedsLayout();
}
bool get isScrollControlled => _isScrollControlled;
bool _isScrollControlled;
set isScrollControlled(bool newValue) {
if (_isScrollControlled == newValue) {
return;
}
_isScrollControlled = newValue;
markNeedsLayout();
}
double get scrollControlDisabledMaxHeightRatio => _scrollControlDisabledMaxHeightRatio;
double _scrollControlDisabledMaxHeightRatio;
set scrollControlDisabledMaxHeightRatio(double newValue) {
if (_scrollControlDisabledMaxHeightRatio == newValue) {
return;
}
_scrollControlDisabledMaxHeightRatio = newValue;
markNeedsLayout();
}
Size _getSize(BoxConstraints constraints) {
return constraints.constrain(constraints.biggest);
}
@override
double computeMinIntrinsicWidth(double height) {
final double width = _getSize(BoxConstraints.tightForFinite(height: height)).width;
if (width.isFinite) {
return width;
}
return 0.0;
}
@override
double computeMaxIntrinsicWidth(double height) {
final double width = _getSize(BoxConstraints.tightForFinite(height: height)).width;
if (width.isFinite) {
return width;
}
return 0.0;
}
@override
double computeMinIntrinsicHeight(double width) {
final double height = _getSize(BoxConstraints.tightForFinite(width: width)).height;
if (height.isFinite) {
return height;
}
return 0.0;
}
@override
double computeMaxIntrinsicHeight(double width) {
final double height = _getSize(BoxConstraints.tightForFinite(width: width)).height;
if (height.isFinite) {
return height;
}
return 0.0;
}
@override
Size computeDryLayout(BoxConstraints constraints) {
return _getSize(constraints);
}
BoxConstraints _getConstraintsForChild(BoxConstraints constraints) {
return BoxConstraints(
minWidth: constraints.maxWidth,
maxWidth: constraints.maxWidth,
maxHeight: isScrollControlled
? constraints.maxHeight
: constraints.maxHeight * scrollControlDisabledMaxHeightRatio,
);
}
Offset _getPositionForChild(Size size, Size childSize) {
return Offset(0.0, size.height - childSize.height * animationValue);
}
@override
void performLayout() {
size = _getSize(constraints);
if (child != null) {
final BoxConstraints childConstraints = _getConstraintsForChild(constraints);
assert(childConstraints.debugAssertIsValid(isAppliedConstraint: true));
child!.layout(childConstraints, parentUsesSize: !childConstraints.isTight);
final BoxParentData childParentData = child!.parentData! as BoxParentData;
childParentData.offset = _getPositionForChild(size, childConstraints.isTight ? childConstraints.smallest : child!.size);
final Size childSize = childConstraints.isTight ? childConstraints.smallest : child!.size;
if (_lastSize != childSize) {
_lastSize = childSize;
_onChildSizeChanged.call(_lastSize);
}
}
}
}
class _ModalBottomSheet<T> extends StatefulWidget {
const _ModalBottomSheet({
super.key,
required this.route,
this.backgroundColor,
this.elevation,
this.shape,
this.clipBehavior,
this.constraints,
this.isScrollControlled = false,
this.scrollControlDisabledMaxHeightRatio = _defaultScrollControlDisabledMaxHeightRatio,
this.enableDrag = true,
this.showDragHandle = false,
});
final ModalBottomSheetRoute<T> route;
final bool isScrollControlled;
final double scrollControlDisabledMaxHeightRatio;
final Color? backgroundColor;
final double? elevation;
final ShapeBorder? shape;
final Clip? clipBehavior;
final BoxConstraints? constraints;
final bool enableDrag;
final bool showDragHandle;
@override
_ModalBottomSheetState<T> createState() => _ModalBottomSheetState<T>();
}
class _ModalBottomSheetState<T> extends State<_ModalBottomSheet<T>> {
ParametricCurve<double> animationCurve = _modalBottomSheetCurve;
String _getRouteLabel(MaterialLocalizations localizations) {
switch (Theme.of(context).platform) {
case TargetPlatform.iOS:
case TargetPlatform.macOS:
return '';
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
return localizations.dialogLabel;
}
}
EdgeInsets _getNewClipDetails(Size topLayerSize) {
return EdgeInsets.fromLTRB(0, 0, 0, topLayerSize.height);
}
void handleDragStart(DragStartDetails details) {
// Allow the bottom sheet to track the user's finger accurately.
animationCurve = Curves.linear;
}
void handleDragEnd(DragEndDetails details, {bool? isClosing}) {
// Allow the bottom sheet to animate smoothly from its current position.
animationCurve = Split(
widget.route.animation!.value,
endCurve: _modalBottomSheetCurve,
);
}
@override
Widget build(BuildContext context) {
assert(debugCheckHasMediaQuery(context));
assert(debugCheckHasMaterialLocalizations(context));
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
final String routeLabel = _getRouteLabel(localizations);
return AnimatedBuilder(
animation: widget.route.animation!,
child: BottomSheet(
animationController: widget.route._animationController,
onClosing: () {
if (widget.route.isCurrent) {
Navigator.pop(context);
}
},
builder: widget.route.builder,
backgroundColor: widget.backgroundColor,
elevation: widget.elevation,
shape: widget.shape,
clipBehavior: widget.clipBehavior,
constraints: widget.constraints,
enableDrag: widget.enableDrag,
showDragHandle: widget.showDragHandle,
onDragStart: handleDragStart,
onDragEnd: handleDragEnd,
),
builder: (BuildContext context, Widget? child) {
final double animationValue = animationCurve.transform(
widget.route.animation!.value,
);
return Semantics(
scopesRoute: true,
namesRoute: true,
label: routeLabel,
explicitChildNodes: true,
child: ClipRect(
child: _BottomSheetLayoutWithSizeListener(
onChildSizeChanged: (Size size) {
widget.route._didChangeBarrierSemanticsClip(
_getNewClipDetails(size),
);
},
animationValue: animationValue,
isScrollControlled: widget.isScrollControlled,
scrollControlDisabledMaxHeightRatio: widget.scrollControlDisabledMaxHeightRatio,
child: child,
),
),
);
},
);
}
}
/// A route that represents a Material Design modal bottom sheet.
///
/// {@template flutter.material.ModalBottomSheetRoute}
/// A modal bottom sheet is an alternative to a menu or a dialog and prevents
/// the user from interacting with the rest of the app.
///
/// A closely related widget is a persistent bottom sheet, which shows
/// information that supplements the primary content of the app without
/// preventing the user from interacting with the app. Persistent bottom sheets
/// can be created and displayed with the [showBottomSheet] function or the
/// [ScaffoldState.showBottomSheet] method.
///
/// The [isScrollControlled] parameter specifies whether this is a route for
/// a bottom sheet that will utilize [DraggableScrollableSheet]. Consider
/// setting this parameter to true if this bottom sheet has
/// a scrollable child, such as a [ListView] or a [GridView],
/// to have the bottom sheet be draggable.
///
/// The [isDismissible] parameter specifies whether the bottom sheet will be
/// dismissed when user taps on the scrim.
///
/// The [enableDrag] parameter specifies whether the bottom sheet can be
/// dragged up and down and dismissed by swiping downwards.
///
/// The [useSafeArea] parameter specifies whether the sheet will avoid system
/// intrusions on the top, left, and right. If false, no [SafeArea] is added;
/// and [MediaQuery.removePadding] is applied to the top,
/// so that system intrusions at the top will not be avoided by a [SafeArea]
/// inside the bottom sheet either.
/// Defaults to false.
///
/// The optional [backgroundColor], [elevation], [shape], [clipBehavior],
/// [constraints] and [transitionAnimationController]
/// parameters can be passed in to customize the appearance and behavior of
/// modal bottom sheets (see the documentation for these on [BottomSheet]
/// for more details).
///
/// The [transitionAnimationController] controls the bottom sheet's entrance and
/// exit animations. It's up to the owner of the controller to call
/// [AnimationController.dispose] when the controller is no longer needed.
///
/// The optional `settings` parameter sets the [RouteSettings] of the modal bottom sheet
/// sheet. This is particularly useful in the case that a user wants to observe
/// [PopupRoute]s within a [NavigatorObserver].
/// {@endtemplate}
///
/// {@macro flutter.widgets.RawDialogRoute}
///
/// See also:
///
/// * [showModalBottomSheet], which is a way to display a ModalBottomSheetRoute.
/// * [BottomSheet], which becomes the parent of the widget returned by the
/// function passed as the `builder` argument to [showModalBottomSheet].
/// * [showBottomSheet] and [ScaffoldState.showBottomSheet], for showing
/// non-modal bottom sheets.
/// * [DraggableScrollableSheet], creates a bottom sheet that grows
/// and then becomes scrollable once it reaches its maximum size.
/// * [DisplayFeatureSubScreen], which documents the specifics of how
/// [DisplayFeature]s can split the screen into sub-screens.
/// * The Material 2 spec at <https://m2.material.io/components/sheets-bottom>.
/// * The Material 3 spec at <https://m3.material.io/components/bottom-sheets/overview>.
class ModalBottomSheetRoute<T> extends PopupRoute<T> {
/// A modal bottom sheet route.
ModalBottomSheetRoute({
required this.builder,
this.capturedThemes,
this.barrierLabel,
this.barrierOnTapHint,
this.backgroundColor,
this.elevation,
this.shape,
this.clipBehavior,
this.constraints,
this.modalBarrierColor,
this.isDismissible = true,
this.enableDrag = true,
this.showDragHandle,
required this.isScrollControlled,
this.scrollControlDisabledMaxHeightRatio = _defaultScrollControlDisabledMaxHeightRatio,
super.settings,
this.transitionAnimationController,
this.anchorPoint,
this.useSafeArea = false,
});
/// A builder for the contents of the sheet.
///
/// The bottom sheet will wrap the widget produced by this builder in a
/// [Material] widget.
final WidgetBuilder builder;
/// Stores a list of captured [InheritedTheme]s that are wrapped around the
/// bottom sheet.
///
/// Consider setting this attribute when the [ModalBottomSheetRoute]
/// is created through [Navigator.push] and its friends.
final CapturedThemes? capturedThemes;
/// Specifies whether this is a route for a bottom sheet that will utilize
/// [DraggableScrollableSheet].
///
/// Consider setting this parameter to true if this bottom sheet has
/// a scrollable child, such as a [ListView] or a [GridView],
/// to have the bottom sheet be draggable.
final bool isScrollControlled;
/// The max height constraint ratio for the bottom sheet
/// when [isScrollControlled] set to false,
/// no ratio will be applied when [isScrollControlled] set to true.
///
/// Defaults to 9 / 16.
final double scrollControlDisabledMaxHeightRatio;
/// The bottom sheet's background color.
///
/// Defines the bottom sheet's [Material.color].
///
/// If this property is not provided, it falls back to [Material]'s default.
final Color? backgroundColor;
/// The z-coordinate at which to place this material relative to its parent.
///
/// This controls the size of the shadow below the material.
///
/// Defaults to 0, must not be negative.
final double? elevation;
/// The shape of the bottom sheet.
///
/// Defines the bottom sheet's [Material.shape].
///
/// If this property is not provided, it falls back to [Material]'s default.
final ShapeBorder? shape;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defines the bottom sheet's [Material.clipBehavior].
///
/// Use this property to enable clipping of content when the bottom sheet has
/// a custom [shape] and the content can extend past this shape. For example,
/// a bottom sheet with rounded corners and an edge-to-edge [Image] at the
/// top.
///
/// If this property is null, the [BottomSheetThemeData.clipBehavior] of
/// [ThemeData.bottomSheetTheme] is used. If that's null, the behavior defaults to [Clip.none]
/// will be [Clip.none].
final Clip? clipBehavior;
/// Defines minimum and maximum sizes for a [BottomSheet].
///
/// If null, the ambient [ThemeData.bottomSheetTheme]'s
/// [BottomSheetThemeData.constraints] will be used. If that
/// is null and [ThemeData.useMaterial3] is true, then the bottom sheet
/// will have a max width of 640dp. If [ThemeData.useMaterial3] is false, then
/// the bottom sheet's size will be constrained by its parent
/// (usually a [Scaffold]). In this case, consider limiting the width by
/// setting smaller constraints for large screens.
///
/// If constraints are specified (either in this property or in the
/// theme), the bottom sheet will be aligned to the bottom-center of
/// the available space. Otherwise, no alignment is applied.
final BoxConstraints? constraints;
/// Specifies the color of the modal barrier that darkens everything below the
/// bottom sheet.
///
/// Defaults to `Colors.black54` if not provided.
final Color? modalBarrierColor;
/// Specifies whether the bottom sheet will be dismissed
/// when user taps on the scrim.
///
/// If true, the bottom sheet will be dismissed when user taps on the scrim.
///
/// Defaults to true.
final bool isDismissible;
/// Specifies whether the bottom sheet can be dragged up and down
/// and dismissed by swiping downwards.
///
/// If true, the bottom sheet can be dragged up and down and dismissed by
/// swiping downwards.
///
/// This applies to the content below the drag handle, if showDragHandle is true.
///
/// Defaults is true.
final bool enableDrag;
/// Specifies whether a drag handle is shown.
///
/// The drag handle appears at the top of the bottom sheet. The default color is
/// [ColorScheme.onSurfaceVariant] with an opacity of 0.4 and can be customized
/// using dragHandleColor. The default size is `Size(32,4)` and can be customized
/// with dragHandleSize.
///
/// If null, then the value of [BottomSheetThemeData.showDragHandle] is used. If
/// that is also null, defaults to false.
final bool? showDragHandle;
/// The animation controller that controls the bottom sheet's entrance and
/// exit animations.
///
/// The BottomSheet widget will manipulate the position of this animation, it
/// is not just a passive observer.
final AnimationController? transitionAnimationController;
/// {@macro flutter.widgets.DisplayFeatureSubScreen.anchorPoint}
final Offset? anchorPoint;
/// Whether to avoid system intrusions on the top, left, and right.
///
/// If true, a [SafeArea] is inserted to keep the bottom sheet away from
/// system intrusions at the top, left, and right sides of the screen.
///
/// If false, the bottom sheet will extend through any system intrusions
/// at the top, left, and right.
///
/// If false, then moreover [MediaQuery.removePadding] will be used
/// to remove top padding, so that a [SafeArea] widget inside the bottom
/// sheet will have no effect at the top edge. If this is undesired, consider
/// setting [useSafeArea] to true. Alternatively, wrap the [SafeArea] in a
/// [MediaQuery] that restates an ambient [MediaQueryData] from outside [builder].
///
/// In either case, the bottom sheet extends all the way to the bottom of
/// the screen, including any system intrusions.
///
/// The default is false.
final bool useSafeArea;
/// {@template flutter.material.ModalBottomSheetRoute.barrierOnTapHint}
/// The semantic hint text that informs users what will happen if they
/// tap on the widget. Announced in the format of 'Double tap to ...'.
///
/// If the field is null, the default hint will be used, which results in
/// announcement of 'Double tap to activate'.
/// {@endtemplate}
///
/// See also:
///
/// * [barrierDismissible], which controls the behavior of the barrier when
/// tapped.
/// * [ModalBarrier], which uses this field as onTapHint when it has an onTap action.
final String? barrierOnTapHint;
final ValueNotifier<EdgeInsets> _clipDetailsNotifier = ValueNotifier<EdgeInsets>(EdgeInsets.zero);
@override
void dispose() {
_clipDetailsNotifier.dispose();
super.dispose();
}
/// Updates the details regarding how the [SemanticsNode.rect] (focus) of
/// the barrier for this [ModalBottomSheetRoute] should be clipped.
///
/// returns true if the clipDetails did change and false otherwise.
bool _didChangeBarrierSemanticsClip(EdgeInsets newClipDetails) {
if (_clipDetailsNotifier.value == newClipDetails) {
return false;
}
_clipDetailsNotifier.value = newClipDetails;
return true;
}
@override
Duration get transitionDuration => _bottomSheetEnterDuration;
@override
Duration get reverseTransitionDuration => _bottomSheetExitDuration;
@override
bool get barrierDismissible => isDismissible;
@override
final String? barrierLabel;
@override
Color get barrierColor => modalBarrierColor ?? Colors.black54;
AnimationController? _animationController;
@override
AnimationController createAnimationController() {
assert(_animationController == null);
if (transitionAnimationController != null) {
_animationController = transitionAnimationController;
willDisposeAnimationController = false;
} else {
_animationController = BottomSheet.createAnimationController(navigator!);
}
return _animationController!;
}
@override
Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
final Widget content = DisplayFeatureSubScreen(
anchorPoint: anchorPoint,
child: Builder(
builder: (BuildContext context) {
final BottomSheetThemeData sheetTheme = Theme.of(context).bottomSheetTheme;
final BottomSheetThemeData defaults = Theme.of(context).useMaterial3 ? _BottomSheetDefaultsM3(context) : const BottomSheetThemeData();
return _ModalBottomSheet<T>(
route: this,
backgroundColor: backgroundColor ?? sheetTheme.modalBackgroundColor ?? sheetTheme.backgroundColor ?? defaults.backgroundColor,
elevation: elevation ?? sheetTheme.modalElevation ?? sheetTheme.elevation ?? defaults.modalElevation,
shape: shape,
clipBehavior: clipBehavior,
constraints: constraints,
isScrollControlled: isScrollControlled,
scrollControlDisabledMaxHeightRatio: scrollControlDisabledMaxHeightRatio,
enableDrag: enableDrag,
showDragHandle: showDragHandle ?? (enableDrag && (sheetTheme.showDragHandle ?? false)),
);
},
),
);
final Widget bottomSheet = useSafeArea
? SafeArea(bottom: false, child: content)
: MediaQuery.removePadding(
context: context,
removeTop: true,
child: content,
);
return capturedThemes?.wrap(bottomSheet) ?? bottomSheet;
}
@override
Widget buildModalBarrier() {
if (barrierColor.alpha != 0 && !offstage) { // changedInternalState is called if barrierColor or offstage updates
assert(barrierColor != barrierColor.withOpacity(0.0));
final Animation<Color?> color = animation!.drive(
ColorTween(
begin: barrierColor.withOpacity(0.0),
end: barrierColor, // changedInternalState is called if barrierColor updates
).chain(CurveTween(curve: barrierCurve)), // changedInternalState is called if barrierCurve updates
);
return AnimatedModalBarrier(
color: color,
dismissible: barrierDismissible, // changedInternalState is called if barrierDismissible updates
semanticsLabel: barrierLabel, // changedInternalState is called if barrierLabel updates
barrierSemanticsDismissible: semanticsDismissible,
clipDetailsNotifier: _clipDetailsNotifier,
semanticsOnTapHint: barrierOnTapHint,
);
} else {
return ModalBarrier(
dismissible: barrierDismissible, // changedInternalState is called if barrierDismissible updates
semanticsLabel: barrierLabel, // changedInternalState is called if barrierLabel updates
barrierSemanticsDismissible: semanticsDismissible,
clipDetailsNotifier: _clipDetailsNotifier,
semanticsOnTapHint: barrierOnTapHint,
);
}
}
}
/// Shows a modal Material Design bottom sheet.
///
/// {@macro flutter.material.ModalBottomSheetRoute}
///
/// {@macro flutter.widgets.RawDialogRoute}
///
/// The `context` argument is used to look up the [Navigator] and [Theme] for
/// the bottom sheet. It is only used when the method is called. Its
/// corresponding widget can be safely removed from the tree before the bottom
/// sheet is closed.
///
/// The `useRootNavigator` parameter ensures that the root navigator is used to
/// display the [BottomSheet] when set to `true`. This is useful in the case
/// that a modal [BottomSheet] needs to be displayed above all other content
/// but the caller is inside another [Navigator].
///
/// Returns a `Future` that resolves to the value (if any) that was passed to
/// [Navigator.pop] when the modal bottom sheet was closed.
///
/// The 'barrierLabel' parameter can be used to set a custom barrierlabel.
/// Will default to modalBarrierDismissLabel of context if not set.
///
/// {@tool dartpad}
/// This example demonstrates how to use [showModalBottomSheet] to display a
/// bottom sheet that obscures the content behind it when a user taps a button.
/// It also demonstrates how to close the bottom sheet using the [Navigator]
/// when a user taps on a button inside the bottom sheet.
///
/// ** See code in examples/api/lib/material/bottom_sheet/show_modal_bottom_sheet.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This sample shows the creation of [showModalBottomSheet], as described in:
/// https://m3.material.io/components/bottom-sheets/overview
///
/// ** See code in examples/api/lib/material/bottom_sheet/show_modal_bottom_sheet.1.dart **
/// {@end-tool}
///
/// See also:
///
/// * [BottomSheet], which becomes the parent of the widget returned by the
/// function passed as the `builder` argument to [showModalBottomSheet].
/// * [showBottomSheet] and [ScaffoldState.showBottomSheet], for showing
/// non-modal bottom sheets.
/// * [DraggableScrollableSheet], creates a bottom sheet that grows
/// and then becomes scrollable once it reaches its maximum size.
/// * [DisplayFeatureSubScreen], which documents the specifics of how
/// [DisplayFeature]s can split the screen into sub-screens.
/// * The Material 2 spec at <https://m2.material.io/components/sheets-bottom>.
/// * The Material 3 spec at <https://m3.material.io/components/bottom-sheets/overview>.
Future<T?> showModalBottomSheet<T>({
required BuildContext context,
required WidgetBuilder builder,
Color? backgroundColor,
String? barrierLabel,
double? elevation,
ShapeBorder? shape,
Clip? clipBehavior,
BoxConstraints? constraints,
Color? barrierColor,
bool isScrollControlled = false,
double scrollControlDisabledMaxHeightRatio = _defaultScrollControlDisabledMaxHeightRatio,
bool useRootNavigator = false,
bool isDismissible = true,
bool enableDrag = true,
bool? showDragHandle,
bool useSafeArea = false,
RouteSettings? routeSettings,
AnimationController? transitionAnimationController,
Offset? anchorPoint,
}) {
assert(debugCheckHasMediaQuery(context));
assert(debugCheckHasMaterialLocalizations(context));
final NavigatorState navigator = Navigator.of(context, rootNavigator: useRootNavigator);
final MaterialLocalizations localizations = MaterialLocalizations.of(context);
return navigator.push(ModalBottomSheetRoute<T>(
builder: builder,
capturedThemes: InheritedTheme.capture(from: context, to: navigator.context),
isScrollControlled: isScrollControlled,
scrollControlDisabledMaxHeightRatio: scrollControlDisabledMaxHeightRatio,
barrierLabel: barrierLabel ?? localizations.scrimLabel,
barrierOnTapHint: localizations.scrimOnTapHint(localizations.bottomSheetLabel),
backgroundColor: backgroundColor,
elevation: elevation,
shape: shape,
clipBehavior: clipBehavior,
constraints: constraints,
isDismissible: isDismissible,
modalBarrierColor: barrierColor ?? Theme.of(context).bottomSheetTheme.modalBarrierColor,
enableDrag: enableDrag,
showDragHandle: showDragHandle,
settings: routeSettings,
transitionAnimationController: transitionAnimationController,
anchorPoint: anchorPoint,
useSafeArea: useSafeArea,
));
}
/// Shows a Material Design bottom sheet in the nearest [Scaffold] ancestor. To
/// show a persistent bottom sheet, use the [Scaffold.bottomSheet].
///
/// Returns a controller that can be used to close and otherwise manipulate the
/// bottom sheet.
///
/// The optional [backgroundColor], [elevation], [shape], [clipBehavior],
/// [constraints] and [transitionAnimationController]
/// parameters can be passed in to customize the appearance and behavior of
/// persistent bottom sheets (see the documentation for these on [BottomSheet]
/// for more details).
///
/// The [enableDrag] parameter specifies whether the bottom sheet can be
/// dragged up and down and dismissed by swiping downwards.
///
/// To rebuild the bottom sheet (e.g. if it is stateful), call
/// [PersistentBottomSheetController.setState] on the controller returned by
/// this method.
///
/// The new bottom sheet becomes a [LocalHistoryEntry] for the enclosing
/// [ModalRoute] and a back button is added to the app bar of the [Scaffold]
/// that closes the bottom sheet.
///
/// To create a persistent bottom sheet that is not a [LocalHistoryEntry] and
/// does not add a back button to the enclosing Scaffold's app bar, use the
/// [Scaffold.bottomSheet] constructor parameter.
///
/// A closely related widget is a modal bottom sheet, which is an alternative
/// to a menu or a dialog and prevents the user from interacting with the rest
/// of the app. Modal bottom sheets can be created and displayed with the
/// [showModalBottomSheet] function.
///
/// The `context` argument is used to look up the [Scaffold] for the bottom
/// sheet. It is only used when the method is called. Its corresponding widget
/// can be safely removed from the tree before the bottom sheet is closed.
///
/// See also:
///
/// * [BottomSheet], which becomes the parent of the widget returned by the
/// `builder`.
/// * [showModalBottomSheet], which can be used to display a modal bottom
/// sheet.
/// * [Scaffold.of], for information about how to obtain the [BuildContext].
/// * The Material 2 spec at <https://m2.material.io/components/sheets-bottom>.
/// * The Material 3 spec at <https://m3.material.io/components/bottom-sheets/overview>.
PersistentBottomSheetController showBottomSheet({
required BuildContext context,
required WidgetBuilder builder,
Color? backgroundColor,
double? elevation,
ShapeBorder? shape,
Clip? clipBehavior,
BoxConstraints? constraints,
bool? enableDrag,
bool? showDragHandle,
AnimationController? transitionAnimationController,
}) {
assert(debugCheckHasScaffold(context));
return Scaffold.of(context).showBottomSheet(
builder,
backgroundColor: backgroundColor,
elevation: elevation,
shape: shape,
clipBehavior: clipBehavior,
constraints: constraints,
enableDrag: enableDrag,
showDragHandle: showDragHandle,
transitionAnimationController: transitionAnimationController,
);
}
class _BottomSheetGestureDetector extends StatelessWidget {
const _BottomSheetGestureDetector({
required this.child,
required this.onVerticalDragStart,
required this.onVerticalDragUpdate,
required this.onVerticalDragEnd,
});
final Widget child;
final GestureDragStartCallback onVerticalDragStart;
final GestureDragUpdateCallback onVerticalDragUpdate;
final GestureDragEndCallback onVerticalDragEnd;
@override
Widget build(BuildContext context) {
return RawGestureDetector(
excludeFromSemantics: true,
gestures: <Type, GestureRecognizerFactory<GestureRecognizer>>{
VerticalDragGestureRecognizer : GestureRecognizerFactoryWithHandlers<VerticalDragGestureRecognizer>(
() => VerticalDragGestureRecognizer(debugOwner: this),
(VerticalDragGestureRecognizer instance) {
instance
..onStart = onVerticalDragStart
..onUpdate = onVerticalDragUpdate
..onEnd = onVerticalDragEnd
..onlyAcceptDragOnThreshold = true;
},
),
},
child: child,
);
}
}
// BEGIN GENERATED TOKEN PROPERTIES - BottomSheet
// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
// dev/tools/gen_defaults/bin/gen_defaults.dart.
class _BottomSheetDefaultsM3 extends BottomSheetThemeData {
_BottomSheetDefaultsM3(this.context)
: super(
elevation: 1.0,
modalElevation: 1.0,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(28.0))),
constraints: const BoxConstraints(maxWidth: 640),
);
final BuildContext context;
late final ColorScheme _colors = Theme.of(context).colorScheme;
@override
Color? get backgroundColor => _colors.surfaceContainerLow;
@override
Color? get surfaceTintColor => Colors.transparent;
@override
Color? get shadowColor => Colors.transparent;
@override
Color? get dragHandleColor => _colors.onSurfaceVariant;
@override
Size? get dragHandleSize => const Size(32, 4);
@override
BoxConstraints? get constraints => const BoxConstraints(maxWidth: 640.0);
}
// END GENERATED TOKEN PROPERTIES - BottomSheet
| flutter/packages/flutter/lib/src/material/bottom_sheet.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/bottom_sheet.dart",
"repo_id": "flutter",
"token_count": 16258
} | 621 |
// 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' show clampDouble;
import 'package:flutter/widgets.dart';
import 'chip.dart';
import 'chip_theme.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'debug.dart';
import 'material_state.dart';
import 'text_theme.dart';
import 'theme.dart';
import 'theme_data.dart';
enum _ChipVariant { flat, elevated }
/// A Material Design choice chip.
///
/// [ChoiceChip]s represent a single choice from a set. Choice chips contain
/// related descriptive text or categories.
///
/// Requires one of its ancestors to be a [Material] widget.
///
/// {@tool dartpad}
/// This example shows how to create [ChoiceChip]s with [onSelected]. When the
/// user taps, the chip will be selected.
///
/// ** See code in examples/api/lib/material/choice_chip/choice_chip.0.dart **
/// {@end-tool}
///
/// ## Material Design 3
///
/// [ChoiceChip] can be used for single select Filter chips from
/// Material Design 3. If [ThemeData.useMaterial3] is true, then [ChoiceChip]
/// will be styled to match the Material Design 3 specification for Filter
/// chips. Use [FilterChip] for multiple select Filter chips.
///
/// See also:
///
/// * [Chip], a chip that displays information and can be deleted.
/// * [InputChip], a chip that represents a complex piece of information, such
/// as an entity (person, place, or thing) or conversational text, in a
/// compact form.
/// * [FilterChip], uses tags or descriptive words as a way to filter content.
/// * [ActionChip], represents an action related to primary content.
/// * [CircleAvatar], which shows images or initials of people.
/// * [Wrap], A widget that displays its children in multiple horizontal or
/// vertical runs.
/// * <https://material.io/design/components/chips.html>
class ChoiceChip extends StatelessWidget
implements
ChipAttributes,
SelectableChipAttributes,
CheckmarkableChipAttributes,
DisabledChipAttributes {
/// Create a chip that acts like a radio button.
///
/// The [label], [selected], [autofocus], and [clipBehavior] arguments must
/// not be null. When [onSelected] is null, the [ChoiceChip] will be disabled.
/// The [pressElevation] and [elevation] must be null or non-negative. Typically,
/// [pressElevation] is greater than [elevation].
const ChoiceChip({
super.key,
this.avatar,
required this.label,
this.labelStyle,
this.labelPadding,
this.onSelected,
this.pressElevation,
required this.selected,
this.selectedColor,
this.disabledColor,
this.tooltip,
this.side,
this.shape,
this.clipBehavior = Clip.none,
this.focusNode,
this.autofocus = false,
this.color,
this.backgroundColor,
this.padding,
this.visualDensity,
this.materialTapTargetSize,
this.elevation,
this.shadowColor,
this.surfaceTintColor,
this.iconTheme,
this.selectedShadowColor,
this.showCheckmark,
this.checkmarkColor,
this.avatarBorder = const CircleBorder(),
this.avatarBoxConstraints,
}) : assert(pressElevation == null || pressElevation >= 0.0),
assert(elevation == null || elevation >= 0.0),
_chipVariant = _ChipVariant.flat;
/// Create an elevated chip that acts like a radio button.
///
/// The [label], [selected], [autofocus], and [clipBehavior] arguments must
/// not be null. When [onSelected] is null, the [ChoiceChip] will be disabled.
/// The [pressElevation] and [elevation] must be null or non-negative. Typically,
/// [pressElevation] is greater than [elevation].
const ChoiceChip.elevated({
super.key,
this.avatar,
required this.label,
this.labelStyle,
this.labelPadding,
this.onSelected,
this.pressElevation,
required this.selected,
this.selectedColor,
this.disabledColor,
this.tooltip,
this.side,
this.shape,
this.clipBehavior = Clip.none,
this.focusNode,
this.autofocus = false,
this.color,
this.backgroundColor,
this.padding,
this.visualDensity,
this.materialTapTargetSize,
this.elevation,
this.shadowColor,
this.surfaceTintColor,
this.iconTheme,
this.selectedShadowColor,
this.showCheckmark,
this.checkmarkColor,
this.avatarBorder = const CircleBorder(),
this.avatarBoxConstraints,
}) : assert(pressElevation == null || pressElevation >= 0.0),
assert(elevation == null || elevation >= 0.0),
_chipVariant = _ChipVariant.elevated;
@override
final Widget? avatar;
@override
final Widget label;
@override
final TextStyle? labelStyle;
@override
final EdgeInsetsGeometry? labelPadding;
@override
final ValueChanged<bool>? onSelected;
@override
final double? pressElevation;
@override
final bool selected;
@override
final Color? disabledColor;
@override
final Color? selectedColor;
@override
final String? tooltip;
@override
final BorderSide? side;
@override
final OutlinedBorder? shape;
@override
final Clip clipBehavior;
@override
final FocusNode? focusNode;
@override
final bool autofocus;
@override
final MaterialStateProperty<Color?>? color;
@override
final Color? backgroundColor;
@override
final EdgeInsetsGeometry? padding;
@override
final VisualDensity? visualDensity;
@override
final MaterialTapTargetSize? materialTapTargetSize;
@override
final double? elevation;
@override
final Color? shadowColor;
@override
final Color? surfaceTintColor;
@override
final Color? selectedShadowColor;
@override
final bool? showCheckmark;
@override
final Color? checkmarkColor;
@override
final ShapeBorder avatarBorder;
@override
final IconThemeData? iconTheme;
@override
final BoxConstraints? avatarBoxConstraints;
@override
bool get isEnabled => onSelected != null;
final _ChipVariant _chipVariant;
@override
Widget build(BuildContext context) {
assert(debugCheckHasMaterial(context));
final ChipThemeData chipTheme = ChipTheme.of(context);
final ChipThemeData? defaults = Theme.of(context).useMaterial3
? _ChoiceChipDefaultsM3(context, isEnabled, selected, _chipVariant)
: null;
return RawChip(
defaultProperties: defaults,
avatar: avatar,
label: label,
labelStyle: labelStyle ?? (selected ? chipTheme.secondaryLabelStyle : null),
labelPadding: labelPadding,
onSelected: onSelected,
pressElevation: pressElevation,
selected: selected,
showCheckmark: showCheckmark ?? chipTheme.showCheckmark ?? Theme.of(context).useMaterial3,
checkmarkColor: checkmarkColor,
tooltip: tooltip,
side: side,
shape: shape,
clipBehavior: clipBehavior,
focusNode: focusNode,
autofocus: autofocus,
disabledColor: disabledColor,
selectedColor: selectedColor ?? chipTheme.secondarySelectedColor,
color: color,
backgroundColor: backgroundColor,
padding: padding,
visualDensity: visualDensity,
isEnabled: isEnabled,
materialTapTargetSize: materialTapTargetSize,
elevation: elevation,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
selectedShadowColor: selectedShadowColor,
avatarBorder: avatarBorder,
iconTheme: iconTheme,
avatarBoxConstraints: avatarBoxConstraints,
);
}
}
// BEGIN GENERATED TOKEN PROPERTIES - ChoiceChip
// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
// dev/tools/gen_defaults/bin/gen_defaults.dart.
class _ChoiceChipDefaultsM3 extends ChipThemeData {
_ChoiceChipDefaultsM3(
this.context,
this.isEnabled,
this.isSelected,
this._chipVariant,
) : super(
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(8.0))),
showCheckmark: true,
);
final BuildContext context;
final bool isEnabled;
final bool isSelected;
final _ChipVariant _chipVariant;
late final ColorScheme _colors = Theme.of(context).colorScheme;
late final TextTheme _textTheme = Theme.of(context).textTheme;
@override
double? get elevation => _chipVariant == _ChipVariant.flat
? 0.0
: isEnabled ? 1.0 : 0.0;
@override
double? get pressElevation => 1.0;
@override
TextStyle? get labelStyle => _textTheme.labelLarge?.copyWith(
color: isEnabled
? isSelected
? _colors.onSecondaryContainer
: _colors.onSurfaceVariant
: _colors.onSurface,
);
@override
MaterialStateProperty<Color?>? get color =>
MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected) && states.contains(MaterialState.disabled)) {
return _chipVariant == _ChipVariant.flat
? _colors.onSurface.withOpacity(0.12)
: _colors.onSurface.withOpacity(0.12);
}
if (states.contains(MaterialState.disabled)) {
return _chipVariant == _ChipVariant.flat
? null
: _colors.onSurface.withOpacity(0.12);
}
if (states.contains(MaterialState.selected)) {
return _chipVariant == _ChipVariant.flat
? _colors.secondaryContainer
: _colors.secondaryContainer;
}
return _chipVariant == _ChipVariant.flat
? null
: _colors.surfaceContainerLow;
});
@override
Color? get shadowColor => _chipVariant == _ChipVariant.flat
? Colors.transparent
: _colors.shadow;
@override
Color? get surfaceTintColor => Colors.transparent;
@override
Color? get checkmarkColor => isEnabled
? isSelected
? _colors.onSecondaryContainer
: _colors.primary
: _colors.onSurface;
@override
Color? get deleteIconColor => isEnabled
? isSelected
? _colors.onSecondaryContainer
: _colors.onSurfaceVariant
: _colors.onSurface;
@override
BorderSide? get side => _chipVariant == _ChipVariant.flat && !isSelected
? isEnabled
? BorderSide(color: _colors.outline)
: BorderSide(color: _colors.onSurface.withOpacity(0.12))
: const BorderSide(color: Colors.transparent);
@override
IconThemeData? get iconTheme => IconThemeData(
color: isEnabled
? isSelected
? _colors.onSecondaryContainer
: _colors.primary
: _colors.onSurface,
size: 18.0,
);
@override
EdgeInsetsGeometry? get padding => const EdgeInsets.all(8.0);
/// The label padding of the chip scales with the font size specified in the
/// [labelStyle], and the system font size settings that scale font sizes
/// globally.
///
/// The chip at effective font size 14.0 starts with 8px on each side and as
/// the font size scales up to closer to 28.0, the label padding is linearly
/// interpolated from 8px to 4px. Once the label has a font size of 2 or
/// higher, label padding remains 4px.
@override
EdgeInsetsGeometry? get labelPadding {
final double fontSize = labelStyle?.fontSize ?? 14.0;
final double fontSizeRatio = MediaQuery.textScalerOf(context).scale(fontSize) / 14.0;
return EdgeInsets.lerp(
const EdgeInsets.symmetric(horizontal: 8.0),
const EdgeInsets.symmetric(horizontal: 4.0),
clampDouble(fontSizeRatio - 1.0, 0.0, 1.0),
)!;
}
}
// END GENERATED TOKEN PROPERTIES - ChoiceChip
| flutter/packages/flutter/lib/src/material/choice_chip.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/choice_chip.dart",
"repo_id": "flutter",
"token_count": 4076
} | 622 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' show clampDouble, lerpDouble;
import 'package:flutter/cupertino.dart';
import 'color_scheme.dart';
import 'colors.dart';
import 'debug.dart';
import 'dialog_theme.dart';
import 'ink_well.dart';
import 'material.dart';
import 'material_localizations.dart';
import 'text_theme.dart';
import 'theme.dart';
import 'theme_data.dart';
// Examples can assume:
// enum Department { treasury, state }
// late BuildContext context;
const EdgeInsets _defaultInsetPadding = EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0);
/// A Material Design dialog.
///
/// This dialog widget does not have any opinion about the contents of the
/// dialog. Rather than using this widget directly, consider using [AlertDialog]
/// or [SimpleDialog], which implement specific kinds of Material Design
/// dialogs.
///
/// {@tool dartpad}
/// This sample shows the creation of [Dialog] and [Dialog.fullscreen] widgets.
///
/// ** See code in examples/api/lib/material/dialog/dialog.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [AlertDialog], for dialogs that have a message and some buttons.
/// * [SimpleDialog], for dialogs that offer a variety of options.
/// * [showDialog], which actually displays the dialog and returns its result.
/// * <https://material.io/design/components/dialogs.html>
class Dialog extends StatelessWidget {
/// Creates a dialog.
///
/// Typically used in conjunction with [showDialog].
const Dialog({
super.key,
this.backgroundColor,
this.elevation,
this.shadowColor,
this.surfaceTintColor,
this.insetAnimationDuration = const Duration(milliseconds: 100),
this.insetAnimationCurve = Curves.decelerate,
this.insetPadding,
this.clipBehavior = Clip.none,
this.shape,
this.alignment,
this.child,
}) : assert(elevation == null || elevation >= 0.0),
_fullscreen = false;
/// Creates a fullscreen dialog.
///
/// Typically used in conjunction with [showDialog].
const Dialog.fullscreen({
super.key,
this.backgroundColor,
this.insetAnimationDuration = Duration.zero,
this.insetAnimationCurve = Curves.decelerate,
this.child,
}) : elevation = 0,
shadowColor = null,
surfaceTintColor = null,
insetPadding = EdgeInsets.zero,
clipBehavior = Clip.none,
shape = null,
alignment = null,
_fullscreen = true;
/// {@template flutter.material.dialog.backgroundColor}
/// The background color of the surface of this [Dialog].
///
/// This sets the [Material.color] on this [Dialog]'s [Material].
///
/// If `null`, [ColorScheme.surfaceContainerHigh] is used in Material 3.
/// {@endtemplate}
final Color? backgroundColor;
/// {@template flutter.material.dialog.elevation}
/// The z-coordinate of this [Dialog].
///
/// Controls how far above the parent the dialog will appear. Elevation is
/// represented by a drop shadow if [shadowColor] is non null,
/// and a surface tint overlay on the background color if [surfaceTintColor] is
/// non null.
///
/// If null then [DialogTheme.elevation] is used, and if that is null then
/// the elevation will match the Material Design specification for Dialogs.
///
/// See also:
/// * [Material.elevation], which describes how [elevation] effects the
/// drop shadow or surface tint overlay.
/// * [shadowColor], color of the drop shadow used to indicate the elevation.
/// * [surfaceTintColor], color of an overlay on top of the background
/// color used to indicate the elevation.
/// * <https://m3.material.io/components/dialogs/overview>, the Material
/// Design specification for dialogs.
/// {@endtemplate}
final double? elevation;
/// {@template flutter.material.dialog.shadowColor}
/// The color used to paint a drop shadow under the dialog's [Material],
/// which reflects the dialog's [elevation].
///
/// If null and [ThemeData.useMaterial3] is true then no drop shadow will
/// be rendered.
///
/// If null and [ThemeData.useMaterial3] is false then it will default to
/// [ThemeData.shadowColor].
///
/// See also:
/// * [Material.shadowColor], which describes how the drop shadow is painted.
/// * [elevation], which affects how the drop shadow is painted.
/// * [surfaceTintColor], which can be used to indicate elevation through
/// tinting the background color.
/// {@endtemplate}
final Color? shadowColor;
/// {@template flutter.material.dialog.surfaceTintColor}
/// The color used as a surface tint overlay on the dialog's background color,
/// which reflects the dialog's [elevation].
///
/// If [ThemeData.useMaterial3] is false property has no effect.
///
/// This is not recommended for use. [Material 3 spec](https://m3.material.io/styles/color/the-color-system/color-roles)
/// introduced a set of tone-based surfaces and surface containers in its [ColorScheme],
/// which provide more flexibility. The intention is to eventually remove surface tint color from
/// the framework.
///
/// defaults to [Colors.transparent].
///
/// To disable this feature, set [surfaceTintColor] to [Colors.transparent].
///
/// See also:
/// * [Material.surfaceTintColor], which describes how the surface tint will
/// be applied to the background color of the dialog.
/// * [elevation], which affects the opacity of the surface tint.
/// * [shadowColor], which can be used to indicate elevation through
/// a drop shadow.
/// {@endtemplate}
final Color? surfaceTintColor;
/// {@template flutter.material.dialog.insetAnimationDuration}
/// The duration of the animation to show when the system keyboard intrudes
/// into the space that the dialog is placed in.
///
/// Defaults to 100 milliseconds when [Dialog] is used, and [Duration.zero]
/// when [Dialog.fullscreen] is used.
/// {@endtemplate}
final Duration insetAnimationDuration;
/// {@template flutter.material.dialog.insetAnimationCurve}
/// The curve to use for the animation shown when the system keyboard intrudes
/// into the space that the dialog is placed in.
///
/// Defaults to [Curves.decelerate].
/// {@endtemplate}
final Curve insetAnimationCurve;
/// {@template flutter.material.dialog.insetPadding}
/// The amount of padding added to [MediaQueryData.viewInsets] on the outside
/// of the dialog. This defines the minimum space between the screen's edges
/// and the dialog.
///
/// Defaults to `EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0)`.
/// {@endtemplate}
final EdgeInsets? insetPadding;
/// {@template flutter.material.dialog.clipBehavior}
/// Controls how the contents of the dialog are clipped (or not) to the given
/// [shape].
///
/// See the enum [Clip] for details of all possible options and their common
/// use cases.
///
/// Defaults to [Clip.none].
/// {@endtemplate}
final Clip clipBehavior;
/// {@template flutter.material.dialog.shape}
/// The shape of this dialog's border.
///
/// Defines the dialog's [Material.shape].
///
/// The default shape is a [RoundedRectangleBorder] with a radius of 4.0
/// {@endtemplate}
final ShapeBorder? shape;
/// {@template flutter.material.dialog.alignment}
/// How to align the [Dialog].
///
/// If null, then [DialogTheme.alignment] is used. If that is also null, the
/// default is [Alignment.center].
/// {@endtemplate}
final AlignmentGeometry? alignment;
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
/// This value is used to determine if this is a fullscreen dialog.
final bool _fullscreen;
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
final DialogTheme dialogTheme = DialogTheme.of(context);
final EdgeInsets effectivePadding = MediaQuery.viewInsetsOf(context)
+ (insetPadding ?? dialogTheme.insetPadding ?? _defaultInsetPadding);
final DialogTheme defaults = theme.useMaterial3
? (_fullscreen ? _DialogFullscreenDefaultsM3(context) : _DialogDefaultsM3(context))
: _DialogDefaultsM2(context);
Widget dialogChild;
if (_fullscreen) {
dialogChild = Material(
color: backgroundColor ?? dialogTheme.backgroundColor ?? defaults.backgroundColor,
child: child,
);
} else {
dialogChild = Align(
alignment: alignment ?? dialogTheme.alignment ?? defaults.alignment!,
child: ConstrainedBox(
constraints: const BoxConstraints(minWidth: 280.0),
child: Material(
color: backgroundColor ?? dialogTheme.backgroundColor ?? Theme.of(context).dialogBackgroundColor,
elevation: elevation ?? dialogTheme.elevation ?? defaults.elevation!,
shadowColor: shadowColor ?? dialogTheme.shadowColor ?? defaults.shadowColor,
surfaceTintColor: surfaceTintColor ?? dialogTheme.surfaceTintColor ?? defaults.surfaceTintColor,
shape: shape ?? dialogTheme.shape ?? defaults.shape!,
type: MaterialType.card,
clipBehavior: clipBehavior,
child: child,
),
),
);
}
return AnimatedPadding(
padding: effectivePadding,
duration: insetAnimationDuration,
curve: insetAnimationCurve,
child: MediaQuery.removeViewInsets(
removeLeft: true,
removeTop: true,
removeRight: true,
removeBottom: true,
context: context,
child: dialogChild,
),
);
}
}
/// A Material Design alert dialog.
///
/// An alert dialog (also known as a basic dialog) informs the user about
/// situations that require acknowledgment. An alert dialog has an optional
/// title and an optional list of actions. The title is displayed above the
/// content and the actions are displayed below the content.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=75CsnyRXf5I}
///
/// For dialogs that offer the user a choice between several options, consider
/// using a [SimpleDialog].
///
/// Typically passed as the child widget to [showDialog], which displays the
/// dialog.
///
/// {@animation 350 622 https://flutter.github.io/assets-for-api-docs/assets/material/alert_dialog.mp4}
///
/// {@tool snippet}
///
/// This snippet shows a method in a [State] which, when called, displays a dialog box
/// and returns a [Future] that completes when the dialog is dismissed.
///
/// ```dart
/// Future<void> _showMyDialog() async {
/// return showDialog<void>(
/// context: context,
/// barrierDismissible: false, // user must tap button!
/// builder: (BuildContext context) {
/// return AlertDialog(
/// title: const Text('AlertDialog Title'),
/// content: const SingleChildScrollView(
/// child: ListBody(
/// children: <Widget>[
/// Text('This is a demo alert dialog.'),
/// Text('Would you like to approve of this message?'),
/// ],
/// ),
/// ),
/// actions: <Widget>[
/// TextButton(
/// child: const Text('Approve'),
/// onPressed: () {
/// Navigator.of(context).pop();
/// },
/// ),
/// ],
/// );
/// },
/// );
/// }
/// ```
/// {@end-tool}
///
/// {@tool dartpad}
/// This demo shows a [TextButton] which when pressed, calls [showDialog]. When called, this method
/// displays a Material dialog above the current contents of the app and returns
/// a [Future] that completes when the dialog is dismissed.
///
/// ** See code in examples/api/lib/material/dialog/alert_dialog.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This sample shows the creation of [AlertDialog], as described in:
/// https://m3.material.io/components/dialogs/overview
///
/// ** See code in examples/api/lib/material/dialog/alert_dialog.1.dart **
/// {@end-tool}
///
/// ## Alert dialogs and scrolling
///
/// By default, alert dialogs size themselves to contain their children.
///
/// If the content is too large to fit on the screen vertically, the dialog will
/// display the title and actions, and let the _[content]_ overflow. This is
/// rarely desired. Consider using a scrolling widget for [content], such as
/// [SingleChildScrollView], to avoid overflow.
///
/// Because the dialog attempts to size itself to the contents, the [content]
/// must support reporting its intrinsic dimensions. In particular, this means
/// that lazily-rendered widgets such as [ListView], [GridView], and
/// [CustomScrollView], will not work in an [AlertDialog] unless they are
/// wrapped in a widget that forces a particular size (e.g. a [SizedBox]).
///
/// For finer-grained control over the sizing of a dialog, consider using
/// [Dialog] directly.
///
/// See also:
///
/// * [SimpleDialog], which handles the scrolling of the contents but has no [actions].
/// * [Dialog], on which [AlertDialog] and [SimpleDialog] are based.
/// * [CupertinoAlertDialog], an iOS-styled alert dialog.
/// * [showDialog], which actually displays the dialog and returns its result.
/// * <https://material.io/design/components/dialogs.html#alert-dialog>
/// * <https://m3.material.io/components/dialogs>
class AlertDialog extends StatelessWidget {
/// Creates an alert dialog.
///
/// Typically used in conjunction with [showDialog].
///
/// The [titlePadding] and [contentPadding] default to null, which implies a
/// default that depends on the values of the other properties. See the
/// documentation of [titlePadding] and [contentPadding] for details.
const AlertDialog({
super.key,
this.icon,
this.iconPadding,
this.iconColor,
this.title,
this.titlePadding,
this.titleTextStyle,
this.content,
this.contentPadding,
this.contentTextStyle,
this.actions,
this.actionsPadding,
this.actionsAlignment,
this.actionsOverflowAlignment,
this.actionsOverflowDirection,
this.actionsOverflowButtonSpacing,
this.buttonPadding,
this.backgroundColor,
this.elevation,
this.shadowColor,
this.surfaceTintColor,
this.semanticLabel,
this.insetPadding,
this.clipBehavior = Clip.none,
this.shape,
this.alignment,
this.scrollable = false,
});
/// Creates an adaptive [AlertDialog] based on whether the target platform is
/// iOS or macOS, following Material design's
/// [Cross-platform guidelines](https://material.io/design/platform-guidance/cross-platform-adaptation.html).
///
/// On iOS and macOS, this constructor creates a [CupertinoAlertDialog]. On
/// other platforms, this creates a Material design [AlertDialog].
///
/// Typically passed as a child of [showAdaptiveDialog], which will display
/// the alert differently based on platform.
///
/// If a [CupertinoAlertDialog] is created only these parameters are used:
/// [title], [content], [actions], [scrollController],
/// [actionScrollController], [insetAnimationDuration], and
/// [insetAnimationCurve]. If a material [AlertDialog] is created,
/// [scrollController], [actionScrollController], [insetAnimationDuration],
/// and [insetAnimationCurve] are ignored.
///
/// The target platform is based on the current [Theme]: [ThemeData.platform].
///
/// {@tool dartpad}
/// This demo shows a [TextButton] which when pressed, calls [showAdaptiveDialog].
/// When called, this method displays an adaptive dialog above the current
/// contents of the app, with different behaviors depending on target platform.
///
/// [CupertinoDialogAction] is conditionally used as the child to show more
/// platform specific design.
///
/// ** See code in examples/api/lib/material/dialog/adaptive_alert_dialog.0.dart **
/// {@end-tool}
const factory AlertDialog.adaptive({
Key? key,
Widget? icon,
EdgeInsetsGeometry? iconPadding,
Color? iconColor,
Widget? title,
EdgeInsetsGeometry? titlePadding,
TextStyle? titleTextStyle,
Widget? content,
EdgeInsetsGeometry? contentPadding,
TextStyle? contentTextStyle,
List<Widget>? actions,
EdgeInsetsGeometry? actionsPadding,
MainAxisAlignment? actionsAlignment,
OverflowBarAlignment? actionsOverflowAlignment,
VerticalDirection? actionsOverflowDirection,
double? actionsOverflowButtonSpacing,
EdgeInsetsGeometry? buttonPadding,
Color? backgroundColor,
double? elevation,
Color? shadowColor,
Color? surfaceTintColor,
String? semanticLabel,
EdgeInsets insetPadding,
Clip clipBehavior,
ShapeBorder? shape,
AlignmentGeometry? alignment,
bool scrollable,
ScrollController? scrollController,
ScrollController? actionScrollController,
Duration insetAnimationDuration,
Curve insetAnimationCurve,
}) = _AdaptiveAlertDialog;
/// An optional icon to display at the top of the dialog.
///
/// Typically, an [Icon] widget. Providing an icon centers the [title]'s text.
final Widget? icon;
/// Color for the [Icon] in the [icon] of this [AlertDialog].
///
/// If null, [DialogTheme.iconColor] is used. If that is null, defaults to
/// color scheme's [ColorScheme.secondary] if [ThemeData.useMaterial3] is
/// true, black otherwise.
final Color? iconColor;
/// Padding around the [icon].
///
/// If there is no [icon], no padding will be provided. Otherwise, this
/// padding is used.
///
/// This property defaults to providing 24 pixels on the top, left, and right
/// of the [icon]. If [title] is _not_ null, 16 pixels of bottom padding is
/// added to separate the [icon] from the [title]. If the [title] is null and
/// [content] is _not_ null, then no bottom padding is provided (but see
/// [contentPadding]). In any other case 24 pixels of bottom padding is
/// added.
final EdgeInsetsGeometry? iconPadding;
/// The (optional) title of the dialog is displayed in a large font at the top
/// of the dialog, below the (optional) [icon].
///
/// Typically a [Text] widget.
final Widget? title;
/// Padding around the title.
///
/// If there is no title, no padding will be provided. Otherwise, this padding
/// is used.
///
/// This property defaults to providing 24 pixels on the top, left, and right
/// of the title. If the [content] is not null, then no bottom padding is
/// provided (but see [contentPadding]). If it _is_ null, then an extra 20
/// pixels of bottom padding is added to separate the [title] from the
/// [actions].
final EdgeInsetsGeometry? titlePadding;
/// Style for the text in the [title] of this [AlertDialog].
///
/// If null, [DialogTheme.titleTextStyle] is used. If that's null, defaults to
/// [TextTheme.headlineSmall] of [ThemeData.textTheme] if
/// [ThemeData.useMaterial3] is true, [TextTheme.titleLarge] otherwise.
final TextStyle? titleTextStyle;
/// The (optional) content of the dialog is displayed in the center of the
/// dialog in a lighter font.
///
/// Typically this is a [SingleChildScrollView] that contains the dialog's
/// message. As noted in the [AlertDialog] documentation, it's important
/// to use a [SingleChildScrollView] if there's any risk that the content
/// will not fit, as the contents will otherwise overflow the dialog.
///
/// The [content] must support reporting its intrinsic dimensions. In
/// particular, [ListView], [GridView], and [CustomScrollView] cannot be used
/// here unless they are first wrapped in a widget that itself can report
/// intrinsic dimensions, such as a [SizedBox].
final Widget? content;
/// Padding around the content.
///
/// If there is no [content], no padding will be provided. Otherwise, this
/// padding is used.
///
/// This property defaults to providing a padding of 20 pixels above the
/// [content] to separate the [content] from the [title], and 24 pixels on the
/// left, right, and bottom to separate the [content] from the other edges of
/// the dialog.
///
/// If [ThemeData.useMaterial3] is true, the top padding separating the
/// content from the title defaults to 16 pixels instead of 20 pixels.
final EdgeInsetsGeometry? contentPadding;
/// Style for the text in the [content] of this [AlertDialog].
///
/// If null, [DialogTheme.contentTextStyle] is used. If that's null, defaults
/// to [TextTheme.bodyMedium] of [ThemeData.textTheme] if
/// [ThemeData.useMaterial3] is true, [TextTheme.titleMedium] otherwise.
final TextStyle? contentTextStyle;
/// The (optional) set of actions that are displayed at the bottom of the
/// dialog with an [OverflowBar].
///
/// Typically this is a list of [TextButton] widgets. It is recommended to
/// set the [Text.textAlign] to [TextAlign.end] for the [Text] within the
/// [TextButton], so that buttons whose labels wrap to an extra line align
/// with the overall [OverflowBar]'s alignment within the dialog.
///
/// If the [title] is not null but the [content] _is_ null, then an extra 20
/// pixels of padding is added above the [OverflowBar] to separate the [title]
/// from the [actions].
final List<Widget>? actions;
/// Padding around the set of [actions] at the bottom of the dialog.
///
/// Typically used to provide padding to the button bar between the button bar
/// and the edges of the dialog.
///
/// The [buttonPadding] may contribute to the padding on the edges of
/// [actions] as well.
///
/// If there are no [actions], then no padding will be included.
///
/// {@tool snippet}
/// This is an example of a set of actions aligned with the content widget.
/// ```dart
/// AlertDialog(
/// title: const Text('Title'),
/// content: Container(width: 200, height: 200, color: Colors.green),
/// actions: <Widget>[
/// ElevatedButton(onPressed: () {}, child: const Text('Button 1')),
/// ElevatedButton(onPressed: () {}, child: const Text('Button 2')),
/// ],
/// actionsPadding: const EdgeInsets.symmetric(horizontal: 8.0),
/// )
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [OverflowBar], which [actions] configures to lay itself out.
final EdgeInsetsGeometry? actionsPadding;
/// Defines the horizontal layout of the [actions] according to the same
/// rules as for [Row.mainAxisAlignment].
///
/// This parameter is passed along to the dialog's [OverflowBar].
///
/// If this parameter is null (the default) then [MainAxisAlignment.end]
/// is used.
final MainAxisAlignment? actionsAlignment;
/// The horizontal alignment of [actions] within the vertical
/// "overflow" layout.
///
/// If the dialog's [actions] do not fit into a single row, then they
/// are arranged in a column. This parameter controls the horizontal
/// alignment of widgets in the case of an overflow.
///
/// If this parameter is null (the default) then [OverflowBarAlignment.end]
/// is used.
///
/// See also:
///
/// * [OverflowBar], which [actions] configures to lay itself out.
final OverflowBarAlignment? actionsOverflowAlignment;
/// The vertical direction of [actions] if the children overflow
/// horizontally.
///
/// If the dialog's [actions] do not fit into a single row, then they
/// are arranged in a column. The first action is at the top of the
/// column if this property is set to [VerticalDirection.down], since it
/// "starts" at the top and "ends" at the bottom. On the other hand,
/// the first action will be at the bottom of the column if this
/// property is set to [VerticalDirection.up], since it "starts" at the
/// bottom and "ends" at the top.
///
/// See also:
///
/// * [OverflowBar], which [actions] configures to lay itself out.
final VerticalDirection? actionsOverflowDirection;
/// The spacing between [actions] when the [OverflowBar] switches to a column
/// layout because the actions don't fit horizontally.
///
/// If the widgets in [actions] do not fit into a single row, they are
/// arranged into a column. This parameter provides additional vertical space
/// between buttons when it does overflow.
///
/// The button spacing may appear to be more than the value provided. This is
/// because most buttons adhere to the [MaterialTapTargetSize] of 48px. So,
/// even though a button might visually be 36px in height, it might still take
/// up to 48px vertically.
///
/// If null then no spacing will be added in between buttons in an overflow
/// state.
final double? actionsOverflowButtonSpacing;
/// The padding that surrounds each button in [actions].
///
/// This is different from [actionsPadding], which defines the padding
/// between the entire button bar and the edges of the dialog.
///
/// If this property is null, then it will default to
/// 8.0 logical pixels on the left and right.
final EdgeInsetsGeometry? buttonPadding;
/// {@macro flutter.material.dialog.backgroundColor}
final Color? backgroundColor;
/// {@macro flutter.material.dialog.elevation}
final double? elevation;
/// {@macro flutter.material.dialog.shadowColor}
final Color? shadowColor;
/// {@macro flutter.material.dialog.surfaceTintColor}
final Color? surfaceTintColor;
/// The semantic label of the dialog used by accessibility frameworks to
/// announce screen transitions when the dialog is opened and closed.
///
/// In iOS, if this label is not provided, a semantic label will be inferred
/// from the [title] if it is not null.
///
/// In Android, if this label is not provided, the dialog will use the
/// [MaterialLocalizations.alertDialogLabel] as its label.
///
/// See also:
///
/// * [SemanticsConfiguration.namesRoute], for a description of how this
/// value is used.
final String? semanticLabel;
/// {@macro flutter.material.dialog.insetPadding}
final EdgeInsets? insetPadding;
/// {@macro flutter.material.dialog.clipBehavior}
final Clip clipBehavior;
/// {@macro flutter.material.dialog.shape}
final ShapeBorder? shape;
/// {@macro flutter.material.dialog.alignment}
final AlignmentGeometry? alignment;
/// Determines whether the [title] and [content] widgets are wrapped in a
/// scrollable.
///
/// This configuration is used when the [title] and [content] are expected
/// to overflow. Both [title] and [content] are wrapped in a scroll view,
/// allowing all overflowed content to be visible while still showing the
/// button bar.
final bool scrollable;
@override
Widget build(BuildContext context) {
assert(debugCheckHasMaterialLocalizations(context));
final ThemeData theme = Theme.of(context);
final DialogTheme dialogTheme = DialogTheme.of(context);
final DialogTheme defaults = theme.useMaterial3 ? _DialogDefaultsM3(context) : _DialogDefaultsM2(context);
String? label = semanticLabel;
switch (theme.platform) {
case TargetPlatform.iOS:
case TargetPlatform.macOS:
break;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
label ??= MaterialLocalizations.of(context).alertDialogLabel;
}
// The paddingScaleFactor is used to adjust the padding of Dialog's
// children.
const double fontSizeToScale = 14.0;
final double effectiveTextScale = MediaQuery.textScalerOf(context).scale(fontSizeToScale) / fontSizeToScale;
final double paddingScaleFactor = _scalePadding(effectiveTextScale);
final TextDirection? textDirection = Directionality.maybeOf(context);
Widget? iconWidget;
Widget? titleWidget;
Widget? contentWidget;
Widget? actionsWidget;
if (icon != null) {
final bool belowIsTitle = title != null;
final bool belowIsContent = !belowIsTitle && content != null;
final EdgeInsets defaultIconPadding = EdgeInsets.only(
left: 24.0,
top: 24.0,
right: 24.0,
bottom: belowIsTitle ? 16.0 : belowIsContent ? 0.0 : 24.0,
);
final EdgeInsets effectiveIconPadding = iconPadding?.resolve(textDirection) ?? defaultIconPadding;
iconWidget = Padding(
padding: EdgeInsets.only(
left: effectiveIconPadding.left * paddingScaleFactor,
right: effectiveIconPadding.right * paddingScaleFactor,
top: effectiveIconPadding.top * paddingScaleFactor,
bottom: effectiveIconPadding.bottom,
),
child: IconTheme(
data: IconThemeData(
color: iconColor ?? dialogTheme.iconColor ?? defaults.iconColor,
),
child: icon!,
),
);
}
if (title != null) {
final EdgeInsets defaultTitlePadding = EdgeInsets.only(
left: 24.0,
top: icon == null ? 24.0 : 0.0,
right: 24.0,
bottom: content == null ? 20.0 : 0.0,
);
final EdgeInsets effectiveTitlePadding = titlePadding?.resolve(textDirection) ?? defaultTitlePadding;
titleWidget = Padding(
padding: EdgeInsets.only(
left: effectiveTitlePadding.left * paddingScaleFactor,
right: effectiveTitlePadding.right * paddingScaleFactor,
top: icon == null ? effectiveTitlePadding.top * paddingScaleFactor : effectiveTitlePadding.top,
bottom: effectiveTitlePadding.bottom,
),
child: DefaultTextStyle(
style: titleTextStyle ?? dialogTheme.titleTextStyle ?? defaults.titleTextStyle!,
textAlign: icon == null ? TextAlign.start : TextAlign.center,
child: Semantics(
// For iOS platform, the focus always lands on the title.
// Set nameRoute to false to avoid title being announce twice.
namesRoute: label == null && theme.platform != TargetPlatform.iOS,
container: true,
child: title,
),
),
);
}
if (content != null) {
final EdgeInsets defaultContentPadding = EdgeInsets.only(
left: 24.0,
top: theme.useMaterial3 ? 16.0 : 20.0,
right: 24.0,
bottom: 24.0,
);
final EdgeInsets effectiveContentPadding = contentPadding?.resolve(textDirection) ?? defaultContentPadding;
contentWidget = Padding(
padding: EdgeInsets.only(
left: effectiveContentPadding.left * paddingScaleFactor,
right: effectiveContentPadding.right * paddingScaleFactor,
top: title == null && icon == null
? effectiveContentPadding.top * paddingScaleFactor
: effectiveContentPadding.top,
bottom: effectiveContentPadding.bottom,
),
child: DefaultTextStyle(
style: contentTextStyle ?? dialogTheme.contentTextStyle ?? defaults.contentTextStyle!,
child: Semantics(
container: true,
child: content,
),
),
);
}
if (actions != null) {
final double spacing = (buttonPadding?.horizontal ?? 16) / 2;
actionsWidget = Padding(
padding: actionsPadding ?? dialogTheme.actionsPadding ?? (
theme.useMaterial3 ? defaults.actionsPadding! : defaults.actionsPadding!.add(EdgeInsets.all(spacing))
),
child: OverflowBar(
alignment: actionsAlignment ?? MainAxisAlignment.end,
spacing: spacing,
overflowAlignment: actionsOverflowAlignment ?? OverflowBarAlignment.end,
overflowDirection: actionsOverflowDirection ?? VerticalDirection.down,
overflowSpacing: actionsOverflowButtonSpacing ?? 0,
children: actions!,
),
);
}
List<Widget> columnChildren;
if (scrollable) {
columnChildren = <Widget>[
if (title != null || content != null)
Flexible(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
if (icon != null) iconWidget!,
if (title != null) titleWidget!,
if (content != null) contentWidget!,
],
),
),
),
if (actions != null)
actionsWidget!,
];
} else {
columnChildren = <Widget>[
if (icon != null) iconWidget!,
if (title != null) titleWidget!,
if (content != null) Flexible(child: contentWidget!),
if (actions != null) actionsWidget!,
];
}
Widget dialogChild = IntrinsicWidth(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: columnChildren,
),
);
if (label != null) {
dialogChild = Semantics(
scopesRoute: true,
explicitChildNodes: true,
namesRoute: true,
label: label,
child: dialogChild,
);
}
return Dialog(
backgroundColor: backgroundColor,
elevation: elevation,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
insetPadding: insetPadding,
clipBehavior: clipBehavior,
shape: shape,
alignment: alignment,
child: dialogChild,
);
}
}
class _AdaptiveAlertDialog extends AlertDialog {
const _AdaptiveAlertDialog({
super.key,
super.icon,
super.iconPadding,
super.iconColor,
super.title,
super.titlePadding,
super.titleTextStyle,
super.content,
super.contentPadding,
super.contentTextStyle,
super.actions,
super.actionsPadding,
super.actionsAlignment,
super.actionsOverflowAlignment,
super.actionsOverflowDirection,
super.actionsOverflowButtonSpacing,
super.buttonPadding,
super.backgroundColor,
super.elevation,
super.shadowColor,
super.surfaceTintColor,
super.semanticLabel,
super.insetPadding,
super.clipBehavior = Clip.none,
super.shape,
super.alignment,
super.scrollable = false,
this.scrollController,
this.actionScrollController,
this.insetAnimationDuration = const Duration(milliseconds: 100),
this.insetAnimationCurve = Curves.decelerate,
});
final ScrollController? scrollController;
final ScrollController? actionScrollController;
final Duration insetAnimationDuration;
final Curve insetAnimationCurve;
@override
Widget build(BuildContext context) {
final ThemeData theme = Theme.of(context);
switch (theme.platform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
break;
case TargetPlatform.iOS:
case TargetPlatform.macOS:
return CupertinoAlertDialog(
title: title,
content: content,
actions: actions ?? <Widget>[],
scrollController: scrollController,
actionScrollController: actionScrollController,
insetAnimationDuration: insetAnimationDuration,
insetAnimationCurve: insetAnimationCurve,
);
}
return super.build(context);
}
}
/// An option used in a [SimpleDialog].
///
/// A simple dialog offers the user a choice between several options. This
/// widget is commonly used to represent each of the options. If the user
/// selects this option, the widget will call the [onPressed] callback, which
/// typically uses [Navigator.pop] to close the dialog.
///
/// The padding on a [SimpleDialogOption] is configured to combine with the
/// default [SimpleDialog.contentPadding] so that each option ends up 8 pixels
/// from the other vertically, with 20 pixels of spacing between the dialog's
/// title and the first option, and 24 pixels of spacing between the last option
/// and the bottom of the dialog.
///
/// {@tool snippet}
///
/// ```dart
/// SimpleDialogOption(
/// onPressed: () { Navigator.pop(context, Department.treasury); },
/// child: const Text('Treasury department'),
/// )
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [SimpleDialog], for a dialog in which to use this widget.
/// * [showDialog], which actually displays the dialog and returns its result.
/// * [TextButton], which are commonly used as actions in other kinds of
/// dialogs, such as [AlertDialog]s.
/// * <https://material.io/design/components/dialogs.html#simple-dialog>
class SimpleDialogOption extends StatelessWidget {
/// Creates an option for a [SimpleDialog].
const SimpleDialogOption({
super.key,
this.onPressed,
this.padding,
this.child,
});
/// The callback that is called when this option is selected.
///
/// If this is set to null, the option cannot be selected.
///
/// When used in a [SimpleDialog], this will typically call [Navigator.pop]
/// with a value for [showDialog] to complete its future with.
final VoidCallback? onPressed;
/// The widget below this widget in the tree.
///
/// Typically a [Text] widget.
final Widget? child;
/// The amount of space to surround the [child] with.
///
/// Defaults to EdgeInsets.symmetric(vertical: 8.0, horizontal: 24.0).
final EdgeInsets? padding;
@override
Widget build(BuildContext context) {
return InkWell(
onTap: onPressed,
child: Padding(
padding: padding ?? const EdgeInsets.symmetric(vertical: 8.0, horizontal: 24.0),
child: child,
),
);
}
}
/// A simple Material Design dialog.
///
/// A simple dialog offers the user a choice between several options. A simple
/// dialog has an optional title that is displayed above the choices.
///
/// Choices are normally represented using [SimpleDialogOption] widgets. If
/// other widgets are used, see [contentPadding] for notes regarding the
/// conventions for obtaining the spacing expected by Material Design.
///
/// For dialogs that inform the user about a situation, consider using an
/// [AlertDialog].
///
/// Typically passed as the child widget to [showDialog], which displays the
/// dialog.
///
/// {@animation 350 622 https://flutter.github.io/assets-for-api-docs/assets/material/simple_dialog.mp4}
///
/// {@tool snippet}
///
/// In this example, the user is asked to select between two options. These
/// options are represented as an enum. The [showDialog] method here returns
/// a [Future] that completes to a value of that enum. If the user cancels
/// the dialog (e.g. by hitting the back button on Android, or tapping on the
/// mask behind the dialog) then the future completes with the null value.
///
/// The return value in this example is used as the index for a switch statement.
/// One advantage of using an enum as the return value and then using that to
/// drive a switch statement is that the analyzer will flag any switch statement
/// that doesn't mention every value in the enum.
///
/// ```dart
/// Future<void> _askedToLead() async {
/// switch (await showDialog<Department>(
/// context: context,
/// builder: (BuildContext context) {
/// return SimpleDialog(
/// title: const Text('Select assignment'),
/// children: <Widget>[
/// SimpleDialogOption(
/// onPressed: () { Navigator.pop(context, Department.treasury); },
/// child: const Text('Treasury department'),
/// ),
/// SimpleDialogOption(
/// onPressed: () { Navigator.pop(context, Department.state); },
/// child: const Text('State department'),
/// ),
/// ],
/// );
/// }
/// )) {
/// case Department.treasury:
/// // Let's go.
/// // ...
/// break;
/// case Department.state:
/// // ...
/// break;
/// case null:
/// // dialog dismissed
/// break;
/// }
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [SimpleDialogOption], which are options used in this type of dialog.
/// * [AlertDialog], for dialogs that have a row of buttons below the body.
/// * [Dialog], on which [SimpleDialog] and [AlertDialog] are based.
/// * [showDialog], which actually displays the dialog and returns its result.
/// * <https://material.io/design/components/dialogs.html#simple-dialog>
class SimpleDialog extends StatelessWidget {
/// Creates a simple dialog.
///
/// Typically used in conjunction with [showDialog].
const SimpleDialog({
super.key,
this.title,
this.titlePadding = const EdgeInsets.fromLTRB(24.0, 24.0, 24.0, 0.0),
this.titleTextStyle,
this.children,
this.contentPadding = const EdgeInsets.fromLTRB(0.0, 12.0, 0.0, 16.0),
this.backgroundColor,
this.elevation,
this.shadowColor,
this.surfaceTintColor,
this.semanticLabel,
this.insetPadding,
this.clipBehavior = Clip.none,
this.shape,
this.alignment,
});
/// The (optional) title of the dialog is displayed in a large font at the top
/// of the dialog.
///
/// Typically a [Text] widget.
final Widget? title;
/// Padding around the title.
///
/// If there is no title, no padding will be provided.
///
/// By default, this provides the recommend Material Design padding of 24
/// pixels around the left, top, and right edges of the title.
///
/// See [contentPadding] for the conventions regarding padding between the
/// [title] and the [children].
final EdgeInsetsGeometry titlePadding;
/// Style for the text in the [title] of this [SimpleDialog].
///
/// If null, [DialogTheme.titleTextStyle] is used. If that's null, defaults to
/// [TextTheme.titleLarge] of [ThemeData.textTheme].
final TextStyle? titleTextStyle;
/// The (optional) content of the dialog is displayed in a
/// [SingleChildScrollView] underneath the title.
///
/// Typically a list of [SimpleDialogOption]s.
final List<Widget>? children;
/// Padding around the content.
///
/// By default, this is 12 pixels on the top and 16 pixels on the bottom. This
/// is intended to be combined with children that have 24 pixels of padding on
/// the left and right, and 8 pixels of padding on the top and bottom, so that
/// the content ends up being indented 20 pixels from the title, 24 pixels
/// from the bottom, and 24 pixels from the sides.
///
/// The [SimpleDialogOption] widget uses such padding.
///
/// If there is no [title], the [contentPadding] should be adjusted so that
/// the top padding ends up being 24 pixels.
final EdgeInsetsGeometry contentPadding;
/// {@macro flutter.material.dialog.backgroundColor}
final Color? backgroundColor;
/// {@macro flutter.material.dialog.elevation}
final double? elevation;
/// {@macro flutter.material.dialog.shadowColor}
final Color? shadowColor;
/// {@macro flutter.material.dialog.surfaceTintColor}
final Color? surfaceTintColor;
/// The semantic label of the dialog used by accessibility frameworks to
/// announce screen transitions when the dialog is opened and closed.
///
/// If this label is not provided, a semantic label will be inferred from the
/// [title] if it is not null. If there is no title, the label will be taken
/// from [MaterialLocalizations.dialogLabel].
///
/// See also:
///
/// * [SemanticsConfiguration.namesRoute], for a description of how this
/// value is used.
final String? semanticLabel;
/// {@macro flutter.material.dialog.insetPadding}
final EdgeInsets? insetPadding;
/// {@macro flutter.material.dialog.clipBehavior}
final Clip clipBehavior;
/// {@macro flutter.material.dialog.shape}
final ShapeBorder? shape;
/// {@macro flutter.material.dialog.shape}
final AlignmentGeometry? alignment;
@override
Widget build(BuildContext context) {
assert(debugCheckHasMaterialLocalizations(context));
final ThemeData theme = Theme.of(context);
String? label = semanticLabel;
switch (theme.platform) {
case TargetPlatform.macOS:
case TargetPlatform.iOS:
break;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
label ??= MaterialLocalizations.of(context).dialogLabel;
}
// The paddingScaleFactor is used to adjust the padding of Dialog
// children.
final TextStyle defaultTextStyle = titleTextStyle ?? DialogTheme.of(context).titleTextStyle ?? theme.textTheme.titleLarge!;
final double fontSize = defaultTextStyle.fontSize ?? kDefaultFontSize;
final double fontSizeToScale = fontSize == 0.0 ? kDefaultFontSize : fontSize;
final double effectiveTextScale = MediaQuery.textScalerOf(context).scale(fontSizeToScale) / fontSizeToScale;
final double paddingScaleFactor = _scalePadding(effectiveTextScale);
final TextDirection? textDirection = Directionality.maybeOf(context);
Widget? titleWidget;
if (title != null) {
final EdgeInsets effectiveTitlePadding = titlePadding.resolve(textDirection);
titleWidget = Padding(
padding: EdgeInsets.only(
left: effectiveTitlePadding.left * paddingScaleFactor,
right: effectiveTitlePadding.right * paddingScaleFactor,
top: effectiveTitlePadding.top * paddingScaleFactor,
bottom: children == null ? effectiveTitlePadding.bottom * paddingScaleFactor : effectiveTitlePadding.bottom,
),
child: DefaultTextStyle(
style: defaultTextStyle,
child: Semantics(
// For iOS platform, the focus always lands on the title.
// Set nameRoute to false to avoid title being announce twice.
namesRoute: label == null && theme.platform != TargetPlatform.iOS,
container: true,
child: title,
),
),
);
}
Widget? contentWidget;
if (children != null) {
final EdgeInsets effectiveContentPadding = contentPadding.resolve(textDirection);
contentWidget = Flexible(
child: SingleChildScrollView(
padding: EdgeInsets.only(
left: effectiveContentPadding.left * paddingScaleFactor,
right: effectiveContentPadding.right * paddingScaleFactor,
top: title == null ? effectiveContentPadding.top * paddingScaleFactor : effectiveContentPadding.top,
bottom: effectiveContentPadding.bottom * paddingScaleFactor,
),
child: ListBody(children: children!),
),
);
}
Widget dialogChild = IntrinsicWidth(
stepWidth: 56.0,
child: ConstrainedBox(
constraints: const BoxConstraints(minWidth: 280.0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
if (title != null) titleWidget!,
if (children != null) contentWidget!,
],
),
),
);
if (label != null) {
dialogChild = Semantics(
scopesRoute: true,
explicitChildNodes: true,
namesRoute: true,
label: label,
child: dialogChild,
);
}
return Dialog(
backgroundColor: backgroundColor,
elevation: elevation,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
insetPadding: insetPadding,
clipBehavior: clipBehavior,
shape: shape,
alignment: alignment,
child: dialogChild,
);
}
}
Widget _buildMaterialDialogTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
return FadeTransition(
opacity: CurvedAnimation(
parent: animation,
curve: Curves.easeOut,
),
child: child,
);
}
/// Displays a Material dialog above the current contents of the app, with
/// Material entrance and exit animations, modal barrier color, and modal
/// barrier behavior (dialog is dismissible with a tap on the barrier).
///
/// This function takes a `builder` which typically builds a [Dialog] widget.
/// Content below the dialog is dimmed with a [ModalBarrier]. The widget
/// returned by the `builder` does not share a context with the location that
/// [showDialog] is originally called from. Use a [StatefulBuilder] or a
/// custom [StatefulWidget] if the dialog needs to update dynamically.
///
/// The `context` argument is used to look up the [Navigator] and [Theme] for
/// the dialog. It is only used when the method is called. Its corresponding
/// widget can be safely removed from the tree before the dialog is closed.
///
/// The `barrierDismissible` argument is used to indicate whether tapping on the
/// barrier will dismiss the dialog. It is `true` by default and can not be `null`.
///
/// The `barrierColor` argument is used to specify the color of the modal
/// barrier that darkens everything below the dialog. If `null` the `barrierColor`
/// field from `DialogTheme` is used. If that is `null` the default color
/// `Colors.black54` is used.
///
/// The `useSafeArea` argument is used to indicate if the dialog should only
/// display in 'safe' areas of the screen not used by the operating system
/// (see [SafeArea] for more details). It is `true` by default, which means
/// the dialog will not overlap operating system areas. If it is set to `false`
/// the dialog will only be constrained by the screen size. It can not be `null`.
///
/// The `useRootNavigator` argument is used to determine whether to push the
/// dialog to the [Navigator] furthest from or nearest to the given `context`.
/// By default, `useRootNavigator` is `true` and the dialog route created by
/// this method is pushed to the root navigator. It can not be `null`.
///
/// The `routeSettings` argument is passed to [showGeneralDialog],
/// see [RouteSettings] for details.
///
/// If not null, the `traversalEdgeBehavior` argument specifies the transfer of
/// focus beyond the first and the last items of the dialog route. By default,
/// [TraversalEdgeBehavior.closedLoop] is used, because it's typical for dialogs
/// to allow users to cycle through dialog widgets without leaving the dialog.
///
/// {@macro flutter.widgets.RawDialogRoute}
///
/// If the application has multiple [Navigator] objects, it may be necessary to
/// call `Navigator.of(context, rootNavigator: true).pop(result)` to close the
/// dialog rather than just `Navigator.pop(context, result)`.
///
/// Returns a [Future] that resolves to the value (if any) that was passed to
/// [Navigator.pop] when the dialog was closed.
///
/// {@tool dartpad}
/// This sample demonstrates how to use [showDialog] to display a dialog box.
///
/// ** See code in examples/api/lib/material/dialog/show_dialog.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// This sample shows the creation of [showDialog], as described in:
/// https://m3.material.io/components/dialogs/overview
///
/// ** See code in examples/api/lib/material/dialog/show_dialog.1.dart **
/// {@end-tool}
///
/// ### State Restoration in Dialogs
///
/// Using this method will not enable state restoration for the dialog. In order
/// to enable state restoration for a dialog, use [Navigator.restorablePush]
/// or [Navigator.restorablePushNamed] with [DialogRoute].
///
/// For more information about state restoration, see [RestorationManager].
///
/// {@tool dartpad}
/// This sample demonstrates how to create a restorable Material dialog. This is
/// accomplished by enabling state restoration by specifying
/// [MaterialApp.restorationScopeId] and using [Navigator.restorablePush] to
/// push [DialogRoute] when the button is tapped.
///
/// {@macro flutter.widgets.RestorationManager}
///
/// ** See code in examples/api/lib/material/dialog/show_dialog.2.dart **
/// {@end-tool}
///
/// See also:
///
/// * [AlertDialog], for dialogs that have a row of buttons below a body.
/// * [SimpleDialog], which handles the scrolling of the contents and does
/// not show buttons below its body.
/// * [Dialog], on which [SimpleDialog] and [AlertDialog] are based.
/// * [showCupertinoDialog], which displays an iOS-style dialog.
/// * [showGeneralDialog], which allows for customization of the dialog popup.
/// * [DisplayFeatureSubScreen], which documents the specifics of how
/// [DisplayFeature]s can split the screen into sub-screens.
/// * <https://material.io/design/components/dialogs.html>
/// * <https://m3.material.io/components/dialogs>
Future<T?> showDialog<T>({
required BuildContext context,
required WidgetBuilder builder,
bool barrierDismissible = true,
Color? barrierColor,
String? barrierLabel,
bool useSafeArea = true,
bool useRootNavigator = true,
RouteSettings? routeSettings,
Offset? anchorPoint,
TraversalEdgeBehavior? traversalEdgeBehavior,
}) {
assert(_debugIsActive(context));
assert(debugCheckHasMaterialLocalizations(context));
final CapturedThemes themes = InheritedTheme.capture(
from: context,
to: Navigator.of(
context,
rootNavigator: useRootNavigator,
).context,
);
return Navigator.of(context, rootNavigator: useRootNavigator).push<T>(DialogRoute<T>(
context: context,
builder: builder,
barrierColor: barrierColor ?? Theme.of(context).dialogTheme.barrierColor ?? Colors.black54,
barrierDismissible: barrierDismissible,
barrierLabel: barrierLabel,
useSafeArea: useSafeArea,
settings: routeSettings,
themes: themes,
anchorPoint: anchorPoint,
traversalEdgeBehavior: traversalEdgeBehavior ?? TraversalEdgeBehavior.closedLoop,
));
}
/// Displays either a Material or Cupertino dialog depending on platform.
///
/// On most platforms this function will act the same as [showDialog], except
/// for iOS and macOS, in which case it will act the same as
/// [showCupertinoDialog].
///
/// On Cupertino platforms, [barrierColor], [useSafeArea], and
/// [traversalEdgeBehavior] are ignored.
Future<T?> showAdaptiveDialog<T>({
required BuildContext context,
required WidgetBuilder builder,
bool? barrierDismissible,
Color? barrierColor,
String? barrierLabel,
bool useSafeArea = true,
bool useRootNavigator = true,
RouteSettings? routeSettings,
Offset? anchorPoint,
TraversalEdgeBehavior? traversalEdgeBehavior,
}) {
final ThemeData theme = Theme.of(context);
switch (theme.platform) {
case TargetPlatform.android:
case TargetPlatform.fuchsia:
case TargetPlatform.linux:
case TargetPlatform.windows:
return showDialog<T>(
context: context,
builder: builder,
barrierDismissible: barrierDismissible ?? true,
barrierColor: barrierColor,
barrierLabel: barrierLabel,
useSafeArea: useSafeArea,
useRootNavigator: useRootNavigator,
routeSettings: routeSettings,
anchorPoint: anchorPoint,
traversalEdgeBehavior: traversalEdgeBehavior,
);
case TargetPlatform.iOS:
case TargetPlatform.macOS:
return showCupertinoDialog<T>(
context: context,
builder: builder,
barrierDismissible: barrierDismissible ?? false,
barrierLabel: barrierLabel,
useRootNavigator: useRootNavigator,
anchorPoint: anchorPoint,
routeSettings: routeSettings,
);
}
}
bool _debugIsActive(BuildContext context) {
if (context is Element && !context.debugIsActive) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('This BuildContext is no longer valid.'),
ErrorDescription(
'The showDialog function context parameter is a BuildContext that is no longer valid.'
),
ErrorHint(
'This can commonly occur when the showDialog function is called after awaiting a Future. '
'In this situation the BuildContext might refer to a widget that has already been disposed during the await. '
'Consider using a parent context instead.',
),
]);
}
return true;
}
/// A dialog route with Material entrance and exit animations,
/// modal barrier color, and modal barrier behavior (dialog is dismissible
/// with a tap on the barrier).
///
/// It is used internally by [showDialog] or can be directly pushed
/// onto the [Navigator] stack to enable state restoration. See
/// [showDialog] for a state restoration app example.
///
/// This function takes a `builder` which typically builds a [Dialog] widget.
/// Content below the dialog is dimmed with a [ModalBarrier]. The widget
/// returned by the `builder` does not share a context with the location that
/// `showDialog` is originally called from. Use a [StatefulBuilder] or a
/// custom [StatefulWidget] if the dialog needs to update dynamically.
///
/// The `context` argument is used to look up
/// [MaterialLocalizations.modalBarrierDismissLabel], which provides the
/// modal with a localized accessibility label that will be used for the
/// modal's barrier. However, a custom `barrierLabel` can be passed in as well.
///
/// The `barrierDismissible` argument is used to indicate whether tapping on the
/// barrier will dismiss the dialog. It is `true` by default and cannot be `null`.
///
/// The `barrierColor` argument is used to specify the color of the modal
/// barrier that darkens everything below the dialog. If `null`, the default
/// color `Colors.black54` is used.
///
/// The `useSafeArea` argument is used to indicate if the dialog should only
/// display in 'safe' areas of the screen not used by the operating system
/// (see [SafeArea] for more details). It is `true` by default, which means
/// the dialog will not overlap operating system areas. If it is set to `false`
/// the dialog will only be constrained by the screen size. It can not be `null`.
///
/// The `settings` argument define the settings for this route. See
/// [RouteSettings] for details.
///
/// {@macro flutter.widgets.RawDialogRoute}
///
/// See also:
///
/// * [showDialog], which is a way to display a DialogRoute.
/// * [showGeneralDialog], which allows for customization of the dialog popup.
/// * [showCupertinoDialog], which displays an iOS-style dialog.
/// * [DisplayFeatureSubScreen], which documents the specifics of how
/// [DisplayFeature]s can split the screen into sub-screens.
class DialogRoute<T> extends RawDialogRoute<T> {
/// A dialog route with Material entrance and exit animations,
/// modal barrier color, and modal barrier behavior (dialog is dismissible
/// with a tap on the barrier).
DialogRoute({
required BuildContext context,
required WidgetBuilder builder,
CapturedThemes? themes,
super.barrierColor = Colors.black54,
super.barrierDismissible,
String? barrierLabel,
bool useSafeArea = true,
super.settings,
super.anchorPoint,
super.traversalEdgeBehavior,
}) : super(
pageBuilder: (BuildContext buildContext, Animation<double> animation, Animation<double> secondaryAnimation) {
final Widget pageChild = Builder(builder: builder);
Widget dialog = themes?.wrap(pageChild) ?? pageChild;
if (useSafeArea) {
dialog = SafeArea(child: dialog);
}
return dialog;
},
barrierLabel: barrierLabel ?? MaterialLocalizations.of(context).modalBarrierDismissLabel,
transitionDuration: const Duration(milliseconds: 150),
transitionBuilder: _buildMaterialDialogTransitions,
);
}
double _scalePadding(double textScaleFactor) {
final double clampedTextScaleFactor = clampDouble(textScaleFactor, 1.0, 2.0);
// The final padding scale factor is clamped between 1/3 and 1. For example,
// a non-scaled padding of 24 will produce a padding between 24 and 8.
return lerpDouble(1.0, 1.0 / 3.0, clampedTextScaleFactor - 1.0)!;
}
// Hand coded defaults based on Material Design 2.
class _DialogDefaultsM2 extends DialogTheme {
_DialogDefaultsM2(this.context)
: _textTheme = Theme.of(context).textTheme,
_iconTheme = Theme.of(context).iconTheme,
super(
alignment: Alignment.center,
elevation: 24.0,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))),
);
final BuildContext context;
final TextTheme _textTheme;
final IconThemeData _iconTheme;
@override
Color? get iconColor => _iconTheme.color;
@override
Color? get backgroundColor => Theme.of(context).dialogBackgroundColor;
@override
Color? get shadowColor => Theme.of(context).shadowColor;
@override
TextStyle? get titleTextStyle => _textTheme.titleLarge;
@override
TextStyle? get contentTextStyle => _textTheme.titleMedium;
@override
EdgeInsetsGeometry? get actionsPadding => EdgeInsets.zero;
}
// BEGIN GENERATED TOKEN PROPERTIES - Dialog
// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
// dev/tools/gen_defaults/bin/gen_defaults.dart.
class _DialogDefaultsM3 extends DialogTheme {
_DialogDefaultsM3(this.context)
: super(
alignment: Alignment.center,
elevation: 6.0,
shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(28.0))),
);
final BuildContext context;
late final ColorScheme _colors = Theme.of(context).colorScheme;
late final TextTheme _textTheme = Theme.of(context).textTheme;
@override
Color? get iconColor => _colors.secondary;
@override
Color? get backgroundColor => _colors.surfaceContainerHigh;
@override
Color? get shadowColor => Colors.transparent;
@override
Color? get surfaceTintColor => Colors.transparent;
@override
TextStyle? get titleTextStyle => _textTheme.headlineSmall;
@override
TextStyle? get contentTextStyle => _textTheme.bodyMedium;
@override
EdgeInsetsGeometry? get actionsPadding => const EdgeInsets.only(left: 24.0, right: 24.0, bottom: 24.0);
}
// END GENERATED TOKEN PROPERTIES - Dialog
// BEGIN GENERATED TOKEN PROPERTIES - DialogFullscreen
// Do not edit by hand. The code between the "BEGIN GENERATED" and
// "END GENERATED" comments are generated from data in the Material
// Design token database by the script:
// dev/tools/gen_defaults/bin/gen_defaults.dart.
class _DialogFullscreenDefaultsM3 extends DialogTheme {
const _DialogFullscreenDefaultsM3(this.context);
final BuildContext context;
@override
Color? get backgroundColor => Theme.of(context).colorScheme.surface;
}
// END GENERATED TOKEN PROPERTIES - DialogFullscreen
| flutter/packages/flutter/lib/src/material/dialog.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/dialog.dart",
"repo_id": "flutter",
"token_count": 20240
} | 623 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'theme.dart';
// Examples can assume:
// late BuildContext context;
/// Used with [ExpansionTileTheme] to define default property values for
/// descendant [ExpansionTile] widgets.
///
/// Descendant widgets obtain the current [ExpansionTileThemeData] object
/// using `ExpansionTileTheme.of(context)`. Instances of
/// [ExpansionTileThemeData] can be customized with
/// [ExpansionTileThemeData.copyWith].
///
/// A [ExpansionTileThemeData] is often specified as part of the
/// overall [Theme] with [ThemeData.expansionTileTheme].
///
/// All [ExpansionTileThemeData] properties are `null` by default.
/// When a theme property is null, the [ExpansionTile] will provide its own
/// default based on the overall [Theme]'s textTheme and
/// colorScheme. See the individual [ExpansionTile] properties for details.
///
/// See also:
///
/// * [ThemeData], which describes the overall theme information for the
/// application.
/// * [ExpansionTileTheme] which overrides the default [ExpansionTileTheme]
/// of its [ExpansionTile] descendants.
/// * [ThemeData.textTheme], text with a color that contrasts with the card
/// and canvas colors.
/// * [ThemeData.colorScheme], the thirteen colors that most Material widget
/// default colors are based on.
@immutable
class ExpansionTileThemeData with Diagnosticable {
/// Creates a [ExpansionTileThemeData].
const ExpansionTileThemeData ({
this.backgroundColor,
this.collapsedBackgroundColor,
this.tilePadding,
this.expandedAlignment,
this.childrenPadding,
this.iconColor,
this.collapsedIconColor,
this.textColor,
this.collapsedTextColor,
this.shape,
this.collapsedShape,
this.clipBehavior,
this.expansionAnimationStyle,
});
/// Overrides the default value of [ExpansionTile.backgroundColor].
final Color? backgroundColor;
/// Overrides the default value of [ExpansionTile.collapsedBackgroundColor].
final Color? collapsedBackgroundColor;
/// Overrides the default value of [ExpansionTile.tilePadding].
final EdgeInsetsGeometry? tilePadding;
/// Overrides the default value of [ExpansionTile.expandedAlignment].
final AlignmentGeometry? expandedAlignment;
/// Overrides the default value of [ExpansionTile.childrenPadding].
final EdgeInsetsGeometry? childrenPadding;
/// Overrides the default value of [ExpansionTile.iconColor].
final Color? iconColor;
/// Overrides the default value of [ExpansionTile.collapsedIconColor].
final Color? collapsedIconColor;
/// Overrides the default value of [ExpansionTile.textColor].
final Color? textColor;
/// Overrides the default value of [ExpansionTile.collapsedTextColor].
final Color? collapsedTextColor;
/// Overrides the default value of [ExpansionTile.shape].
final ShapeBorder? shape;
/// Overrides the default value of [ExpansionTile.collapsedShape].
final ShapeBorder? collapsedShape;
/// Overrides the default value of [ExpansionTile.clipBehavior].
final Clip? clipBehavior;
/// Overrides the default value of [ExpansionTile.expansionAnimationStyle].
final AnimationStyle? expansionAnimationStyle;
/// Creates a copy of this object with the given fields replaced with the
/// new values.
ExpansionTileThemeData copyWith({
Color? backgroundColor,
Color? collapsedBackgroundColor,
EdgeInsetsGeometry? tilePadding,
AlignmentGeometry? expandedAlignment,
EdgeInsetsGeometry? childrenPadding,
Color? iconColor,
Color? collapsedIconColor,
Color? textColor,
Color? collapsedTextColor,
ShapeBorder? shape,
ShapeBorder? collapsedShape,
Clip? clipBehavior,
AnimationStyle? expansionAnimationStyle,
}) {
return ExpansionTileThemeData(
backgroundColor: backgroundColor ?? this.backgroundColor,
collapsedBackgroundColor: collapsedBackgroundColor ?? this.collapsedBackgroundColor,
tilePadding: tilePadding ?? this.tilePadding,
expandedAlignment: expandedAlignment ?? this.expandedAlignment,
childrenPadding: childrenPadding ?? this.childrenPadding,
iconColor: iconColor ?? this.iconColor,
collapsedIconColor: collapsedIconColor ?? this.collapsedIconColor,
textColor: textColor ?? this.textColor,
collapsedTextColor: collapsedTextColor ?? this.collapsedTextColor,
shape: shape ?? this.shape,
collapsedShape: collapsedShape ?? this.collapsedShape,
clipBehavior: clipBehavior ?? this.clipBehavior,
expansionAnimationStyle: expansionAnimationStyle ?? this.expansionAnimationStyle,
);
}
/// Linearly interpolate between ExpansionTileThemeData objects.
static ExpansionTileThemeData? lerp(ExpansionTileThemeData? a, ExpansionTileThemeData? b, double t) {
if (identical(a, b)) {
return a;
}
return ExpansionTileThemeData(
backgroundColor: Color.lerp(a?.backgroundColor, b?.backgroundColor, t),
collapsedBackgroundColor: Color.lerp(a?.collapsedBackgroundColor, b?.collapsedBackgroundColor, t),
tilePadding: EdgeInsetsGeometry.lerp(a?.tilePadding, b?.tilePadding, t),
expandedAlignment: AlignmentGeometry.lerp(a?.expandedAlignment, b?.expandedAlignment, t),
childrenPadding: EdgeInsetsGeometry.lerp(a?.childrenPadding, b?.childrenPadding, t),
iconColor: Color.lerp(a?.iconColor, b?.iconColor, t),
collapsedIconColor: Color.lerp(a?.collapsedIconColor, b?.collapsedIconColor, t),
textColor: Color.lerp(a?.textColor, b?.textColor, t),
collapsedTextColor: Color.lerp(a?.collapsedTextColor, b?.collapsedTextColor, t),
shape: ShapeBorder.lerp(a?.shape, b?.shape, t),
collapsedShape: ShapeBorder.lerp(a?.collapsedShape, b?.collapsedShape, t),
clipBehavior: t < 0.5 ? a?.clipBehavior : b?.clipBehavior,
expansionAnimationStyle: t < 0.5 ? a?.expansionAnimationStyle : b?.expansionAnimationStyle,
);
}
@override
int get hashCode {
return Object.hash(
backgroundColor,
collapsedBackgroundColor,
tilePadding,
expandedAlignment,
childrenPadding,
iconColor,
collapsedIconColor,
textColor,
collapsedTextColor,
shape,
collapsedShape,
clipBehavior,
expansionAnimationStyle,
);
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is ExpansionTileThemeData
&& other.backgroundColor == backgroundColor
&& other.collapsedBackgroundColor == collapsedBackgroundColor
&& other.tilePadding == tilePadding
&& other.expandedAlignment == expandedAlignment
&& other.childrenPadding == childrenPadding
&& other.iconColor == iconColor
&& other.collapsedIconColor == collapsedIconColor
&& other.textColor == textColor
&& other.collapsedTextColor == collapsedTextColor
&& other.shape == shape
&& other.collapsedShape == collapsedShape
&& other.clipBehavior == clipBehavior
&& other.expansionAnimationStyle == expansionAnimationStyle;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(ColorProperty('backgroundColor', backgroundColor, defaultValue: null));
properties.add(ColorProperty('collapsedBackgroundColor', collapsedBackgroundColor, defaultValue: null));
properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('tilePadding', tilePadding, defaultValue: null));
properties.add(DiagnosticsProperty<AlignmentGeometry>('expandedAlignment', expandedAlignment, defaultValue: null));
properties.add(DiagnosticsProperty<EdgeInsetsGeometry>('childrenPadding', childrenPadding, defaultValue: null));
properties.add(ColorProperty('iconColor', iconColor, defaultValue: null));
properties.add(ColorProperty('collapsedIconColor', collapsedIconColor, defaultValue: null));
properties.add(ColorProperty('textColor', textColor, defaultValue: null));
properties.add(ColorProperty('collapsedTextColor', collapsedTextColor, defaultValue: null));
properties.add(DiagnosticsProperty<ShapeBorder>('shape', shape, defaultValue: null));
properties.add(DiagnosticsProperty<ShapeBorder>('collapsedShape', collapsedShape, defaultValue: null));
properties.add(DiagnosticsProperty<Clip>('clipBehavior', clipBehavior, defaultValue: null));
properties.add(DiagnosticsProperty<AnimationStyle>('expansionAnimationStyle', expansionAnimationStyle, defaultValue: null));
}
}
/// Overrides the default [ExpansionTileTheme] of its [ExpansionTile] descendants.
///
/// See also:
///
/// * [ExpansionTileThemeData], which is used to configure this theme.
/// * [ThemeData.expansionTileTheme], which can be used to override the default
/// [ExpansionTileTheme] for [ExpansionTile]s below the overall [Theme].
class ExpansionTileTheme extends InheritedTheme {
/// Applies the given theme [data] to [child].
const ExpansionTileTheme({
super.key,
required this.data,
required super.child,
});
/// Specifies color, alignment, and text style values for
/// descendant [ExpansionTile] widgets.
final ExpansionTileThemeData data;
/// The closest instance of this class that encloses the given context.
///
/// If there is no enclosing [ExpansionTileTheme] widget, then
/// [ThemeData.expansionTileTheme] is used.
///
/// Typical usage is as follows:
///
/// ```dart
/// ExpansionTileThemeData theme = ExpansionTileTheme.of(context);
/// ```
static ExpansionTileThemeData of(BuildContext context) {
final ExpansionTileTheme? inheritedTheme = context.dependOnInheritedWidgetOfExactType<ExpansionTileTheme>();
return inheritedTheme?.data ?? Theme.of(context).expansionTileTheme;
}
@override
Widget wrap(BuildContext context, Widget child) {
return ExpansionTileTheme(data: data, child: child);
}
@override
bool updateShouldNotify(ExpansionTileTheme oldWidget) => data != oldWidget.data;
}
| flutter/packages/flutter/lib/src/material/expansion_tile_theme.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/expansion_tile_theme.dart",
"repo_id": "flutter",
"token_count": 3143
} | 624 |
// 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 'ink_well.dart' show InteractiveInkFeature;
import 'material.dart';
const Duration _kDefaultHighlightFadeDuration = Duration(milliseconds: 200);
/// A visual emphasis on a part of a [Material] receiving user interaction.
///
/// This object is rarely created directly. Instead of creating an ink highlight
/// directly, consider using an [InkResponse] or [InkWell] widget, which uses
/// gestures (such as tap and long-press) to trigger ink highlights.
///
/// See also:
///
/// * [InkResponse], which uses gestures to trigger ink highlights and ink
/// splashes in the parent [Material].
/// * [InkWell], which is a rectangular [InkResponse] (the most common type of
/// ink response).
/// * [Material], which is the widget on which the ink highlight is painted.
/// * [InkSplash], which is an ink feature that shows a reaction to user input
/// on a [Material].
/// * [Ink], a convenience widget for drawing images and other decorations on
/// Material widgets.
class InkHighlight extends InteractiveInkFeature {
/// Begin a highlight animation.
///
/// The [controller] argument is typically obtained via
/// `Material.of(context)`.
///
/// If a `rectCallback` is given, then it provides the highlight rectangle,
/// otherwise, the highlight rectangle is coincident with the [referenceBox].
///
/// When the highlight is removed, `onRemoved` will be called.
InkHighlight({
required super.controller,
required super.referenceBox,
required super.color,
required TextDirection textDirection,
BoxShape shape = BoxShape.rectangle,
double? radius,
BorderRadius? borderRadius,
super.customBorder,
RectCallback? rectCallback,
super.onRemoved,
Duration fadeDuration = _kDefaultHighlightFadeDuration,
}) : _shape = shape,
_radius = radius,
_borderRadius = borderRadius ?? BorderRadius.zero,
_textDirection = textDirection,
_rectCallback = rectCallback {
_alphaController = AnimationController(duration: fadeDuration, vsync: controller.vsync)
..addListener(controller.markNeedsPaint)
..addStatusListener(_handleAlphaStatusChanged)
..forward();
_alpha = _alphaController.drive(IntTween(
begin: 0,
end: color.alpha,
));
controller.addInkFeature(this);
}
final BoxShape _shape;
final double? _radius;
final BorderRadius _borderRadius;
final RectCallback? _rectCallback;
final TextDirection _textDirection;
late Animation<int> _alpha;
late AnimationController _alphaController;
/// Whether this part of the material is being visually emphasized.
bool get active => _active;
bool _active = true;
/// Start visually emphasizing this part of the material.
void activate() {
_active = true;
_alphaController.forward();
}
/// Stop visually emphasizing this part of the material.
void deactivate() {
_active = false;
_alphaController.reverse();
}
void _handleAlphaStatusChanged(AnimationStatus status) {
if (status == AnimationStatus.dismissed && !_active) {
dispose();
}
}
@override
void dispose() {
_alphaController.dispose();
super.dispose();
}
void _paintHighlight(Canvas canvas, Rect rect, Paint paint) {
canvas.save();
if (customBorder != null) {
canvas.clipPath(customBorder!.getOuterPath(rect, textDirection: _textDirection));
}
switch (_shape) {
case BoxShape.circle:
canvas.drawCircle(rect.center, _radius ?? Material.defaultSplashRadius, paint);
case BoxShape.rectangle:
if (_borderRadius != BorderRadius.zero) {
final RRect clipRRect = RRect.fromRectAndCorners(
rect,
topLeft: _borderRadius.topLeft, topRight: _borderRadius.topRight,
bottomLeft: _borderRadius.bottomLeft, bottomRight: _borderRadius.bottomRight,
);
canvas.drawRRect(clipRRect, paint);
} else {
canvas.drawRect(rect, paint);
}
}
canvas.restore();
}
@override
void paintFeature(Canvas canvas, Matrix4 transform) {
final Paint paint = Paint()..color = color.withAlpha(_alpha.value);
final Offset? originOffset = MatrixUtils.getAsTranslation(transform);
final Rect rect = _rectCallback != null ? _rectCallback() : Offset.zero & referenceBox.size;
if (originOffset == null) {
canvas.save();
canvas.transform(transform.storage);
_paintHighlight(canvas, rect, paint);
canvas.restore();
} else {
_paintHighlight(canvas, rect.shift(originOffset), paint);
}
}
}
| flutter/packages/flutter/lib/src/material/ink_highlight.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/ink_highlight.dart",
"repo_id": "flutter",
"token_count": 1575
} | 625 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'material_state.dart';
/// Mixin for [State] classes that require knowledge of changing [MaterialState]
/// values for their child widgets.
///
/// This mixin does nothing by mere application to a [State] class, but is
/// helpful when writing `build` methods that include child [InkWell],
/// [GestureDetector], [MouseRegion], or [Focus] widgets. Instead of manually
/// creating handlers for each type of user interaction, such [State] classes can
/// instead provide a `ValueChanged<bool>` function and allow [MaterialStateMixin]
/// to manage the set of active [MaterialState]s, and the calling of [setState]
/// as necessary.
///
/// {@tool snippet}
/// This example shows how to write a [StatefulWidget] that uses the
/// [MaterialStateMixin] class to watch [MaterialState] values.
///
/// ```dart
/// class MyWidget extends StatefulWidget {
/// const MyWidget({super.key, required this.color, required this.child});
///
/// final MaterialStateColor color;
/// final Widget child;
///
/// @override
/// State<MyWidget> createState() => MyWidgetState();
/// }
///
/// class MyWidgetState extends State<MyWidget> with MaterialStateMixin<MyWidget> {
/// @override
/// Widget build(BuildContext context) {
/// return InkWell(
/// onFocusChange: updateMaterialState(MaterialState.focused),
/// child: ColoredBox(
/// color: widget.color.resolve(materialStates),
/// child: widget.child,
/// ),
/// );
/// }
/// }
/// ```
/// {@end-tool}
@optionalTypeArgs
mixin MaterialStateMixin<T extends StatefulWidget> on State<T> {
/// Managed set of active [MaterialState] values; designed to be passed to
/// [MaterialStateProperty.resolve] methods.
///
/// To mutate and have [setState] called automatically for you, use
/// [setMaterialState], [addMaterialState], or [removeMaterialState]. Directly
/// mutating the set is possible, and may be necessary if you need to alter its
/// list without calling [setState] (and thus triggering a re-render).
///
/// To check for a single condition, convenience getters [isPressed], [isHovered],
/// [isFocused], etc, are available for each [MaterialState] value.
@protected
Set<MaterialState> materialStates = <MaterialState>{};
/// Callback factory which accepts a [MaterialState] value and returns a
/// closure to mutate [materialStates] and call [setState].
///
/// Accepts an optional second named parameter, `onChanged`, which allows
/// arbitrary functionality to be wired through the [MaterialStateMixin].
/// If supplied, the [onChanged] function is only called when child widgets
/// report events that make changes to the current set of [MaterialState]s.
///
/// {@tool snippet}
/// This example shows how to use the [updateMaterialState] callback factory
/// in other widgets, including the optional [onChanged] callback.
///
/// ```dart
/// class MyWidget extends StatefulWidget {
/// const MyWidget({super.key, this.onPressed});
///
/// /// Something important this widget must do when pressed.
/// final VoidCallback? onPressed;
///
/// @override
/// State<MyWidget> createState() => MyWidgetState();
/// }
///
/// class MyWidgetState extends State<MyWidget> with MaterialStateMixin<MyWidget> {
/// @override
/// Widget build(BuildContext context) {
/// return ColoredBox(
/// color: isPressed ? Colors.black : Colors.white,
/// child: InkWell(
/// onHighlightChanged: updateMaterialState(
/// MaterialState.pressed,
/// onChanged: (bool val) {
/// if (val) {
/// widget.onPressed?.call();
/// }
/// },
/// ),
/// ),
/// );
/// }
/// }
/// ```
/// {@end-tool}
@protected
ValueChanged<bool> updateMaterialState(MaterialState key, {ValueChanged<bool>? onChanged}) {
return (bool value) {
if (materialStates.contains(key) == value) {
return;
}
setMaterialState(key, value);
onChanged?.call(value);
};
}
/// Mutator to mark a [MaterialState] value as either active or inactive.
@protected
void setMaterialState(MaterialState state, bool isSet) {
return isSet ? addMaterialState(state) : removeMaterialState(state);
}
/// Mutator to mark a [MaterialState] value as active.
@protected
void addMaterialState(MaterialState state) {
if (materialStates.add(state)) {
setState((){});
}
}
/// Mutator to mark a [MaterialState] value as inactive.
@protected
void removeMaterialState(MaterialState state) {
if (materialStates.remove(state)) {
setState((){});
}
}
/// Getter for whether this class considers [MaterialState.disabled] to be active.
bool get isDisabled => materialStates.contains(MaterialState.disabled);
/// Getter for whether this class considers [MaterialState.dragged] to be active.
bool get isDragged => materialStates.contains(MaterialState.dragged);
/// Getter for whether this class considers [MaterialState.error] to be active.
bool get isErrored => materialStates.contains(MaterialState.error);
/// Getter for whether this class considers [MaterialState.focused] to be active.
bool get isFocused => materialStates.contains(MaterialState.focused);
/// Getter for whether this class considers [MaterialState.hovered] to be active.
bool get isHovered => materialStates.contains(MaterialState.hovered);
/// Getter for whether this class considers [MaterialState.pressed] to be active.
bool get isPressed => materialStates.contains(MaterialState.pressed);
/// Getter for whether this class considers [MaterialState.scrolledUnder] to be active.
bool get isScrolledUnder => materialStates.contains(MaterialState.scrolledUnder);
/// Getter for whether this class considers [MaterialState.selected] to be active.
bool get isSelected => materialStates.contains(MaterialState.selected);
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<Set<MaterialState>>('materialStates', materialStates, defaultValue: <MaterialState>{}));
}
}
| flutter/packages/flutter/lib/src/material/material_state_mixin.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/material_state_mixin.dart",
"repo_id": "flutter",
"token_count": 1975
} | 626 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'button_style.dart';
import 'theme.dart';
// Examples can assume:
// late BuildContext context;
/// A [ButtonStyle] that overrides the default appearance of
/// [OutlinedButton]s when it's used with [OutlinedButtonTheme] or with the
/// overall [Theme]'s [ThemeData.outlinedButtonTheme].
///
/// The [style]'s properties override [OutlinedButton]'s default style,
/// i.e. the [ButtonStyle] returned by [OutlinedButton.defaultStyleOf]. Only
/// the style's non-null property values or resolved non-null
/// [MaterialStateProperty] values are used.
///
/// See also:
///
/// * [OutlinedButtonTheme], the theme which is configured with this class.
/// * [OutlinedButton.defaultStyleOf], which returns the default [ButtonStyle]
/// for outlined buttons.
/// * [OutlinedButton.styleFrom], which converts simple values into a
/// [ButtonStyle] that's consistent with [OutlinedButton]'s defaults.
/// * [MaterialStateProperty.resolve], "resolve" a material state property
/// to a simple value based on a set of [MaterialState]s.
/// * [ThemeData.outlinedButtonTheme], which can be used to override the default
/// [ButtonStyle] for [OutlinedButton]s below the overall [Theme].
@immutable
class OutlinedButtonThemeData with Diagnosticable {
/// Creates a [OutlinedButtonThemeData].
///
/// The [style] may be null.
const OutlinedButtonThemeData({ this.style });
/// Overrides for [OutlinedButton]'s default style.
///
/// Non-null properties or non-null resolved [MaterialStateProperty]
/// values override the [ButtonStyle] returned by
/// [OutlinedButton.defaultStyleOf].
///
/// If [style] is null, then this theme doesn't override anything.
final ButtonStyle? style;
/// Linearly interpolate between two outlined button themes.
static OutlinedButtonThemeData? lerp(OutlinedButtonThemeData? a, OutlinedButtonThemeData? b, double t) {
if (identical(a, b)) {
return a;
}
return OutlinedButtonThemeData(
style: ButtonStyle.lerp(a?.style, b?.style, t),
);
}
@override
int get hashCode => style.hashCode;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is OutlinedButtonThemeData && other.style == style;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<ButtonStyle>('style', style, defaultValue: null));
}
}
/// Overrides the default [ButtonStyle] of its [OutlinedButton] descendants.
///
/// See also:
///
/// * [OutlinedButtonThemeData], which is used to configure this theme.
/// * [OutlinedButton.defaultStyleOf], which returns the default [ButtonStyle]
/// for outlined buttons.
/// * [OutlinedButton.styleFrom], which converts simple values into a
/// [ButtonStyle] that's consistent with [OutlinedButton]'s defaults.
/// * [ThemeData.outlinedButtonTheme], which can be used to override the default
/// [ButtonStyle] for [OutlinedButton]s below the overall [Theme].
class OutlinedButtonTheme extends InheritedTheme {
/// Create a [OutlinedButtonTheme].
const OutlinedButtonTheme({
super.key,
required this.data,
required super.child,
});
/// The configuration of this theme.
final OutlinedButtonThemeData data;
/// The closest instance of this class that encloses the given context.
///
/// If there is no enclosing [OutlinedButtonTheme] widget, then
/// [ThemeData.outlinedButtonTheme] is used.
///
/// Typical usage is as follows:
///
/// ```dart
/// OutlinedButtonThemeData theme = OutlinedButtonTheme.of(context);
/// ```
static OutlinedButtonThemeData of(BuildContext context) {
final OutlinedButtonTheme? buttonTheme = context.dependOnInheritedWidgetOfExactType<OutlinedButtonTheme>();
return buttonTheme?.data ?? Theme.of(context).outlinedButtonTheme;
}
@override
Widget wrap(BuildContext context, Widget child) {
return OutlinedButtonTheme(data: data, child: child);
}
@override
bool updateShouldNotify(OutlinedButtonTheme oldWidget) => data != oldWidget.data;
}
| flutter/packages/flutter/lib/src/material/outlined_button_theme.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/outlined_button_theme.dart",
"repo_id": "flutter",
"token_count": 1325
} | 627 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' show lerpDouble;
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'material_state.dart';
import 'theme.dart';
// Examples can assume:
// late BuildContext context;
/// Defines default property values for descendant [Scrollbar] widgets.
///
/// Descendant widgets obtain the current [ScrollbarThemeData] object with
/// `ScrollbarTheme.of(context)`. Instances of [ScrollbarThemeData] can be
/// customized with [ScrollbarThemeData.copyWith].
///
/// Typically the [ScrollbarThemeData] of a [ScrollbarTheme] is specified as
/// part of the overall [Theme] with [ThemeData.scrollbarTheme].
///
/// All [ScrollbarThemeData] properties are `null` by default. When null, the
/// [Scrollbar] computes its own default values, typically based on the overall
/// theme's [ThemeData.colorScheme].
///
/// See also:
///
/// * [ThemeData], which describes the overall theme information for the
/// application.
@immutable
class ScrollbarThemeData with Diagnosticable {
/// Creates a theme that can be used for [ThemeData.scrollbarTheme].
const ScrollbarThemeData({
this.thumbVisibility,
this.thickness,
this.trackVisibility,
this.radius,
this.thumbColor,
this.trackColor,
this.trackBorderColor,
this.crossAxisMargin,
this.mainAxisMargin,
this.minThumbLength,
this.interactive,
});
/// Overrides the default value of [Scrollbar.thumbVisibility] in all
/// descendant [Scrollbar] widgets.
final MaterialStateProperty<bool?>? thumbVisibility;
/// Overrides the default value of [Scrollbar.thickness] in all
/// descendant [Scrollbar] widgets.
///
/// Resolves in the following states:
/// * [MaterialState.hovered] on web and desktop platforms.
final MaterialStateProperty<double?>? thickness;
/// Overrides the default value of [Scrollbar.trackVisibility] in all
/// descendant [Scrollbar] widgets.
final MaterialStateProperty<bool?>? trackVisibility;
/// Overrides the default value of [Scrollbar.interactive] in all
/// descendant [Scrollbar] widgets.
final bool? interactive;
/// Overrides the default value of [Scrollbar.radius] in all
/// descendant widgets.
final Radius? radius;
/// Overrides the default [Color] of the [Scrollbar] thumb in all descendant
/// [Scrollbar] widgets.
///
/// Resolves in the following states:
/// * [MaterialState.dragged].
/// * [MaterialState.hovered] on web and desktop platforms.
final MaterialStateProperty<Color?>? thumbColor;
/// Overrides the default [Color] of the [Scrollbar] track when
/// [trackVisibility] is true in all descendant [Scrollbar] widgets.
///
/// Resolves in the following states:
/// * [MaterialState.hovered] on web and desktop platforms.
final MaterialStateProperty<Color?>? trackColor;
/// Overrides the default [Color] of the [Scrollbar] track border when
/// [trackVisibility] is true in all descendant [Scrollbar] widgets.
///
/// Resolves in the following states:
/// * [MaterialState.hovered] on web and desktop platforms.
final MaterialStateProperty<Color?>? trackBorderColor;
/// Overrides the default value of the [ScrollbarPainter.crossAxisMargin]
/// property in all descendant [Scrollbar] widgets.
///
/// See also:
///
/// * [ScrollbarPainter.crossAxisMargin], which sets the distance from the
/// scrollbar's side to the nearest edge in logical pixels.
final double? crossAxisMargin;
/// Overrides the default value of the [ScrollbarPainter.mainAxisMargin]
/// property in all descendant [Scrollbar] widgets.
///
/// See also:
///
/// * [ScrollbarPainter.mainAxisMargin], which sets the distance from the
/// scrollbar's start and end to the edge of the viewport in logical pixels.
final double? mainAxisMargin;
/// Overrides the default value of the [ScrollbarPainter.minLength]
/// property in all descendant [Scrollbar] widgets.
///
/// See also:
///
/// * [ScrollbarPainter.minLength], which sets the preferred smallest size
/// the scrollbar can shrink to when the total scrollable extent is large,
/// the current visible viewport is small, and the viewport is not
/// overscrolled.
final double? minThumbLength;
/// Creates a copy of this object with the given fields replaced with the
/// new values.
ScrollbarThemeData copyWith({
MaterialStateProperty<bool?>? thumbVisibility,
MaterialStateProperty<double?>? thickness,
MaterialStateProperty<bool?>? trackVisibility,
bool? interactive,
Radius? radius,
MaterialStateProperty<Color?>? thumbColor,
MaterialStateProperty<Color?>? trackColor,
MaterialStateProperty<Color?>? trackBorderColor,
double? crossAxisMargin,
double? mainAxisMargin,
double? minThumbLength,
}) {
return ScrollbarThemeData(
thumbVisibility: thumbVisibility ?? this.thumbVisibility,
thickness: thickness ?? this.thickness,
trackVisibility: trackVisibility ?? this.trackVisibility,
interactive: interactive ?? this.interactive,
radius: radius ?? this.radius,
thumbColor: thumbColor ?? this.thumbColor,
trackColor: trackColor ?? this.trackColor,
trackBorderColor: trackBorderColor ?? this.trackBorderColor,
crossAxisMargin: crossAxisMargin ?? this.crossAxisMargin,
mainAxisMargin: mainAxisMargin ?? this.mainAxisMargin,
minThumbLength: minThumbLength ?? this.minThumbLength,
);
}
/// Linearly interpolate between two Scrollbar themes.
///
/// {@macro dart.ui.shadow.lerp}
static ScrollbarThemeData lerp(ScrollbarThemeData? a, ScrollbarThemeData? b, double t) {
if (identical(a, b) && a != null) {
return a;
}
return ScrollbarThemeData(
thumbVisibility: MaterialStateProperty.lerp<bool?>(a?.thumbVisibility, b?.thumbVisibility, t, _lerpBool),
thickness: MaterialStateProperty.lerp<double?>(a?.thickness, b?.thickness, t, lerpDouble),
trackVisibility: MaterialStateProperty.lerp<bool?>(a?.trackVisibility, b?.trackVisibility, t, _lerpBool),
interactive: _lerpBool(a?.interactive, b?.interactive, t),
radius: Radius.lerp(a?.radius, b?.radius, t),
thumbColor: MaterialStateProperty.lerp<Color?>(a?.thumbColor, b?.thumbColor, t, Color.lerp),
trackColor: MaterialStateProperty.lerp<Color?>(a?.trackColor, b?.trackColor, t, Color.lerp),
trackBorderColor: MaterialStateProperty.lerp<Color?>(a?.trackBorderColor, b?.trackBorderColor, t, Color.lerp),
crossAxisMargin: lerpDouble(a?.crossAxisMargin, b?.crossAxisMargin, t),
mainAxisMargin: lerpDouble(a?.mainAxisMargin, b?.mainAxisMargin, t),
minThumbLength: lerpDouble(a?.minThumbLength, b?.minThumbLength, t),
);
}
@override
int get hashCode => Object.hash(
thumbVisibility,
thickness,
trackVisibility,
interactive,
radius,
thumbColor,
trackColor,
trackBorderColor,
crossAxisMargin,
mainAxisMargin,
minThumbLength,
);
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other.runtimeType != runtimeType) {
return false;
}
return other is ScrollbarThemeData
&& other.thumbVisibility == thumbVisibility
&& other.thickness == thickness
&& other.trackVisibility == trackVisibility
&& other.interactive == interactive
&& other.radius == radius
&& other.thumbColor == thumbColor
&& other.trackColor == trackColor
&& other.trackBorderColor == trackBorderColor
&& other.crossAxisMargin == crossAxisMargin
&& other.mainAxisMargin == mainAxisMargin
&& other.minThumbLength == minThumbLength;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<MaterialStateProperty<bool?>>('thumbVisibility', thumbVisibility, defaultValue: null));
properties.add(DiagnosticsProperty<MaterialStateProperty<double?>>('thickness', thickness, defaultValue: null));
properties.add(DiagnosticsProperty<MaterialStateProperty<bool?>>('trackVisibility', trackVisibility, defaultValue: null));
properties.add(DiagnosticsProperty<bool>('interactive', interactive, defaultValue: null));
properties.add(DiagnosticsProperty<Radius>('radius', radius, defaultValue: null));
properties.add(DiagnosticsProperty<MaterialStateProperty<Color?>>('thumbColor', thumbColor, defaultValue: null));
properties.add(DiagnosticsProperty<MaterialStateProperty<Color?>>('trackColor', trackColor, defaultValue: null));
properties.add(DiagnosticsProperty<MaterialStateProperty<Color?>>('trackBorderColor', trackBorderColor, defaultValue: null));
properties.add(DiagnosticsProperty<double>('crossAxisMargin', crossAxisMargin, defaultValue: null));
properties.add(DiagnosticsProperty<double>('mainAxisMargin', mainAxisMargin, defaultValue: null));
properties.add(DiagnosticsProperty<double>('minThumbLength', minThumbLength, defaultValue: null));
}
}
bool? _lerpBool(bool? a, bool? b, double t) => t < 0.5 ? a : b;
/// Applies a scrollbar theme to descendant [Scrollbar] widgets.
///
/// Descendant widgets obtain the current theme's [ScrollbarThemeData] using
/// [ScrollbarTheme.of]. When a widget uses [ScrollbarTheme.of], it is
/// automatically rebuilt if the theme later changes.
///
/// A scrollbar theme can be specified as part of the overall Material theme
/// using [ThemeData.scrollbarTheme].
///
/// See also:
///
/// * [ScrollbarThemeData], which describes the configuration of a
/// scrollbar theme.
class ScrollbarTheme extends InheritedTheme {
/// Constructs a scrollbar theme that configures all descendant [Scrollbar]
/// widgets.
const ScrollbarTheme({
super.key,
required this.data,
required super.child,
});
/// The properties used for all descendant [Scrollbar] widgets.
final ScrollbarThemeData data;
/// Returns the configuration [data] from the closest [ScrollbarTheme]
/// ancestor. If there is no ancestor, it returns [ThemeData.scrollbarTheme].
///
/// Typical usage is as follows:
///
/// ```dart
/// ScrollbarThemeData theme = ScrollbarTheme.of(context);
/// ```
static ScrollbarThemeData of(BuildContext context) {
final ScrollbarTheme? scrollbarTheme = context.dependOnInheritedWidgetOfExactType<ScrollbarTheme>();
return scrollbarTheme?.data ?? Theme.of(context).scrollbarTheme;
}
@override
Widget wrap(BuildContext context, Widget child) {
return ScrollbarTheme(data: data, child: child);
}
@override
bool updateShouldNotify(ScrollbarTheme oldWidget) => data != oldWidget.data;
}
| flutter/packages/flutter/lib/src/material/scrollbar_theme.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/scrollbar_theme.dart",
"repo_id": "flutter",
"token_count": 3452
} | 628 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart' show TextSelectionToolbarLayoutDelegate;
/// Positions the toolbar below [anchor] or adjusts it higher to fit above
/// the bottom view insets, if applicable.
///
/// See also:
///
/// * [SpellCheckSuggestionsToolbar], which uses this to position itself.
class SpellCheckSuggestionsToolbarLayoutDelegate extends SingleChildLayoutDelegate {
/// Creates an instance of [SpellCheckSuggestionsToolbarLayoutDelegate].
SpellCheckSuggestionsToolbarLayoutDelegate({
required this.anchor,
});
/// {@macro flutter.material.SpellCheckSuggestionsToolbar.anchor}
///
/// Should be provided in local coordinates.
final Offset anchor;
@override
BoxConstraints getConstraintsForChild(BoxConstraints constraints) {
return constraints.loosen();
}
@override
Offset getPositionForChild(Size size, Size childSize) {
return Offset(
TextSelectionToolbarLayoutDelegate.centerOn(
anchor.dx,
childSize.width,
size.width,
),
// Positions child (of childSize) just enough upwards to fit within size
// if it otherwise does not fit below the anchor.
anchor.dy + childSize.height > size.height
? size.height - childSize.height
: anchor.dy,
);
}
@override
bool shouldRelayout(SpellCheckSuggestionsToolbarLayoutDelegate oldDelegate) {
return anchor != oldDelegate.anchor;
}
}
| flutter/packages/flutter/lib/src/material/spell_check_suggestions_toolbar_layout_delegate.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/spell_check_suggestions_toolbar_layout_delegate.dart",
"repo_id": "flutter",
"token_count": 518
} | 629 |
// 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 'color_scheme.dart';
import 'constants.dart';
import 'text_button.dart';
import 'theme.dart';
enum _TextSelectionToolbarItemPosition {
/// The first item among multiple in the menu.
first,
/// One of several items, not the first or last.
middle,
/// The last item among multiple in the menu.
last,
/// The only item in the menu.
only,
}
/// A button styled like a Material native Android text selection menu button.
class TextSelectionToolbarTextButton extends StatelessWidget {
/// Creates an instance of TextSelectionToolbarTextButton.
const TextSelectionToolbarTextButton({
super.key,
required this.child,
required this.padding,
this.onPressed,
this.alignment,
});
// These values were eyeballed to match the native text selection menu on a
// Pixel 2 running Android 10.
static const double _kMiddlePadding = 9.5;
static const double _kEndPadding = 14.5;
/// {@template flutter.material.TextSelectionToolbarTextButton.child}
/// The child of this button.
///
/// Usually a [Text].
/// {@endtemplate}
final Widget child;
/// {@template flutter.material.TextSelectionToolbarTextButton.onPressed}
/// Called when this button is pressed.
/// {@endtemplate}
final VoidCallback? onPressed;
/// The padding between the button's edge and its child.
///
/// In a standard Material [TextSelectionToolbar], the padding depends on the
/// button's position within the toolbar.
///
/// See also:
///
/// * [getPadding], which calculates the standard padding based on the
/// button's position.
/// * [ButtonStyle.padding], which is where this padding is applied.
final EdgeInsets padding;
/// The alignment of the button's child.
///
/// By default, this will be [Alignment.center].
///
/// See also:
///
/// * [ButtonStyle.alignment], which is where this alignment is applied.
final AlignmentGeometry? alignment;
/// Returns the standard padding for a button at index out of a total number
/// of buttons.
///
/// Standard Material [TextSelectionToolbar]s have buttons with different
/// padding depending on their position in the toolbar.
static EdgeInsets getPadding(int index, int total) {
assert(total > 0 && index >= 0 && index < total);
final _TextSelectionToolbarItemPosition position = _getPosition(index, total);
return EdgeInsets.only(
left: _getLeftPadding(position),
right: _getRightPadding(position),
);
}
static double _getLeftPadding(_TextSelectionToolbarItemPosition position) {
if (position == _TextSelectionToolbarItemPosition.first
|| position == _TextSelectionToolbarItemPosition.only) {
return _kEndPadding;
}
return _kMiddlePadding;
}
static double _getRightPadding(_TextSelectionToolbarItemPosition position) {
if (position == _TextSelectionToolbarItemPosition.last
|| position == _TextSelectionToolbarItemPosition.only) {
return _kEndPadding;
}
return _kMiddlePadding;
}
static _TextSelectionToolbarItemPosition _getPosition(int index, int total) {
if (index == 0) {
return total == 1
? _TextSelectionToolbarItemPosition.only
: _TextSelectionToolbarItemPosition.first;
}
if (index == total - 1) {
return _TextSelectionToolbarItemPosition.last;
}
return _TextSelectionToolbarItemPosition.middle;
}
/// Returns a copy of the current [TextSelectionToolbarTextButton] instance
/// with specific overrides.
TextSelectionToolbarTextButton copyWith({
Widget? child,
VoidCallback? onPressed,
EdgeInsets? padding,
AlignmentGeometry? alignment,
}) {
return TextSelectionToolbarTextButton(
onPressed: onPressed ?? this.onPressed,
padding: padding ?? this.padding,
alignment: alignment ?? this.alignment,
child: child ?? this.child,
);
}
// These colors were taken from a screenshot of a Pixel 6 emulator running
// Android API level 34.
static const Color _defaultForegroundColorLight = Color(0xff000000);
static const Color _defaultForegroundColorDark = Color(0xffffffff);
// The background color is hardcoded to transparent by default so the buttons
// are the color of the container behind them. For example TextSelectionToolbar
// hardcodes the color value, and TextSelectionToolbarTextButtons that are its
// children become that color.
static const Color _defaultBackgroundColorTransparent = Color(0x00000000);
static Color _getForegroundColor(ColorScheme colorScheme) {
final bool isDefaultOnSurface = switch (colorScheme.brightness) {
Brightness.light => identical(ThemeData().colorScheme.onSurface, colorScheme.onSurface),
Brightness.dark => identical(ThemeData.dark().colorScheme.onSurface, colorScheme.onSurface),
};
if (!isDefaultOnSurface) {
return colorScheme.onSurface;
}
return switch (colorScheme.brightness) {
Brightness.light => _defaultForegroundColorLight,
Brightness.dark => _defaultForegroundColorDark,
};
}
@override
Widget build(BuildContext context) {
final ColorScheme colorScheme = Theme.of(context).colorScheme;
return TextButton(
style: TextButton.styleFrom(
backgroundColor: _defaultBackgroundColorTransparent,
foregroundColor: _getForegroundColor(colorScheme),
shape: const RoundedRectangleBorder(),
minimumSize: const Size(kMinInteractiveDimension, kMinInteractiveDimension),
padding: padding,
alignment: alignment,
textStyle: const TextStyle(
// This value was eyeballed from a screenshot of a Pixel 6 emulator
// running Android API level 34.
fontWeight: FontWeight.w400,
),
),
onPressed: onPressed,
child: child,
);
}
}
| flutter/packages/flutter/lib/src/material/text_selection_toolbar_text_button.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/material/text_selection_toolbar_text_button.dart",
"repo_id": "flutter",
"token_count": 1928
} | 630 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:js_interop';
import 'dart:ui' as ui;
import 'dart:ui_web' as ui_web;
import 'package:flutter/foundation.dart';
import '../web.dart' as web;
import 'image_provider.dart' as image_provider;
import 'image_stream.dart';
/// Creates a type for an overridable factory function for testing purposes.
typedef HttpRequestFactory = web.XMLHttpRequest Function();
// Method signature for _loadAsync decode callbacks.
typedef _SimpleDecoderCallback = Future<ui.Codec> Function(ui.ImmutableBuffer buffer);
/// Default HTTP client.
web.XMLHttpRequest _httpClient() {
return web.XMLHttpRequest();
}
/// Creates an overridable factory function.
HttpRequestFactory httpRequestFactory = _httpClient;
/// Restores to the default HTTP request factory.
void debugRestoreHttpRequestFactory() {
httpRequestFactory = _httpClient;
}
/// The web implementation of [image_provider.NetworkImage].
///
/// NetworkImage on the web does not support decoding to a specified size.
@immutable
class NetworkImage
extends image_provider.ImageProvider<image_provider.NetworkImage>
implements image_provider.NetworkImage {
/// Creates an object that fetches the image at the given URL.
const NetworkImage(this.url, {this.scale = 1.0, this.headers});
@override
final String url;
@override
final double scale;
@override
final Map<String, String>? headers;
@override
Future<NetworkImage> obtainKey(image_provider.ImageConfiguration configuration) {
return SynchronousFuture<NetworkImage>(this);
}
@override
ImageStreamCompleter loadBuffer(image_provider.NetworkImage key, image_provider.DecoderBufferCallback decode) {
// Ownership of this controller is handed off to [_loadAsync]; it is that
// method's responsibility to close the controller's stream when the image
// has been loaded or an error is thrown.
final StreamController<ImageChunkEvent> chunkEvents =
StreamController<ImageChunkEvent>();
return MultiFrameImageStreamCompleter(
chunkEvents: chunkEvents.stream,
codec: _loadAsync(key as NetworkImage, decode, chunkEvents),
scale: key.scale,
debugLabel: key.url,
informationCollector: _imageStreamInformationCollector(key),
);
}
@override
ImageStreamCompleter loadImage(image_provider.NetworkImage key, image_provider.ImageDecoderCallback decode) {
// Ownership of this controller is handed off to [_loadAsync]; it is that
// method's responsibility to close the controller's stream when the image
// has been loaded or an error is thrown.
final StreamController<ImageChunkEvent> chunkEvents = StreamController<ImageChunkEvent>();
return MultiFrameImageStreamCompleter(
chunkEvents: chunkEvents.stream,
codec: _loadAsync(key as NetworkImage, decode, chunkEvents),
scale: key.scale,
debugLabel: key.url,
informationCollector: _imageStreamInformationCollector(key),
);
}
InformationCollector? _imageStreamInformationCollector(image_provider.NetworkImage key) {
InformationCollector? collector;
assert(() {
collector = () => <DiagnosticsNode>[
DiagnosticsProperty<image_provider.ImageProvider>('Image provider', this),
DiagnosticsProperty<NetworkImage>('Image key', key as NetworkImage),
];
return true;
}());
return collector;
}
// Html renderer does not support decoding network images to a specified size. The decode parameter
// here is ignored and `ui_web.createImageCodecFromUrl` will be used directly
// in place of the typical `instantiateImageCodec` method.
Future<ui.Codec> _loadAsync(
NetworkImage key,
_SimpleDecoderCallback decode,
StreamController<ImageChunkEvent> chunkEvents,
) async {
assert(key == this);
final Uri resolved = Uri.base.resolve(key.url);
final bool containsNetworkImageHeaders = key.headers?.isNotEmpty ?? false;
// We use a different method when headers are set because the
// `ui_web.createImageCodecFromUrl` method is not capable of handling headers.
if (isCanvasKit || containsNetworkImageHeaders) {
final Completer<web.XMLHttpRequest> completer =
Completer<web.XMLHttpRequest>();
final web.XMLHttpRequest request = httpRequestFactory();
request.open('GET', key.url, true);
request.responseType = 'arraybuffer';
if (containsNetworkImageHeaders) {
key.headers!.forEach((String header, String value) {
request.setRequestHeader(header, value);
});
}
request.addEventListener('load', (web.Event e) {
final int status = request.status;
final bool accepted = status >= 200 && status < 300;
final bool fileUri = status == 0; // file:// URIs have status of 0.
final bool notModified = status == 304;
final bool unknownRedirect = status > 307 && status < 400;
final bool success =
accepted || fileUri || notModified || unknownRedirect;
if (success) {
completer.complete(request);
} else {
completer.completeError(e);
throw image_provider.NetworkImageLoadException(
statusCode: status, uri: resolved);
}
}.toJS);
request.addEventListener('error',
((JSObject e) => completer.completeError(e)).toJS);
request.send();
await completer.future;
final Uint8List bytes = (request.response! as JSArrayBuffer).toDart.asUint8List();
if (bytes.lengthInBytes == 0) {
throw image_provider.NetworkImageLoadException(
statusCode: request.status, uri: resolved);
}
return decode(await ui.ImmutableBuffer.fromUint8List(bytes));
} else {
return ui_web.createImageCodecFromUrl(
resolved,
chunkCallback: (int bytes, int total) {
chunkEvents.add(ImageChunkEvent(
cumulativeBytesLoaded: bytes, expectedTotalBytes: total));
},
);
}
}
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is NetworkImage && other.url == url && other.scale == scale;
}
@override
int get hashCode => Object.hash(url, scale);
@override
String toString() => '${objectRuntimeType(this, 'NetworkImage')}("$url", scale: ${scale.toStringAsFixed(1)})';
}
| flutter/packages/flutter/lib/src/painting/_network_image_web.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/painting/_network_image_web.dart",
"repo_id": "flutter",
"token_count": 2212
} | 631 |
// 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 'basic_types.dart';
import 'edge_insets.dart';
import 'image_provider.dart';
// Examples can assume:
// late Decoration myDecoration;
// This group of classes is intended for painting in cartesian coordinates.
/// A description of a box decoration (a decoration applied to a [Rect]).
///
/// This class presents the abstract interface for all decorations.
/// See [BoxDecoration] for a concrete example.
///
/// To actually paint a [Decoration], use the [createBoxPainter]
/// method to obtain a [BoxPainter]. [Decoration] objects can be
/// shared between boxes; [BoxPainter] objects can cache resources to
/// make painting on a particular surface faster.
@immutable
abstract class Decoration with Diagnosticable {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const Decoration();
@override
String toStringShort() => objectRuntimeType(this, 'Decoration');
/// In debug mode, throws an exception if the object is not in a
/// valid configuration. Otherwise, returns true.
///
/// This is intended to be used as follows:
/// ```dart
/// assert(myDecoration.debugAssertIsValid());
/// ```
bool debugAssertIsValid() => true;
/// Returns the insets to apply when using this decoration on a box
/// that has contents, so that the contents do not overlap the edges
/// of the decoration. For example, if the decoration draws a frame
/// around its edge, the padding would return the distance by which
/// to inset the children so as to not overlap the frame.
///
/// This only works for decorations that have absolute sizes. If the padding
/// needed would change based on the size at which the decoration is drawn,
/// then this will return incorrect padding values.
///
/// For example, when a [BoxDecoration] has [BoxShape.circle], the padding
/// does not take into account that the circle is drawn in the center of the
/// box regardless of the ratio of the box; it does not provide the extra
/// padding that is implied by changing the ratio.
///
/// The value returned by this getter must be resolved (using
/// [EdgeInsetsGeometry.resolve] to obtain an absolute [EdgeInsets]. (For
/// example, [BorderDirectional] will return an [EdgeInsetsDirectional] for
/// its [padding].)
EdgeInsetsGeometry get padding => EdgeInsets.zero;
/// Whether this decoration is complex enough to benefit from caching its painting.
bool get isComplex => false;
/// Linearly interpolates from another [Decoration] (which may be of a
/// different class) to `this`.
///
/// When implementing this method in subclasses, return null if this class
/// cannot interpolate from `a`. In that case, [lerp] will try `a`'s [lerpTo]
/// method instead. Classes should implement both [lerpFrom] and [lerpTo].
///
/// Supporting interpolating from null is recommended as the [Decoration.lerp]
/// method uses this as a fallback when two classes can't interpolate between
/// each other.
///
/// The `t` argument represents position on the timeline, with 0.0 meaning
/// that the interpolation has not started, returning `a` (or something
/// equivalent to `a`), 1.0 meaning that the interpolation has finished,
/// returning `this` (or something equivalent to `this`), and values in
/// between meaning that the interpolation is at the relevant point on the
/// timeline between `a` and `this`. The interpolation can be extrapolated
/// beyond 0.0 and 1.0, so negative values and values greater than 1.0 are
/// valid (and can easily be generated by curves such as
/// [Curves.elasticInOut]).
///
/// Values for `t` are usually obtained from an [Animation<double>], such as
/// an [AnimationController].
///
/// Instead of calling this directly, use [Decoration.lerp].
@protected
Decoration? lerpFrom(Decoration? a, double t) => null;
/// Linearly interpolates from `this` to another [Decoration] (which may be of
/// a different class).
///
/// This is called if `b`'s [lerpFrom] did not know how to handle this class.
///
/// When implementing this method in subclasses, return null if this class
/// cannot interpolate from `b`. In that case, [lerp] will apply a default
/// behavior instead. Classes should implement both [lerpFrom] and [lerpTo].
///
/// Supporting interpolating to null is recommended as the [Decoration.lerp]
/// method uses this as a fallback when two classes can't interpolate between
/// each other.
///
/// The `t` argument represents position on the timeline, with 0.0 meaning
/// that the interpolation has not started, returning `this` (or something
/// equivalent to `this`), 1.0 meaning that the interpolation has finished,
/// returning `b` (or something equivalent to `b`), and values in between
/// meaning that the interpolation is at the relevant point on the timeline
/// between `this` and `b`. The interpolation can be extrapolated beyond 0.0
/// and 1.0, so negative values and values greater than 1.0 are valid (and can
/// easily be generated by curves such as [Curves.elasticInOut]).
///
/// Values for `t` are usually obtained from an [Animation<double>], such as
/// an [AnimationController].
///
/// Instead of calling this directly, use [Decoration.lerp].
@protected
Decoration? lerpTo(Decoration? b, double t) => null;
/// Linearly interpolates between two [Decoration]s.
///
/// This attempts to use [lerpFrom] and [lerpTo] on `b` and `a`
/// respectively to find a solution. If the two values can't directly be
/// interpolated, then the interpolation is done via null (at `t == 0.5`).
///
/// {@macro dart.ui.shadow.lerp}
static Decoration? lerp(Decoration? a, Decoration? b, double t) {
if (identical(a, b)) {
return a;
}
if (a == null) {
return b!.lerpFrom(null, t) ?? b;
}
if (b == null) {
return a.lerpTo(null, t) ?? a;
}
if (t == 0.0) {
return a;
}
if (t == 1.0) {
return b;
}
return b.lerpFrom(a, t)
?? a.lerpTo(b, t)
?? (t < 0.5 ? (a.lerpTo(null, t * 2.0) ?? a) : (b.lerpFrom(null, (t - 0.5) * 2.0) ?? b));
}
/// Tests whether the given point, on a rectangle of a given size,
/// would be considered to hit the decoration or not. For example,
/// if the decoration only draws a circle, this function might
/// return true if the point was inside the circle and false
/// otherwise.
///
/// The decoration may be sensitive to the [TextDirection]. The
/// `textDirection` argument should therefore be provided. If it is known that
/// the decoration is not affected by the text direction, then the argument
/// may be omitted or set to null.
///
/// When a [Decoration] is painted in a [Container] or [DecoratedBox] (which
/// is what [Container] uses), the `textDirection` parameter will be populated
/// based on the ambient [Directionality] (by way of the [RenderDecoratedBox]
/// renderer).
bool hitTest(Size size, Offset position, { TextDirection? textDirection }) => true;
/// Returns a [BoxPainter] that will paint this decoration.
///
/// The `onChanged` argument configures [BoxPainter.onChanged]. It can be
/// omitted if there is no chance that the painter will change (for example,
/// if it is a [BoxDecoration] with definitely no [DecorationImage]).
@factory
BoxPainter createBoxPainter([ VoidCallback onChanged ]);
/// Returns a closed [Path] that describes the outer edge of this decoration.
///
/// The default implementation throws. Subclasses must override this implementation
/// to describe the clip path that should be applied to the decoration when it is
/// used in a [Container] with an explicit [Clip] behavior.
///
/// See also:
///
/// * [Container.clipBehavior], which, if set, uses this method to determine
/// the clip path to use.
Path getClipPath(Rect rect, TextDirection textDirection) {
throw UnsupportedError('${objectRuntimeType(this, 'This Decoration subclass')} does not expect to be used for clipping.');
}
}
/// A stateful class that can paint a particular [Decoration].
///
/// [BoxPainter] objects can cache resources so that they can be used
/// multiple times.
///
/// Some resources used by [BoxPainter] may load asynchronously. When this
/// happens, the [onChanged] callback will be invoked. To stop this callback
/// from being called after the painter has been discarded, call [dispose].
abstract class BoxPainter {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const BoxPainter([this.onChanged]);
/// Paints the [Decoration] for which this object was created on the
/// given canvas using the given configuration.
///
/// The [ImageConfiguration] object passed as the third argument must, at a
/// minimum, have a non-null [Size].
///
/// If this object caches resources for painting (e.g. [Paint] objects), the
/// cache may be flushed when [paint] is called with a new configuration. For
/// this reason, it may be more efficient to call
/// [Decoration.createBoxPainter] for each different rectangle that is being
/// painted in a particular frame.
///
/// For example, if a decoration's owner wants to paint a particular
/// decoration once for its whole size, and once just in the bottom
/// right, it might get two [BoxPainter] instances, one for each.
/// However, when its size changes, it could continue using those
/// same instances, since the previous resources would no longer be
/// relevant and thus losing them would not be an issue.
///
/// Implementations should paint their decorations on the canvas in a
/// rectangle whose top left corner is at the given `offset` and whose size is
/// given by `configuration.size`.
///
/// When a [Decoration] is painted in a [Container] or [DecoratedBox] (which
/// is what [Container] uses), the [ImageConfiguration.textDirection] property
/// will be populated based on the ambient [Directionality].
void paint(Canvas canvas, Offset offset, ImageConfiguration configuration);
/// Callback that is invoked if an asynchronously-loading resource used by the
/// decoration finishes loading. For example, an image. When this is invoked,
/// the [paint] method should be called again.
///
/// Resources might not start to load until after [paint] has been called,
/// because they might depend on the configuration.
final VoidCallback? onChanged;
/// Discard any resources being held by the object.
///
/// The [onChanged] callback will not be invoked after this method has been
/// called.
@mustCallSuper
void dispose() { }
}
| flutter/packages/flutter/lib/src/painting/decoration.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/painting/decoration.dart",
"repo_id": "flutter",
"token_count": 3039
} | 632 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui show lerpDouble;
import 'package:flutter/foundation.dart';
import 'borders.dart';
import 'circle_border.dart';
/// A border that fits an elliptical shape.
///
/// Typically used with [ShapeDecoration] to draw an oval. Instead of centering
/// the [Border] to a square, like [CircleBorder], it fills the available space,
/// such that it touches the edges of the box. There is no difference between
/// `CircleBorder(eccentricity = 1.0)` and `OvalBorder()`. [OvalBorder] works as
/// an alias for users to discover this feature.
///
/// See also:
///
/// * [CircleBorder], which draws a circle, centering when the box is rectangular.
/// * [Border], which, when used with [BoxDecoration], can also describe an oval.
class OvalBorder extends CircleBorder {
/// Create an oval border.
const OvalBorder({ super.side, super.eccentricity = 1.0 });
@override
ShapeBorder scale(double t) => OvalBorder(side: side.scale(t), eccentricity: eccentricity);
@override
OvalBorder copyWith({ BorderSide? side, double? eccentricity }) {
return OvalBorder(side: side ?? this.side, eccentricity: eccentricity ?? this.eccentricity);
}
@override
ShapeBorder? lerpFrom(ShapeBorder? a, double t) {
if (a is OvalBorder) {
return OvalBorder(
side: BorderSide.lerp(a.side, side, t),
eccentricity: clampDouble(ui.lerpDouble(a.eccentricity, eccentricity, t)!, 0.0, 1.0),
);
}
return super.lerpFrom(a, t);
}
@override
ShapeBorder? lerpTo(ShapeBorder? b, double t) {
if (b is OvalBorder) {
return OvalBorder(
side: BorderSide.lerp(side, b.side, t),
eccentricity: clampDouble(ui.lerpDouble(eccentricity, b.eccentricity, t)!, 0.0, 1.0),
);
}
return super.lerpTo(b, t);
}
@override
String toString() {
if (eccentricity != 1.0) {
return '${objectRuntimeType(this, 'OvalBorder')}($side, eccentricity: $eccentricity)';
}
return '${objectRuntimeType(this, 'OvalBorder')}($side)';
}
}
| flutter/packages/flutter/lib/src/painting/oval_border.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/painting/oval_border.dart",
"repo_id": "flutter",
"token_count": 764
} | 633 |
// 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 'tolerance.dart';
export 'tolerance.dart' show Tolerance;
/// The base class for all simulations.
///
/// A simulation models an object, in a one-dimensional space, on which particular
/// forces are being applied, and exposes:
///
/// * The object's position, [x]
/// * The object's velocity, [dx]
/// * Whether the simulation is "done", [isDone]
///
/// A simulation is generally "done" if the object has, to a given [tolerance],
/// come to a complete rest.
///
/// The [x], [dx], and [isDone] functions take a time argument which specifies
/// the time for which they are to be evaluated. In principle, simulations can
/// be stateless, and thus can be queried with arbitrary times. In practice,
/// however, some simulations are not, and calling any of these functions will
/// advance the simulation to the given time.
///
/// As a general rule, therefore, a simulation should only be queried using
/// times that are equal to or greater than all times previously used for that
/// simulation.
///
/// Simulations do not specify units for distance, velocity, and time. Client
/// should establish a convention and use that convention consistently with all
/// related objects.
abstract class Simulation {
/// Initializes the [tolerance] field for subclasses.
Simulation({ this.tolerance = Tolerance.defaultTolerance });
/// The position of the object in the simulation at the given time.
double x(double time);
/// The velocity of the object in the simulation at the given time.
double dx(double time);
/// Whether the simulation is "done" at the given time.
bool isDone(double time);
/// How close to the actual end of the simulation a value at a particular time
/// must be before [isDone] considers the simulation to be "done".
///
/// A simulation with an asymptotic curve would never technically be "done",
/// but once the difference from the value at a particular time and the
/// asymptote itself could not be seen, it would be pointless to continue. The
/// tolerance defines how to determine if the difference could not be seen.
Tolerance tolerance;
@override
String toString() => objectRuntimeType(this, 'Simulation');
}
| flutter/packages/flutter/lib/src/physics/simulation.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/physics/simulation.dart",
"repo_id": "flutter",
"token_count": 602
} | 634 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui show Image;
import 'package:flutter/animation.dart';
import 'package:flutter/foundation.dart';
import 'box.dart';
import 'object.dart';
export 'package:flutter/painting.dart' show
BoxFit,
ImageRepeat;
/// An image in the render tree.
///
/// The render image attempts to find a size for itself that fits in the given
/// constraints and preserves the image's intrinsic aspect ratio.
///
/// The image is painted using [paintImage], which describes the meanings of the
/// various fields on this class in more detail.
class RenderImage extends RenderBox {
/// Creates a render box that displays an image.
///
/// The [textDirection] argument must not be null if [alignment] will need
/// resolving or if [matchTextDirection] is true.
RenderImage({
ui.Image? image,
this.debugImageLabel,
double? width,
double? height,
double scale = 1.0,
Color? color,
Animation<double>? opacity,
BlendMode? colorBlendMode,
BoxFit? fit,
AlignmentGeometry alignment = Alignment.center,
ImageRepeat repeat = ImageRepeat.noRepeat,
Rect? centerSlice,
bool matchTextDirection = false,
TextDirection? textDirection,
bool invertColors = false,
bool isAntiAlias = false,
FilterQuality filterQuality = FilterQuality.low,
}) : _image = image,
_width = width,
_height = height,
_scale = scale,
_color = color,
_opacity = opacity,
_colorBlendMode = colorBlendMode,
_fit = fit,
_alignment = alignment,
_repeat = repeat,
_centerSlice = centerSlice,
_matchTextDirection = matchTextDirection,
_invertColors = invertColors,
_textDirection = textDirection,
_isAntiAlias = isAntiAlias,
_filterQuality = filterQuality {
_updateColorFilter();
}
Alignment? _resolvedAlignment;
bool? _flipHorizontally;
void _resolve() {
if (_resolvedAlignment != null) {
return;
}
_resolvedAlignment = alignment.resolve(textDirection);
_flipHorizontally = matchTextDirection && textDirection == TextDirection.rtl;
}
void _markNeedResolution() {
_resolvedAlignment = null;
_flipHorizontally = null;
markNeedsPaint();
}
/// The image to display.
ui.Image? get image => _image;
ui.Image? _image;
set image(ui.Image? value) {
if (value == _image) {
return;
}
// If we get a clone of our image, it's the same underlying native data -
// dispose of the new clone and return early.
if (value != null && _image != null && value.isCloneOf(_image!)) {
value.dispose();
return;
}
final bool sizeChanged = _image?.width != value?.width || _image?.height != value?.height;
_image?.dispose();
_image = value;
markNeedsPaint();
if (sizeChanged && (_width == null || _height == null)) {
markNeedsLayout();
}
}
/// A string used to identify the source of the image.
String? debugImageLabel;
/// If non-null, requires the image to have this width.
///
/// If null, the image will pick a size that best preserves its intrinsic
/// aspect ratio.
double? get width => _width;
double? _width;
set width(double? value) {
if (value == _width) {
return;
}
_width = value;
markNeedsLayout();
}
/// If non-null, require the image to have this height.
///
/// If null, the image will pick a size that best preserves its intrinsic
/// aspect ratio.
double? get height => _height;
double? _height;
set height(double? value) {
if (value == _height) {
return;
}
_height = value;
markNeedsLayout();
}
/// Specifies the image's scale.
///
/// Used when determining the best display size for the image.
double get scale => _scale;
double _scale;
set scale(double value) {
if (value == _scale) {
return;
}
_scale = value;
markNeedsLayout();
}
ColorFilter? _colorFilter;
void _updateColorFilter() {
if (_color == null) {
_colorFilter = null;
} else {
_colorFilter = ColorFilter.mode(_color!, _colorBlendMode ?? BlendMode.srcIn);
}
}
/// If non-null, this color is blended with each image pixel using [colorBlendMode].
Color? get color => _color;
Color? _color;
set color(Color? value) {
if (value == _color) {
return;
}
_color = value;
_updateColorFilter();
markNeedsPaint();
}
/// If non-null, the value from the [Animation] is multiplied with the opacity
/// of each image pixel before painting onto the canvas.
Animation<double>? get opacity => _opacity;
Animation<double>? _opacity;
set opacity(Animation<double>? value) {
if (value == _opacity) {
return;
}
if (attached) {
_opacity?.removeListener(markNeedsPaint);
}
_opacity = value;
if (attached) {
value?.addListener(markNeedsPaint);
}
}
/// Used to set the filterQuality of the image.
///
/// Use the [FilterQuality.low] quality setting to scale the image, which corresponds to
/// bilinear interpolation, rather than the default [FilterQuality.none] which corresponds
/// to nearest-neighbor.
FilterQuality get filterQuality => _filterQuality;
FilterQuality _filterQuality;
set filterQuality(FilterQuality value) {
if (value == _filterQuality) {
return;
}
_filterQuality = value;
markNeedsPaint();
}
/// Used to combine [color] with this image.
///
/// The default is [BlendMode.srcIn]. In terms of the blend mode, [color] is
/// the source and this image is the destination.
///
/// See also:
///
/// * [BlendMode], which includes an illustration of the effect of each blend mode.
BlendMode? get colorBlendMode => _colorBlendMode;
BlendMode? _colorBlendMode;
set colorBlendMode(BlendMode? value) {
if (value == _colorBlendMode) {
return;
}
_colorBlendMode = value;
_updateColorFilter();
markNeedsPaint();
}
/// How to inscribe the image into the space allocated during layout.
///
/// The default varies based on the other fields. See the discussion at
/// [paintImage].
BoxFit? get fit => _fit;
BoxFit? _fit;
set fit(BoxFit? value) {
if (value == _fit) {
return;
}
_fit = value;
markNeedsPaint();
}
/// How to align the image within its bounds.
///
/// If this is set to a text-direction-dependent value, [textDirection] must
/// not be null.
AlignmentGeometry get alignment => _alignment;
AlignmentGeometry _alignment;
set alignment(AlignmentGeometry value) {
if (value == _alignment) {
return;
}
_alignment = value;
_markNeedResolution();
}
/// How to repeat this image if it doesn't fill its layout bounds.
ImageRepeat get repeat => _repeat;
ImageRepeat _repeat;
set repeat(ImageRepeat value) {
if (value == _repeat) {
return;
}
_repeat = value;
markNeedsPaint();
}
/// The center slice for a nine-patch image.
///
/// The region of the image inside the center slice will be stretched both
/// horizontally and vertically to fit the image into its destination. The
/// region of the image above and below the center slice will be stretched
/// only horizontally and the region of the image to the left and right of
/// the center slice will be stretched only vertically.
Rect? get centerSlice => _centerSlice;
Rect? _centerSlice;
set centerSlice(Rect? value) {
if (value == _centerSlice) {
return;
}
_centerSlice = value;
markNeedsPaint();
}
/// Whether to invert the colors of the image.
///
/// Inverting the colors of an image applies a new color filter to the paint.
/// If there is another specified color filter, the invert will be applied
/// after it. This is primarily used for implementing smart invert on iOS.
bool get invertColors => _invertColors;
bool _invertColors;
set invertColors(bool value) {
if (value == _invertColors) {
return;
}
_invertColors = value;
markNeedsPaint();
}
/// Whether to paint the image in the direction of the [TextDirection].
///
/// If this is true, then in [TextDirection.ltr] contexts, the image will be
/// drawn with its origin in the top left (the "normal" painting direction for
/// images); and in [TextDirection.rtl] contexts, the image will be drawn with
/// a scaling factor of -1 in the horizontal direction so that the origin is
/// in the top right.
///
/// This is occasionally used with images in right-to-left environments, for
/// images that were designed for left-to-right locales. Be careful, when
/// using this, to not flip images with integral shadows, text, or other
/// effects that will look incorrect when flipped.
///
/// If this is set to true, [textDirection] must not be null.
bool get matchTextDirection => _matchTextDirection;
bool _matchTextDirection;
set matchTextDirection(bool value) {
if (value == _matchTextDirection) {
return;
}
_matchTextDirection = value;
_markNeedResolution();
}
/// The text direction with which to resolve [alignment].
///
/// This may be changed to null, but only after the [alignment] and
/// [matchTextDirection] properties have been changed to values that do not
/// depend on the direction.
TextDirection? get textDirection => _textDirection;
TextDirection? _textDirection;
set textDirection(TextDirection? value) {
if (_textDirection == value) {
return;
}
_textDirection = value;
_markNeedResolution();
}
/// Whether to paint the image with anti-aliasing.
///
/// Anti-aliasing alleviates the sawtooth artifact when the image is rotated.
bool get isAntiAlias => _isAntiAlias;
bool _isAntiAlias;
set isAntiAlias(bool value) {
if (_isAntiAlias == value) {
return;
}
_isAntiAlias = value;
markNeedsPaint();
}
/// Find a size for the render image within the given constraints.
///
/// - The dimensions of the RenderImage must fit within the constraints.
/// - The aspect ratio of the RenderImage matches the intrinsic aspect
/// ratio of the image.
/// - The RenderImage's dimension are maximal subject to being smaller than
/// the intrinsic size of the image.
Size _sizeForConstraints(BoxConstraints constraints) {
// Folds the given |width| and |height| into |constraints| so they can all
// be treated uniformly.
constraints = BoxConstraints.tightFor(
width: _width,
height: _height,
).enforce(constraints);
if (_image == null) {
return constraints.smallest;
}
return constraints.constrainSizeAndAttemptToPreserveAspectRatio(Size(
_image!.width.toDouble() / _scale,
_image!.height.toDouble() / _scale,
));
}
@override
double computeMinIntrinsicWidth(double height) {
assert(height >= 0.0);
if (_width == null && _height == null) {
return 0.0;
}
return _sizeForConstraints(BoxConstraints.tightForFinite(height: height)).width;
}
@override
double computeMaxIntrinsicWidth(double height) {
assert(height >= 0.0);
return _sizeForConstraints(BoxConstraints.tightForFinite(height: height)).width;
}
@override
double computeMinIntrinsicHeight(double width) {
assert(width >= 0.0);
if (_width == null && _height == null) {
return 0.0;
}
return _sizeForConstraints(BoxConstraints.tightForFinite(width: width)).height;
}
@override
double computeMaxIntrinsicHeight(double width) {
assert(width >= 0.0);
return _sizeForConstraints(BoxConstraints.tightForFinite(width: width)).height;
}
@override
bool hitTestSelf(Offset position) => true;
@override
@protected
Size computeDryLayout(covariant BoxConstraints constraints) {
return _sizeForConstraints(constraints);
}
@override
void performLayout() {
size = _sizeForConstraints(constraints);
}
@override
void attach(covariant PipelineOwner owner) {
super.attach(owner);
_opacity?.addListener(markNeedsPaint);
}
@override
void detach() {
_opacity?.removeListener(markNeedsPaint);
super.detach();
}
@override
void paint(PaintingContext context, Offset offset) {
if (_image == null) {
return;
}
_resolve();
assert(_resolvedAlignment != null);
assert(_flipHorizontally != null);
paintImage(
canvas: context.canvas,
rect: offset & size,
image: _image!,
debugImageLabel: debugImageLabel,
scale: _scale,
opacity: _opacity?.value ?? 1.0,
colorFilter: _colorFilter,
fit: _fit,
alignment: _resolvedAlignment!,
centerSlice: _centerSlice,
repeat: _repeat,
flipHorizontally: _flipHorizontally!,
invertColors: invertColors,
filterQuality: _filterQuality,
isAntiAlias: _isAntiAlias,
);
}
@override
void dispose() {
_image?.dispose();
_image = null;
super.dispose();
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<ui.Image>('image', image));
properties.add(DoubleProperty('width', width, defaultValue: null));
properties.add(DoubleProperty('height', height, defaultValue: null));
properties.add(DoubleProperty('scale', scale, defaultValue: 1.0));
properties.add(ColorProperty('color', color, defaultValue: null));
properties.add(DiagnosticsProperty<Animation<double>?>('opacity', opacity, defaultValue: null));
properties.add(EnumProperty<BlendMode>('colorBlendMode', colorBlendMode, defaultValue: null));
properties.add(EnumProperty<BoxFit>('fit', fit, defaultValue: null));
properties.add(DiagnosticsProperty<AlignmentGeometry>('alignment', alignment, defaultValue: null));
properties.add(EnumProperty<ImageRepeat>('repeat', repeat, defaultValue: ImageRepeat.noRepeat));
properties.add(DiagnosticsProperty<Rect>('centerSlice', centerSlice, defaultValue: null));
properties.add(FlagProperty('matchTextDirection', value: matchTextDirection, ifTrue: 'match text direction'));
properties.add(EnumProperty<TextDirection>('textDirection', textDirection, defaultValue: null));
properties.add(DiagnosticsProperty<bool>('invertColors', invertColors));
properties.add(EnumProperty<FilterQuality>('filterQuality', filterQuality));
}
}
| flutter/packages/flutter/lib/src/rendering/image.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/rendering/image.dart",
"repo_id": "flutter",
"token_count": 4960
} | 635 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'box.dart';
import 'debug.dart';
import 'object.dart';
import 'viewport.dart';
import 'viewport_offset.dart';
// CORE TYPES FOR SLIVERS
// The RenderSliver base class and its helper types.
/// Called to get the item extent by the index of item.
///
/// Should return null if asked to build an item extent with a greater index than
/// exists.
///
/// Used by [ListView.itemExtentBuilder] and [SliverVariedExtentList.itemExtentBuilder].
typedef ItemExtentBuilder = double? Function(int index, SliverLayoutDimensions dimensions);
/// Relates the dimensions of the [RenderSliver] during layout.
///
/// Used by [ListView.itemExtentBuilder] and [SliverVariedExtentList.itemExtentBuilder].
@immutable
class SliverLayoutDimensions {
/// Constructs a [SliverLayoutDimensions] with the specified parameters.
const SliverLayoutDimensions({
required this.scrollOffset,
required this.precedingScrollExtent,
required this.viewportMainAxisExtent,
required this.crossAxisExtent
});
/// {@macro flutter.rendering.SliverConstraints.scrollOffset}
final double scrollOffset;
/// {@macro flutter.rendering.SliverConstraints.precedingScrollExtent}
final double precedingScrollExtent;
/// The number of pixels the viewport can display in the main axis.
///
/// For a vertical list, this is the height of the viewport.
final double viewportMainAxisExtent;
/// The number of pixels in the cross-axis.
///
/// For a vertical list, this is the width of the sliver.
final double crossAxisExtent;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other is! SliverLayoutDimensions) {
return false;
}
return other.scrollOffset == scrollOffset &&
other.precedingScrollExtent == precedingScrollExtent &&
other.viewportMainAxisExtent == viewportMainAxisExtent &&
other.crossAxisExtent == crossAxisExtent;
}
@override
String toString() {
return 'scrollOffset: $scrollOffset'
' precedingScrollExtent: $precedingScrollExtent'
' viewportMainAxisExtent: $viewportMainAxisExtent'
' crossAxisExtent: $crossAxisExtent';
}
@override
int get hashCode => Object.hash(
scrollOffset,
precedingScrollExtent,
viewportMainAxisExtent,
viewportMainAxisExtent
);
}
/// The direction in which a sliver's contents are ordered, relative to the
/// scroll offset axis.
///
/// For example, a vertical alphabetical list that is going [AxisDirection.down]
/// with a [GrowthDirection.forward] would have the A at the top and the Z at
/// the bottom, with the A adjacent to the origin, as would such a list going
/// [AxisDirection.up] with a [GrowthDirection.reverse]. On the other hand, a
/// vertical alphabetical list that is going [AxisDirection.down] with a
/// [GrowthDirection.reverse] would have the Z at the top (at scroll offset
/// zero) and the A below it.
///
/// {@template flutter.rendering.GrowthDirection.sample}
/// Most scroll views by default are ordered [GrowthDirection.forward].
/// Changing the default values of [ScrollView.anchor],
/// [ScrollView.center], or both, can configure a scroll view for
/// [GrowthDirection.reverse].
///
/// {@tool dartpad}
/// This sample shows a [CustomScrollView], with [Radio] buttons in the
/// [AppBar.bottom] that change the [AxisDirection] to illustrate different
/// configurations. The [CustomScrollView.anchor] and [CustomScrollView.center]
/// properties are also set to have the 0 scroll offset positioned in the middle
/// of the viewport, with [GrowthDirection.forward] and [GrowthDirection.reverse]
/// illustrated on either side. The sliver that shares the
/// [CustomScrollView.center] key is positioned at the [CustomScrollView.anchor].
///
/// ** See code in examples/api/lib/rendering/growth_direction/growth_direction.0.dart **
/// {@end-tool}
/// {@endtemplate}
///
/// See also:
///
/// * [applyGrowthDirectionToAxisDirection], which returns the direction in
/// which the scroll offset increases.
enum GrowthDirection {
/// This sliver's contents are ordered in the same direction as the
/// [AxisDirection]. For example, a vertical alphabetical list that is going
/// [AxisDirection.down] with a [GrowthDirection.forward] would have the A at
/// the top and the Z at the bottom, with the A adjacent to the origin.
///
/// See also:
///
/// * [applyGrowthDirectionToAxisDirection], which returns the direction in
/// which the scroll offset increases.
forward,
/// This sliver's contents are ordered in the opposite direction of the
/// [AxisDirection].
///
/// See also:
///
/// * [applyGrowthDirectionToAxisDirection], which returns the direction in
/// which the scroll offset increases.
reverse,
}
/// Flips the [AxisDirection] if the [GrowthDirection] is [GrowthDirection.reverse].
///
/// Specifically, returns `axisDirection` if `growthDirection` is
/// [GrowthDirection.forward], otherwise returns [flipAxisDirection] applied to
/// `axisDirection`.
///
/// This function is useful in [RenderSliver] subclasses that are given both an
/// [AxisDirection] and a [GrowthDirection] and wish to compute the
/// [AxisDirection] in which growth will occur.
AxisDirection applyGrowthDirectionToAxisDirection(AxisDirection axisDirection, GrowthDirection growthDirection) {
return switch (growthDirection) {
GrowthDirection.forward => axisDirection,
GrowthDirection.reverse => flipAxisDirection(axisDirection),
};
}
/// Flips the [ScrollDirection] if the [GrowthDirection] is
/// [GrowthDirection.reverse].
///
/// Specifically, returns `scrollDirection` if `scrollDirection` is
/// [GrowthDirection.forward], otherwise returns [flipScrollDirection] applied
/// to `scrollDirection`.
///
/// This function is useful in [RenderSliver] subclasses that are given both an
/// [ScrollDirection] and a [GrowthDirection] and wish to compute the
/// [ScrollDirection] in which growth will occur.
ScrollDirection applyGrowthDirectionToScrollDirection(ScrollDirection scrollDirection, GrowthDirection growthDirection) {
return switch (growthDirection) {
GrowthDirection.forward => scrollDirection,
GrowthDirection.reverse => flipScrollDirection(scrollDirection),
};
}
/// Immutable layout constraints for [RenderSliver] layout.
///
/// The [SliverConstraints] describe the current scroll state of the viewport
/// from the point of view of the sliver receiving the constraints. For example,
/// a [scrollOffset] of zero means that the leading edge of the sliver is
/// visible in the viewport, not that the viewport itself has a zero scroll
/// offset.
class SliverConstraints extends Constraints {
/// Creates sliver constraints with the given information.
const SliverConstraints({
required this.axisDirection,
required this.growthDirection,
required this.userScrollDirection,
required this.scrollOffset,
required this.precedingScrollExtent,
required this.overlap,
required this.remainingPaintExtent,
required this.crossAxisExtent,
required this.crossAxisDirection,
required this.viewportMainAxisExtent,
required this.remainingCacheExtent,
required this.cacheOrigin,
});
/// Creates a copy of this object but with the given fields replaced with the
/// new values.
SliverConstraints copyWith({
AxisDirection? axisDirection,
GrowthDirection? growthDirection,
ScrollDirection? userScrollDirection,
double? scrollOffset,
double? precedingScrollExtent,
double? overlap,
double? remainingPaintExtent,
double? crossAxisExtent,
AxisDirection? crossAxisDirection,
double? viewportMainAxisExtent,
double? remainingCacheExtent,
double? cacheOrigin,
}) {
return SliverConstraints(
axisDirection: axisDirection ?? this.axisDirection,
growthDirection: growthDirection ?? this.growthDirection,
userScrollDirection: userScrollDirection ?? this.userScrollDirection,
scrollOffset: scrollOffset ?? this.scrollOffset,
precedingScrollExtent: precedingScrollExtent ?? this.precedingScrollExtent,
overlap: overlap ?? this.overlap,
remainingPaintExtent: remainingPaintExtent ?? this.remainingPaintExtent,
crossAxisExtent: crossAxisExtent ?? this.crossAxisExtent,
crossAxisDirection: crossAxisDirection ?? this.crossAxisDirection,
viewportMainAxisExtent: viewportMainAxisExtent ?? this.viewportMainAxisExtent,
remainingCacheExtent: remainingCacheExtent ?? this.remainingCacheExtent,
cacheOrigin: cacheOrigin ?? this.cacheOrigin,
);
}
/// The direction in which the [scrollOffset] and [remainingPaintExtent]
/// increase.
///
/// {@tool dartpad}
/// This sample shows a [CustomScrollView], with [Radio] buttons in the
/// [AppBar.bottom] that change the [AxisDirection] to illustrate different
/// configurations.
///
/// ** See code in examples/api/lib/painting/axis_direction/axis_direction.0.dart **
/// {@end-tool}
final AxisDirection axisDirection;
/// The direction in which the contents of slivers are ordered, relative to
/// the [axisDirection].
///
/// For example, if the [axisDirection] is [AxisDirection.up], and the
/// [growthDirection] is [GrowthDirection.forward], then an alphabetical list
/// will have A at the bottom, then B, then C, and so forth, with Z at the
/// top, with the bottom of the A at scroll offset zero, and the top of the Z
/// at the highest scroll offset.
///
/// If a viewport has an overall [AxisDirection] of [AxisDirection.down], then
/// slivers above the absolute zero offset will have an axis of
/// [AxisDirection.up] and a growth direction of [GrowthDirection.reverse],
/// while slivers below the absolute zero offset will have the same axis
/// direction as the viewport and a growth direction of
/// [GrowthDirection.forward]. (The slivers with a reverse growth direction
/// still see only positive scroll offsets; the scroll offsets are reversed as
/// well, with zero at the absolute zero point, and positive numbers going
/// away from there.)
///
/// Normally, the absolute zero offset is determined by the viewport's
/// [RenderViewport.center] and [RenderViewport.anchor] properties.
///
/// {@macro flutter.rendering.GrowthDirection.sample}
final GrowthDirection growthDirection;
/// The direction in which the user is attempting to scroll, relative to the
/// [axisDirection] and [growthDirection].
///
/// For example, if [growthDirection] is [GrowthDirection.forward] and
/// [axisDirection] is [AxisDirection.down], then a
/// [ScrollDirection.reverse] means that the user is scrolling down, in the
/// positive [scrollOffset] direction.
///
/// If the _user_ is not scrolling, this will return [ScrollDirection.idle]
/// even if there is (for example) a [ScrollActivity] currently animating the
/// position.
///
/// This is used by some slivers to determine how to react to a change in
/// scroll offset. For example, [RenderSliverFloatingPersistentHeader] will
/// only expand a floating app bar when the [userScrollDirection] is in the
/// positive scroll offset direction.
///
/// {@macro flutter.rendering.ScrollDirection.sample}
final ScrollDirection userScrollDirection;
/// {@template flutter.rendering.SliverConstraints.scrollOffset}
/// The scroll offset, in this sliver's coordinate system, that corresponds to
/// the earliest visible part of this sliver in the [AxisDirection] if
/// [SliverConstraints.growthDirection] is [GrowthDirection.forward] or in the opposite
/// [AxisDirection] direction if [SliverConstraints.growthDirection] is [GrowthDirection.reverse].
///
/// For example, if [AxisDirection] is [AxisDirection.down] and [SliverConstraints.growthDirection]
/// is [GrowthDirection.forward], then scroll offset is the amount the top of
/// the sliver has been scrolled past the top of the viewport.
///
/// This value is typically used to compute whether this sliver should still
/// protrude into the viewport via [SliverGeometry.paintExtent] and
/// [SliverGeometry.layoutExtent] considering how far the beginning of the
/// sliver is above the beginning of the viewport.
///
/// For slivers whose top is not past the top of the viewport, the
/// [scrollOffset] is `0` when [AxisDirection] is [AxisDirection.down] and
/// [SliverConstraints.growthDirection] is [GrowthDirection.forward]. The set of slivers with
/// [scrollOffset] `0` includes all the slivers that are below the bottom of the
/// viewport.
///
/// [SliverConstraints.remainingPaintExtent] is typically used to accomplish
/// the same goal of computing whether scrolled out slivers should still
/// partially 'protrude in' from the bottom of the viewport.
///
/// Whether this corresponds to the beginning or the end of the sliver's
/// contents depends on the [SliverConstraints.growthDirection].
/// {@endtemplate}
final double scrollOffset;
/// {@template flutter.rendering.SliverConstraints.precedingScrollExtent}
/// The scroll distance that has been consumed by all [RenderSliver]s that
/// came before this [RenderSliver].
///
/// # Edge Cases
///
/// [RenderSliver]s often lazily create their internal content as layout
/// occurs, e.g., [SliverList]. In this case, when [RenderSliver]s exceed the
/// viewport, their children are built lazily, and the [RenderSliver] does not
/// have enough information to estimate its total extent,
/// [precedingScrollExtent] will be [double.infinity] for all [RenderSliver]s
/// that appear after the lazily constructed child. This is because a total
/// [SliverGeometry.scrollExtent] cannot be calculated unless all inner
/// children have been created and sized, or the number of children and
/// estimated extents are provided. The infinite [SliverGeometry.scrollExtent]
/// will become finite as soon as enough information is available to estimate
/// the overall extent of all children within the given [RenderSliver].
///
/// [RenderSliver]s may legitimately be infinite, meaning that they can scroll
/// content forever without reaching the end. For any [RenderSliver]s that
/// appear after the infinite [RenderSliver], the [precedingScrollExtent] will
/// be [double.infinity].
/// {@endtemplate}
final double precedingScrollExtent;
/// The number of pixels from where the pixels corresponding to the
/// [scrollOffset] will be painted up to the first pixel that has not yet been
/// painted on by an earlier sliver, in the [axisDirection].
///
/// For example, if the previous sliver had a [SliverGeometry.paintExtent] of
/// 100.0 pixels but a [SliverGeometry.layoutExtent] of only 50.0 pixels,
/// then the [overlap] of this sliver will be 50.0.
///
/// This is typically ignored unless the sliver is itself going to be pinned
/// or floating and wants to avoid doing so under the previous sliver.
final double overlap;
/// The number of pixels of content that the sliver should consider providing.
/// (Providing more pixels than this is inefficient.)
///
/// The actual number of pixels provided should be specified in the
/// [RenderSliver.geometry] as [SliverGeometry.paintExtent].
///
/// This value may be infinite, for example if the viewport is an
/// unconstrained [RenderShrinkWrappingViewport].
///
/// This value may be 0.0, for example if the sliver is scrolled off the
/// bottom of a downwards vertical viewport.
final double remainingPaintExtent;
/// The number of pixels in the cross-axis.
///
/// For a vertical list, this is the width of the sliver.
final double crossAxisExtent;
/// The direction in which children should be placed in the cross axis.
///
/// Typically used in vertical lists to describe whether the ambient
/// [TextDirection] is [TextDirection.rtl] or [TextDirection.ltr].
final AxisDirection crossAxisDirection;
/// The number of pixels the viewport can display in the main axis.
///
/// For a vertical list, this is the height of the viewport.
final double viewportMainAxisExtent;
/// Where the cache area starts relative to the [scrollOffset].
///
/// Slivers that fall into the cache area located before the leading edge and
/// after the trailing edge of the viewport should still render content
/// because they are about to become visible when the user scrolls.
///
/// The [cacheOrigin] describes where the [remainingCacheExtent] starts relative
/// to the [scrollOffset]. A cache origin of 0 means that the sliver does not
/// have to provide any content before the current [scrollOffset]. A
/// [cacheOrigin] of -250.0 means that even though the first visible part of
/// the sliver will be at the provided [scrollOffset], the sliver should
/// render content starting 250.0 before the [scrollOffset] to fill the
/// cache area of the viewport.
///
/// The [cacheOrigin] is always negative or zero and will never exceed
/// -[scrollOffset]. In other words, a sliver is never asked to provide
/// content before its zero [scrollOffset].
///
/// See also:
///
/// * [RenderViewport.cacheExtent] for a description of a viewport's cache area.
final double cacheOrigin;
/// Describes how much content the sliver should provide starting from the
/// [cacheOrigin].
///
/// Not all content in the [remainingCacheExtent] will be visible as some
/// of it might fall into the cache area of the viewport.
///
/// Each sliver should start laying out content at the [cacheOrigin] and
/// try to provide as much content as the [remainingCacheExtent] allows.
///
/// The [remainingCacheExtent] is always larger or equal to the
/// [remainingPaintExtent]. Content, that falls in the [remainingCacheExtent],
/// but is outside of the [remainingPaintExtent] is currently not visible
/// in the viewport.
///
/// See also:
///
/// * [RenderViewport.cacheExtent] for a description of a viewport's cache area.
final double remainingCacheExtent;
/// The axis along which the [scrollOffset] and [remainingPaintExtent] are measured.
Axis get axis => axisDirectionToAxis(axisDirection);
/// Return what the [growthDirection] would be if the [axisDirection] was
/// either [AxisDirection.down] or [AxisDirection.right].
///
/// This is the same as [growthDirection] unless the [axisDirection] is either
/// [AxisDirection.up] or [AxisDirection.left], in which case it is the
/// opposite growth direction.
///
/// This can be useful in combination with [axis] to view the [axisDirection]
/// and [growthDirection] in different terms.
GrowthDirection get normalizedGrowthDirection {
if (axisDirectionIsReversed(axisDirection)) {
return switch (growthDirection) {
GrowthDirection.forward => GrowthDirection.reverse,
GrowthDirection.reverse => GrowthDirection.forward,
};
}
return growthDirection;
}
@override
bool get isTight => false;
@override
bool get isNormalized {
return scrollOffset >= 0.0
&& crossAxisExtent >= 0.0
&& axisDirectionToAxis(axisDirection) != axisDirectionToAxis(crossAxisDirection)
&& viewportMainAxisExtent >= 0.0
&& remainingPaintExtent >= 0.0;
}
/// Returns [BoxConstraints] that reflects the sliver constraints.
///
/// The `minExtent` and `maxExtent` are used as the constraints in the main
/// axis. If non-null, the given `crossAxisExtent` is used as a tight
/// constraint in the cross axis. Otherwise, the [crossAxisExtent] from this
/// object is used as a constraint in the cross axis.
///
/// Useful for slivers that have [RenderBox] children.
BoxConstraints asBoxConstraints({
double minExtent = 0.0,
double maxExtent = double.infinity,
double? crossAxisExtent,
}) {
crossAxisExtent ??= this.crossAxisExtent;
switch (axis) {
case Axis.horizontal:
return BoxConstraints(
minHeight: crossAxisExtent,
maxHeight: crossAxisExtent,
minWidth: minExtent,
maxWidth: maxExtent,
);
case Axis.vertical:
return BoxConstraints(
minWidth: crossAxisExtent,
maxWidth: crossAxisExtent,
minHeight: minExtent,
maxHeight: maxExtent,
);
}
}
@override
bool debugAssertIsValid({
bool isAppliedConstraint = false,
InformationCollector? informationCollector,
}) {
assert(() {
bool hasErrors = false;
final StringBuffer errorMessage = StringBuffer('\n');
void verify(bool check, String message) {
if (check) {
return;
}
hasErrors = true;
errorMessage.writeln(' $message');
}
void verifyDouble(double property, String name, {bool mustBePositive = false, bool mustBeNegative = false}) {
if (property.isNaN) {
String additional = '.';
if (mustBePositive) {
additional = ', expected greater than or equal to zero.';
} else if (mustBeNegative) {
additional = ', expected less than or equal to zero.';
}
verify(false, 'The "$name" is NaN$additional');
} else if (mustBePositive) {
verify(property >= 0.0, 'The "$name" is negative.');
} else if (mustBeNegative) {
verify(property <= 0.0, 'The "$name" is positive.');
}
}
verifyDouble(scrollOffset, 'scrollOffset');
verifyDouble(overlap, 'overlap');
verifyDouble(crossAxisExtent, 'crossAxisExtent');
verifyDouble(scrollOffset, 'scrollOffset', mustBePositive: true);
verify(axisDirectionToAxis(axisDirection) != axisDirectionToAxis(crossAxisDirection), 'The "axisDirection" and the "crossAxisDirection" are along the same axis.');
verifyDouble(viewportMainAxisExtent, 'viewportMainAxisExtent', mustBePositive: true);
verifyDouble(remainingPaintExtent, 'remainingPaintExtent', mustBePositive: true);
verifyDouble(remainingCacheExtent, 'remainingCacheExtent', mustBePositive: true);
verifyDouble(cacheOrigin, 'cacheOrigin', mustBeNegative: true);
verifyDouble(precedingScrollExtent, 'precedingScrollExtent', mustBePositive: true);
verify(isNormalized, 'The constraints are not normalized.'); // should be redundant with earlier checks
if (hasErrors) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('$runtimeType is not valid: $errorMessage'),
if (informationCollector != null)
...informationCollector(),
DiagnosticsProperty<SliverConstraints>('The offending constraints were', this, style: DiagnosticsTreeStyle.errorProperty),
]);
}
return true;
}());
return true;
}
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
if (other is! SliverConstraints) {
return false;
}
assert(other.debugAssertIsValid());
return other.axisDirection == axisDirection
&& other.growthDirection == growthDirection
&& other.userScrollDirection == userScrollDirection
&& other.scrollOffset == scrollOffset
&& other.precedingScrollExtent == precedingScrollExtent
&& other.overlap == overlap
&& other.remainingPaintExtent == remainingPaintExtent
&& other.crossAxisExtent == crossAxisExtent
&& other.crossAxisDirection == crossAxisDirection
&& other.viewportMainAxisExtent == viewportMainAxisExtent
&& other.remainingCacheExtent == remainingCacheExtent
&& other.cacheOrigin == cacheOrigin;
}
@override
int get hashCode => Object.hash(
axisDirection,
growthDirection,
userScrollDirection,
scrollOffset,
precedingScrollExtent,
overlap,
remainingPaintExtent,
crossAxisExtent,
crossAxisDirection,
viewportMainAxisExtent,
remainingCacheExtent,
cacheOrigin,
);
@override
String toString() {
final List<String> properties = <String>[
'$axisDirection',
'$growthDirection',
'$userScrollDirection',
'scrollOffset: ${scrollOffset.toStringAsFixed(1)}',
'precedingScrollExtent: ${precedingScrollExtent.toStringAsFixed(1)}',
'remainingPaintExtent: ${remainingPaintExtent.toStringAsFixed(1)}',
if (overlap != 0.0) 'overlap: ${overlap.toStringAsFixed(1)}',
'crossAxisExtent: ${crossAxisExtent.toStringAsFixed(1)}',
'crossAxisDirection: $crossAxisDirection',
'viewportMainAxisExtent: ${viewportMainAxisExtent.toStringAsFixed(1)}',
'remainingCacheExtent: ${remainingCacheExtent.toStringAsFixed(1)}',
'cacheOrigin: ${cacheOrigin.toStringAsFixed(1)}',
];
return 'SliverConstraints(${properties.join(', ')})';
}
}
/// Describes the amount of space occupied by a [RenderSliver].
///
/// A sliver can occupy space in several different ways, which is why this class
/// contains multiple values.
@immutable
class SliverGeometry with Diagnosticable {
/// Creates an object that describes the amount of space occupied by a sliver.
///
/// If the [layoutExtent] argument is null, [layoutExtent] defaults to the
/// [paintExtent]. If the [hitTestExtent] argument is null, [hitTestExtent]
/// defaults to the [paintExtent]. If [visible] is null, [visible] defaults to
/// whether [paintExtent] is greater than zero.
const SliverGeometry({
this.scrollExtent = 0.0,
this.paintExtent = 0.0,
this.paintOrigin = 0.0,
double? layoutExtent,
this.maxPaintExtent = 0.0,
this.maxScrollObstructionExtent = 0.0,
this.crossAxisExtent,
double? hitTestExtent,
bool? visible,
this.hasVisualOverflow = false,
this.scrollOffsetCorrection,
double? cacheExtent,
}) : assert(scrollOffsetCorrection != 0.0),
layoutExtent = layoutExtent ?? paintExtent,
hitTestExtent = hitTestExtent ?? paintExtent,
cacheExtent = cacheExtent ?? layoutExtent ?? paintExtent,
visible = visible ?? paintExtent > 0.0;
/// Creates a copy of this object but with the given fields replaced with the
/// new values.
SliverGeometry copyWith({
double? scrollExtent,
double? paintExtent,
double? paintOrigin,
double? layoutExtent,
double? maxPaintExtent,
double? maxScrollObstructionExtent,
double? crossAxisExtent,
double? hitTestExtent,
bool? visible,
bool? hasVisualOverflow,
double? cacheExtent,
}) {
return SliverGeometry(
scrollExtent: scrollExtent ?? this.scrollExtent,
paintExtent: paintExtent ?? this.paintExtent,
paintOrigin: paintOrigin ?? this.paintOrigin,
layoutExtent: layoutExtent ?? this.layoutExtent,
maxPaintExtent: maxPaintExtent ?? this.maxPaintExtent,
maxScrollObstructionExtent: maxScrollObstructionExtent ?? this.maxScrollObstructionExtent,
crossAxisExtent: crossAxisExtent ?? this.crossAxisExtent,
hitTestExtent: hitTestExtent ?? this.hitTestExtent,
visible: visible ?? this.visible,
hasVisualOverflow: hasVisualOverflow ?? this.hasVisualOverflow,
cacheExtent: cacheExtent ?? this.cacheExtent,
);
}
/// A sliver that occupies no space at all.
static const SliverGeometry zero = SliverGeometry();
/// The (estimated) total scrollable extent that this sliver has content for.
///
/// This is the amount of scrolling the user needs to do to get from the
/// beginning of this sliver to the end of this sliver.
///
/// The value is used to calculate the [SliverConstraints.scrollOffset] of
/// all slivers in the scrollable and thus should be provided whether the
/// sliver is currently in the viewport or not.
///
/// In a typical scrolling scenario, the [scrollExtent] is constant for a
/// sliver throughout the scrolling while [paintExtent] and [layoutExtent]
/// will progress from `0` when offscreen to between `0` and [scrollExtent]
/// as the sliver scrolls partially into and out of the screen and is
/// equal to [scrollExtent] while the sliver is entirely on screen. However,
/// these relationships can be customized to achieve more special effects.
///
/// This value must be accurate if the [paintExtent] is less than the
/// [SliverConstraints.remainingPaintExtent] provided during layout.
final double scrollExtent;
/// The visual location of the first visible part of this sliver relative to
/// its layout position.
///
/// For example, if the sliver wishes to paint visually before its layout
/// position, the [paintOrigin] is negative. The coordinate system this sliver
/// uses for painting is relative to this [paintOrigin]. In other words,
/// when [RenderSliver.paint] is called, the (0, 0) position of the [Offset]
/// given to it is at this [paintOrigin].
///
/// The coordinate system used for the [paintOrigin] itself is relative
/// to the start of this sliver's layout position rather than relative to
/// its current position on the viewport. In other words, in a typical
/// scrolling scenario, [paintOrigin] remains constant at 0.0 rather than
/// tracking from 0.0 to [SliverConstraints.viewportMainAxisExtent] as the
/// sliver scrolls past the viewport.
///
/// This value does not affect the layout of subsequent slivers. The next
/// sliver is still placed at [layoutExtent] after this sliver's layout
/// position. This value does affect where the [paintExtent] extent is
/// measured from when computing the [SliverConstraints.overlap] for the next
/// sliver.
///
/// Defaults to 0.0, which means slivers start painting at their layout
/// position by default.
final double paintOrigin;
/// The amount of currently visible visual space that was taken by the sliver
/// to render the subset of the sliver that covers all or part of the
/// [SliverConstraints.remainingPaintExtent] in the current viewport.
///
/// This value does not affect how the next sliver is positioned. In other
/// words, if this value was 100 and [layoutExtent] was 0, typical slivers
/// placed after it would end up drawing in the same 100 pixel space while
/// painting.
///
/// This must be between zero and [SliverConstraints.remainingPaintExtent].
///
/// This value is typically 0 when outside of the viewport and grows or
/// shrinks from 0 or to 0 as the sliver is being scrolled into and out of the
/// viewport unless the sliver wants to achieve a special effect and paint
/// even when scrolled away.
///
/// This contributes to the calculation for the next sliver's
/// [SliverConstraints.overlap].
final double paintExtent;
/// The distance from the first visible part of this sliver to the first
/// visible part of the next sliver, assuming the next sliver's
/// [SliverConstraints.scrollOffset] is zero.
///
/// This must be between zero and [paintExtent]. It defaults to [paintExtent].
///
/// This value is typically 0 when outside of the viewport and grows or
/// shrinks from 0 or to 0 as the sliver is being scrolled into and out of the
/// viewport unless the sliver wants to achieve a special effect and push
/// down the layout start position of subsequent slivers before the sliver is
/// even scrolled into the viewport.
final double layoutExtent;
/// The (estimated) total paint extent that this sliver would be able to
/// provide if the [SliverConstraints.remainingPaintExtent] was infinite.
///
/// This is used by viewports that implement shrink-wrapping.
///
/// By definition, this cannot be less than [paintExtent].
final double maxPaintExtent;
/// The maximum extent by which this sliver can reduce the area in which
/// content can scroll if the sliver were pinned at the edge.
///
/// Slivers that never get pinned at the edge, should return zero.
///
/// A pinned app bar is an example for a sliver that would use this setting:
/// When the app bar is pinned to the top, the area in which content can
/// actually scroll is reduced by the height of the app bar.
final double maxScrollObstructionExtent;
/// The distance from where this sliver started painting to the bottom of
/// where it should accept hits.
///
/// This must be between zero and [paintExtent]. It defaults to [paintExtent].
final double hitTestExtent;
/// Whether this sliver should be painted.
///
/// By default, this is true if [paintExtent] is greater than zero, and
/// false if [paintExtent] is zero.
final bool visible;
/// Whether this sliver has visual overflow.
///
/// By default, this is false, which means the viewport does not need to clip
/// its children. If any slivers have visual overflow, the viewport will apply
/// a clip to its children.
final bool hasVisualOverflow;
/// If this is non-zero after [RenderSliver.performLayout] returns, the scroll
/// offset will be adjusted by the parent and then the entire layout of the
/// parent will be rerun.
///
/// When the value is non-zero, the [RenderSliver] does not need to compute
/// the rest of the values when constructing the [SliverGeometry] or call
/// [RenderObject.layout] on its children since [RenderSliver.performLayout]
/// will be called again on this sliver in the same frame after the
/// [SliverConstraints.scrollOffset] correction has been applied, when the
/// proper [SliverGeometry] and layout of its children can be computed.
///
/// If the parent is also a [RenderSliver], it must propagate this value
/// in its own [RenderSliver.geometry] property until a viewport which adjusts
/// its offset based on this value.
final double? scrollOffsetCorrection;
/// How many pixels the sliver has consumed in the
/// [SliverConstraints.remainingCacheExtent].
///
/// This value should be equal to or larger than the [layoutExtent] because
/// the sliver always consumes at least the [layoutExtent] from the
/// [SliverConstraints.remainingCacheExtent] and possibly more if it falls
/// into the cache area of the viewport.
///
/// See also:
///
/// * [RenderViewport.cacheExtent] for a description of a viewport's cache area.
final double cacheExtent;
/// The amount of space allocated to the cross axis.
///
/// This value will be typically null unless it is different from
/// [SliverConstraints.crossAxisExtent]. If null, then the cross axis extent of
/// the sliver is assumed to be the same as the [SliverConstraints.crossAxisExtent].
/// This is because slivers typically consume all of the extent that is available
/// in the cross axis.
///
/// See also:
///
/// * [SliverConstrainedCrossAxis] for an example of a sliver which takes up
/// a smaller cross axis extent than the provided constraint.
/// * [SliverCrossAxisGroup] for an example of a sliver which makes use of this
/// [crossAxisExtent] to lay out their children.
final double? crossAxisExtent;
/// Asserts that this geometry is internally consistent.
///
/// Does nothing if asserts are disabled. Always returns true.
bool debugAssertIsValid({
InformationCollector? informationCollector,
}) {
assert(() {
void verify(bool check, String summary, {List<DiagnosticsNode>? details}) {
if (check) {
return;
}
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('${objectRuntimeType(this, 'SliverGeometry')} is not valid: $summary'),
...?details,
if (informationCollector != null)
...informationCollector(),
]);
}
verify(scrollExtent >= 0.0, 'The "scrollExtent" is negative.');
verify(paintExtent >= 0.0, 'The "paintExtent" is negative.');
verify(layoutExtent >= 0.0, 'The "layoutExtent" is negative.');
verify(cacheExtent >= 0.0, 'The "cacheExtent" is negative.');
if (layoutExtent > paintExtent) {
verify(false,
'The "layoutExtent" exceeds the "paintExtent".',
details: _debugCompareFloats('paintExtent', paintExtent, 'layoutExtent', layoutExtent),
);
}
// If the paintExtent is slightly more than the maxPaintExtent, but the difference is still less
// than precisionErrorTolerance, we will not throw the assert below.
if (paintExtent - maxPaintExtent > precisionErrorTolerance) {
verify(false,
'The "maxPaintExtent" is less than the "paintExtent".',
details:
_debugCompareFloats('maxPaintExtent', maxPaintExtent, 'paintExtent', paintExtent)
..add(ErrorDescription("By definition, a sliver can't paint more than the maximum that it can paint!")),
);
}
verify(hitTestExtent >= 0.0, 'The "hitTestExtent" is negative.');
verify(scrollOffsetCorrection != 0.0, 'The "scrollOffsetCorrection" is zero.');
return true;
}());
return true;
}
@override
String toStringShort() => objectRuntimeType(this, 'SliverGeometry');
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DoubleProperty('scrollExtent', scrollExtent));
if (paintExtent > 0.0) {
properties.add(DoubleProperty('paintExtent', paintExtent, unit : visible ? null : ' but not painting'));
} else if (paintExtent == 0.0) {
if (visible) {
properties.add(DoubleProperty('paintExtent', paintExtent, unit: visible ? null : ' but visible'));
}
properties.add(FlagProperty('visible', value: visible, ifFalse: 'hidden'));
} else {
// Negative paintExtent!
properties.add(DoubleProperty('paintExtent', paintExtent, tooltip: '!'));
}
properties.add(DoubleProperty('paintOrigin', paintOrigin, defaultValue: 0.0));
properties.add(DoubleProperty('layoutExtent', layoutExtent, defaultValue: paintExtent));
properties.add(DoubleProperty('maxPaintExtent', maxPaintExtent));
properties.add(DoubleProperty('hitTestExtent', hitTestExtent, defaultValue: paintExtent));
properties.add(DiagnosticsProperty<bool>('hasVisualOverflow', hasVisualOverflow, defaultValue: false));
properties.add(DoubleProperty('scrollOffsetCorrection', scrollOffsetCorrection, defaultValue: null));
properties.add(DoubleProperty('cacheExtent', cacheExtent, defaultValue: 0.0));
}
}
/// Method signature for hit testing a [RenderSliver].
///
/// Used by [SliverHitTestResult.addWithAxisOffset] to hit test [RenderSliver]
/// children.
///
/// See also:
///
/// * [RenderSliver.hitTest], which documents more details around hit testing
/// [RenderSliver]s.
typedef SliverHitTest = bool Function(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition });
/// The result of performing a hit test on [RenderSliver]s.
///
/// An instance of this class is provided to [RenderSliver.hitTest] to record
/// the result of the hit test.
class SliverHitTestResult extends HitTestResult {
/// Creates an empty hit test result for hit testing on [RenderSliver].
SliverHitTestResult() : super();
/// Wraps `result` to create a [HitTestResult] that implements the
/// [SliverHitTestResult] protocol for hit testing on [RenderSliver]s.
///
/// This method is used by [RenderObject]s that adapt between the
/// [RenderSliver]-world and the non-[RenderSliver]-world to convert a
/// (subtype of) [HitTestResult] to a [SliverHitTestResult] for hit testing on
/// [RenderSliver]s.
///
/// The [HitTestEntry] instances added to the returned [SliverHitTestResult]
/// are also added to the wrapped `result` (both share the same underlying
/// data structure to store [HitTestEntry] instances).
///
/// See also:
///
/// * [HitTestResult.wrap], which turns a [SliverHitTestResult] back into a
/// generic [HitTestResult].
/// * [BoxHitTestResult.wrap], which turns a [SliverHitTestResult] into a
/// [BoxHitTestResult] for hit testing on [RenderBox] children.
SliverHitTestResult.wrap(super.result) : super.wrap();
/// Transforms `mainAxisPosition` and `crossAxisPosition` to the local
/// coordinate system of a child for hit-testing the child.
///
/// The actual hit testing of the child needs to be implemented in the
/// provided `hitTest` callback, which is invoked with the transformed
/// `position` as argument.
///
/// For the transform `mainAxisOffset` is subtracted from `mainAxisPosition`
/// and `crossAxisOffset` is subtracted from `crossAxisPosition`.
///
/// The `paintOffset` describes how the paint position of a point painted at
/// the provided `mainAxisPosition` and `crossAxisPosition` would change after
/// `mainAxisOffset` and `crossAxisOffset` have been applied. This
/// `paintOffset` is used to properly convert [PointerEvent]s to the local
/// coordinate system of the event receiver.
///
/// The `paintOffset` may be null if `mainAxisOffset` and `crossAxisOffset` are
/// both zero.
///
/// The function returns the return value of `hitTest`.
bool addWithAxisOffset({
required Offset? paintOffset,
required double mainAxisOffset,
required double crossAxisOffset,
required double mainAxisPosition,
required double crossAxisPosition,
required SliverHitTest hitTest,
}) {
if (paintOffset != null) {
pushOffset(-paintOffset);
}
final bool isHit = hitTest(
this,
mainAxisPosition: mainAxisPosition - mainAxisOffset,
crossAxisPosition: crossAxisPosition - crossAxisOffset,
);
if (paintOffset != null) {
popTransform();
}
return isHit;
}
}
/// A hit test entry used by [RenderSliver].
///
/// The coordinate system used by this hit test entry is relative to the
/// [AxisDirection] of the target sliver.
class SliverHitTestEntry extends HitTestEntry<RenderSliver> {
/// Creates a sliver hit test entry.
SliverHitTestEntry(
super.target, {
required this.mainAxisPosition,
required this.crossAxisPosition,
});
/// The distance in the [AxisDirection] from the edge of the sliver's painted
/// area (as given by the [SliverConstraints.scrollOffset]) to the hit point.
/// This can be an unusual direction, for example in the [AxisDirection.up]
/// case this is a distance from the _bottom_ of the sliver's painted area.
final double mainAxisPosition;
/// The distance to the hit point in the axis opposite the
/// [SliverConstraints.axis].
///
/// If the cross axis is horizontal (i.e. the
/// [SliverConstraints.axisDirection] is either [AxisDirection.down] or
/// [AxisDirection.up]), then the [crossAxisPosition] is a distance from the
/// left edge of the sliver. If the cross axis is vertical (i.e. the
/// [SliverConstraints.axisDirection] is either [AxisDirection.right] or
/// [AxisDirection.left]), then the [crossAxisPosition] is a distance from the
/// top edge of the sliver.
///
/// This is always a distance from the left or top of the parent, never a
/// distance from the right or bottom.
final double crossAxisPosition;
@override
String toString() => '${target.runtimeType}@(mainAxis: $mainAxisPosition, crossAxis: $crossAxisPosition)';
}
/// Parent data structure used by parents of slivers that position their
/// children using layout offsets.
///
/// This data structure is optimized for fast layout. It is best used by parents
/// that expect to have many children whose relative positions don't change even
/// when the scroll offset does.
class SliverLogicalParentData extends ParentData {
/// The position of the child relative to the zero scroll offset.
///
/// The number of pixels from the zero scroll offset of the parent sliver
/// (the line at which its [SliverConstraints.scrollOffset] is zero) to the
/// side of the child closest to that offset. A [layoutOffset] can be null
/// when it cannot be determined. The value will be set after layout.
///
/// In a typical list, this does not change as the parent is scrolled.
///
/// Defaults to null.
double? layoutOffset;
@override
String toString() => 'layoutOffset=${layoutOffset == null ? 'None': layoutOffset!.toStringAsFixed(1)}';
}
/// Parent data for slivers that have multiple children and that position their
/// children using layout offsets.
class SliverLogicalContainerParentData extends SliverLogicalParentData with ContainerParentDataMixin<RenderSliver> { }
/// Parent data structure used by parents of slivers that position their
/// children using absolute coordinates.
///
/// For example, used by [RenderViewport].
///
/// This data structure is optimized for fast painting, at the cost of requiring
/// additional work during layout when the children change their offsets. It is
/// best used by parents that expect to have few children, especially if those
/// children will themselves be very tall relative to the parent.
class SliverPhysicalParentData extends ParentData {
/// The position of the child relative to the parent.
///
/// This is the distance from the top left visible corner of the parent to the
/// top left visible corner of the sliver.
Offset paintOffset = Offset.zero;
/// The [crossAxisFlex] factor to use for this sliver child.
///
/// If used outside of a [SliverCrossAxisGroup] widget, this value has no meaning.
///
/// If null or zero, the child is inflexible and determines its own size in the cross axis.
/// If non-zero, the amount of space the child can occupy in the cross axis is
/// determined by dividing the free space (after placing the inflexible children)
/// according to the flex factors of the flexible children.
///
/// This value is only used by the [SliverCrossAxisGroup] widget to determine
/// how to allocate its [SliverConstraints.crossAxisExtent] to its children.
///
/// See also:
///
/// * [SliverCrossAxisGroup], which lays out multiple slivers along the
/// cross axis direction.
int? crossAxisFlex;
/// Apply the [paintOffset] to the given [transform].
///
/// Used to implement [RenderObject.applyPaintTransform] by slivers that use
/// [SliverPhysicalParentData].
void applyPaintTransform(Matrix4 transform) {
// Hit test logic relies on this always providing an invertible matrix.
transform.translate(paintOffset.dx, paintOffset.dy);
}
@override
String toString() => 'paintOffset=$paintOffset';
}
/// Parent data for slivers that have multiple children and that position their
/// children using absolute coordinates.
class SliverPhysicalContainerParentData extends SliverPhysicalParentData with ContainerParentDataMixin<RenderSliver> { }
List<DiagnosticsNode> _debugCompareFloats(String labelA, double valueA, String labelB, double valueB) {
return <DiagnosticsNode>[
if (valueA.toStringAsFixed(1) != valueB.toStringAsFixed(1))
ErrorDescription(
'The $labelA is ${valueA.toStringAsFixed(1)}, but '
'the $labelB is ${valueB.toStringAsFixed(1)}.',
)
else ...<DiagnosticsNode>[
ErrorDescription('The $labelA is $valueA, but the $labelB is $valueB.'),
ErrorHint(
'Maybe you have fallen prey to floating point rounding errors, and should explicitly '
'apply the min() or max() functions, or the clamp() method, to the $labelB?',
),
],
];
}
/// Base class for the render objects that implement scroll effects in viewports.
///
/// A [RenderViewport] has a list of child slivers. Each sliver — literally a
/// slice of the viewport's contents — is laid out in turn, covering the
/// viewport in the process. (Every sliver is laid out each time, including
/// those that have zero extent because they are "scrolled off" or are beyond
/// the end of the viewport.)
///
/// Slivers participate in the _sliver protocol_, wherein during [layout] each
/// sliver receives a [SliverConstraints] object and computes a corresponding
/// [SliverGeometry] that describes where it fits in the viewport. This is
/// analogous to the box protocol used by [RenderBox], which gets a
/// [BoxConstraints] as input and computes a [Size].
///
/// Slivers have a leading edge, which is where the position described by
/// [SliverConstraints.scrollOffset] for this sliver begins. Slivers have
/// several dimensions, the primary of which is [SliverGeometry.paintExtent],
/// which describes the extent of the sliver along the main axis, starting from
/// the leading edge, reaching either the end of the viewport or the end of the
/// sliver, whichever comes first.
///
/// Slivers can change dimensions based on the changing constraints in a
/// non-linear fashion, to achieve various scroll effects. For example, the
/// various [RenderSliverPersistentHeader] subclasses, on which [SliverAppBar]
/// is based, achieve effects such as staying visible despite the scroll offset,
/// or reappearing at different offsets based on the user's scroll direction
/// ([SliverConstraints.userScrollDirection]).
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=Mz3kHQxBjGg}
///
/// ## Writing a RenderSliver subclass
///
/// Slivers can have sliver children, or children from another coordinate
/// system, typically box children. (For details on the box protocol, see
/// [RenderBox].) Slivers can also have different child models, typically having
/// either one child, or a list of children.
///
/// ### Examples of slivers
///
/// A good example of a sliver with a single child that is also itself a sliver
/// is [RenderSliverPadding], which indents its child. A sliver-to-sliver render
/// object such as this must construct a [SliverConstraints] object for its
/// child, then must take its child's [SliverGeometry] and use it to form its
/// own [geometry].
///
/// The other common kind of one-child sliver is a sliver that has a single
/// [RenderBox] child. An example of that would be [RenderSliverToBoxAdapter],
/// which lays out a single box and sizes itself around the box. Such a sliver
/// must use its [SliverConstraints] to create a [BoxConstraints] for the
/// child, lay the child out (using the child's [layout] method), and then use
/// the child's [RenderBox.size] to generate the sliver's [SliverGeometry].
///
/// The most common kind of sliver though is one with multiple children. The
/// most straight-forward example of this is [RenderSliverList], which arranges
/// its children one after the other in the main axis direction. As with the
/// one-box-child sliver case, it uses its [constraints] to create a
/// [BoxConstraints] for the children, and then it uses the aggregate
/// information from all its children to generate its [geometry]. Unlike the
/// one-child cases, however, it is judicious in which children it actually lays
/// out (and later paints). If the scroll offset is 1000 pixels, and it
/// previously determined that the first three children are each 400 pixels
/// tall, then it will skip the first two and start the layout with its third
/// child.
///
/// ### Layout
///
/// As they are laid out, slivers decide their [geometry], which includes their
/// size ([SliverGeometry.paintExtent]) and the position of the next sliver
/// ([SliverGeometry.layoutExtent]), as well as the position of each of their
/// children, based on the input [constraints] from the viewport such as the
/// scroll offset ([SliverConstraints.scrollOffset]).
///
/// For example, a sliver that just paints a box 100 pixels high would say its
/// [SliverGeometry.paintExtent] was 100 pixels when the scroll offset was zero,
/// but would say its [SliverGeometry.paintExtent] was 25 pixels when the scroll
/// offset was 75 pixels, and would say it was zero when the scroll offset was
/// 100 pixels or more. (This is assuming that
/// [SliverConstraints.remainingPaintExtent] was more than 100 pixels.)
///
/// The various dimensions that are provided as input to this system are in the
/// [constraints]. They are described in detail in the documentation for the
/// [SliverConstraints] class.
///
/// The [performLayout] function must take these [constraints] and create a
/// [SliverGeometry] object that it must then assign to the [geometry] property.
/// The different dimensions of the geometry that can be configured are
/// described in detail in the documentation for the [SliverGeometry] class.
///
/// ### Painting
///
/// In addition to implementing layout, a sliver must also implement painting.
/// This is achieved by overriding the [paint] method.
///
/// The [paint] method is called with an [Offset] from the [Canvas] origin to
/// the top-left corner of the sliver, _regardless of the axis direction_.
///
/// Subclasses should also override [applyPaintTransform] to provide the
/// [Matrix4] describing the position of each child relative to the sliver.
/// (This is used by, among other things, the accessibility layer, to determine
/// the bounds of the child.)
///
/// ### Hit testing
///
/// To implement hit testing, either override the [hitTestSelf] and
/// [hitTestChildren] methods, or, for more complex cases, instead override the
/// [hitTest] method directly.
///
/// To actually react to pointer events, the [handleEvent] method may be
/// implemented. By default it does nothing. (Typically gestures are handled by
/// widgets in the box protocol, not by slivers directly.)
///
/// ### Helper methods
///
/// There are a number of methods that a sliver should implement which will make
/// the other methods easier to implement. Each method listed below has detailed
/// documentation. In addition, the [RenderSliverHelpers] class can be used to
/// mix in some helpful methods.
///
/// #### childScrollOffset
///
/// If the subclass positions children anywhere other than at scroll offset
/// zero, it should override [childScrollOffset]. For example,
/// [RenderSliverList] and [RenderSliverGrid] override this method, but
/// [RenderSliverToBoxAdapter] does not.
///
/// This is used by, among other things, [Scrollable.ensureVisible].
///
/// #### childMainAxisPosition
///
/// Subclasses should implement [childMainAxisPosition] to describe where their
/// children are positioned.
///
/// #### childCrossAxisPosition
///
/// If the subclass positions children in the cross-axis at a position other
/// than zero, then it should override [childCrossAxisPosition]. For example
/// [RenderSliverGrid] overrides this method.
abstract class RenderSliver extends RenderObject {
// layout input
@override
SliverConstraints get constraints => super.constraints as SliverConstraints;
/// The amount of space this sliver occupies.
///
/// This value is stale whenever this object is marked as needing layout.
/// During [performLayout], do not read the [geometry] of a child unless you
/// pass true for parentUsesSize when calling the child's [layout] function.
///
/// The geometry of a sliver should be set only during the sliver's
/// [performLayout] or [performResize] functions. If you wish to change the
/// geometry of a sliver outside of those functions, call [markNeedsLayout]
/// instead to schedule a layout of the sliver.
SliverGeometry? get geometry => _geometry;
SliverGeometry? _geometry;
set geometry(SliverGeometry? value) {
assert(!(debugDoingThisResize && debugDoingThisLayout));
assert(sizedByParent || !debugDoingThisResize);
assert(() {
if ((sizedByParent && debugDoingThisResize) ||
(!sizedByParent && debugDoingThisLayout)) {
return true;
}
assert(!debugDoingThisResize);
DiagnosticsNode? contract, violation, hint;
if (debugDoingThisLayout) {
assert(sizedByParent);
violation = ErrorDescription('It appears that the geometry setter was called from performLayout().');
} else {
violation = ErrorDescription('The geometry setter was called from outside layout (neither performResize() nor performLayout() were being run for this object).');
if (owner != null && owner!.debugDoingLayout) {
hint = ErrorDescription('Only the object itself can set its geometry. It is a contract violation for other objects to set it.');
}
}
if (sizedByParent) {
contract = ErrorDescription('Because this RenderSliver has sizedByParent set to true, it must set its geometry in performResize().');
} else {
contract = ErrorDescription('Because this RenderSliver has sizedByParent set to false, it must set its geometry in performLayout().');
}
final List<DiagnosticsNode> information = <DiagnosticsNode>[
ErrorSummary('RenderSliver geometry setter called incorrectly.'),
violation,
if (hint != null) hint,
contract,
describeForError('The RenderSliver in question is'),
];
throw FlutterError.fromParts(information);
}());
_geometry = value;
}
@override
Rect get semanticBounds => paintBounds;
@override
Rect get paintBounds {
switch (constraints.axis) {
case Axis.horizontal:
return Rect.fromLTWH(
0.0, 0.0,
geometry!.paintExtent,
constraints.crossAxisExtent,
);
case Axis.vertical:
return Rect.fromLTWH(
0.0, 0.0,
constraints.crossAxisExtent,
geometry!.paintExtent,
);
}
}
@override
void debugResetSize() { }
@override
void debugAssertDoesMeetConstraints() {
assert(geometry!.debugAssertIsValid(
informationCollector: () => <DiagnosticsNode>[
describeForError('The RenderSliver that returned the offending geometry was'),
],
));
assert(() {
if (geometry!.paintOrigin + geometry!.paintExtent > constraints.remainingPaintExtent) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('SliverGeometry has a paintOffset that exceeds the remainingPaintExtent from the constraints.'),
describeForError('The render object whose geometry violates the constraints is the following'),
..._debugCompareFloats(
'remainingPaintExtent', constraints.remainingPaintExtent,
'paintOrigin + paintExtent', geometry!.paintOrigin + geometry!.paintExtent,
),
ErrorDescription(
'The paintOrigin and paintExtent must cause the child sliver to paint '
'within the viewport, and so cannot exceed the remainingPaintExtent.',
),
]);
}
return true;
}());
}
@override
void performResize() {
assert(false);
}
/// For a center sliver, the distance before the absolute zero scroll offset
/// that this sliver can cover.
///
/// For example, if an [AxisDirection.down] viewport with an
/// [RenderViewport.anchor] of 0.5 has a single sliver with a height of 100.0
/// and its [centerOffsetAdjustment] returns 50.0, then the sliver will be
/// centered in the viewport when the scroll offset is 0.0.
///
/// The distance here is in the opposite direction of the
/// [RenderViewport.axisDirection], so values will typically be positive.
double get centerOffsetAdjustment => 0.0;
/// Determines the set of render objects located at the given position.
///
/// Returns true if the given point is contained in this render object or one
/// of its descendants. Adds any render objects that contain the point to the
/// given hit test result.
///
/// The caller is responsible for providing the position in the local
/// coordinate space of the callee. The callee is responsible for checking
/// whether the given position is within its bounds.
///
/// Hit testing requires layout to be up-to-date but does not require painting
/// to be up-to-date. That means a render object can rely upon [performLayout]
/// having been called in [hitTest] but cannot rely upon [paint] having been
/// called. For example, a render object might be a child of a [RenderOpacity]
/// object, which calls [hitTest] on its children when its opacity is zero
/// even through it does not [paint] its children.
///
/// ## Coordinates for RenderSliver objects
///
/// The `mainAxisPosition` is the distance in the [AxisDirection] (after
/// applying the [GrowthDirection]) from the edge of the sliver's painted
/// area. This can be an unusual direction, for example in the
/// [AxisDirection.up] case this is a distance from the _bottom_ of the
/// sliver's painted area.
///
/// The `crossAxisPosition` is the distance in the other axis. If the cross
/// axis is horizontal (i.e. the [SliverConstraints.axisDirection] is either
/// [AxisDirection.down] or [AxisDirection.up]), then the `crossAxisPosition`
/// is a distance from the left edge of the sliver. If the cross axis is
/// vertical (i.e. the [SliverConstraints.axisDirection] is either
/// [AxisDirection.right] or [AxisDirection.left]), then the
/// `crossAxisPosition` is a distance from the top edge of the sliver.
///
/// ## Implementing hit testing for slivers
///
/// The most straight-forward way to implement hit testing for a new sliver
/// render object is to override its [hitTestSelf] and [hitTestChildren]
/// methods.
bool hitTest(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) {
if (mainAxisPosition >= 0.0 && mainAxisPosition < geometry!.hitTestExtent &&
crossAxisPosition >= 0.0 && crossAxisPosition < constraints.crossAxisExtent) {
if (hitTestChildren(result, mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition) ||
hitTestSelf(mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition)) {
result.add(SliverHitTestEntry(
this,
mainAxisPosition: mainAxisPosition,
crossAxisPosition: crossAxisPosition,
));
return true;
}
}
return false;
}
/// Override this method if this render object can be hit even if its
/// children were not hit.
///
/// Used by [hitTest]. If you override [hitTest] and do not call this
/// function, then you don't need to implement this function.
///
/// For a discussion of the semantics of the arguments, see [hitTest].
@protected
bool hitTestSelf({ required double mainAxisPosition, required double crossAxisPosition }) => false;
/// Override this method to check whether any children are located at the
/// given position.
///
/// Typically children should be hit-tested in reverse paint order so that
/// hit tests at locations where children overlap hit the child that is
/// visually "on top" (i.e., paints later).
///
/// Used by [hitTest]. If you override [hitTest] and do not call this
/// function, then you don't need to implement this function.
///
/// For a discussion of the semantics of the arguments, see [hitTest].
@protected
bool hitTestChildren(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) => false;
/// Computes the portion of the region from `from` to `to` that is visible,
/// assuming that only the region from the [SliverConstraints.scrollOffset]
/// that is [SliverConstraints.remainingPaintExtent] high is visible, and that
/// the relationship between scroll offsets and paint offsets is linear.
///
/// For example, if the constraints have a scroll offset of 100 and a
/// remaining paint extent of 100, and the arguments to this method describe
/// the region 50..150, then the returned value would be 50 (from scroll
/// offset 100 to scroll offset 150).
///
/// This method is not useful if there is not a 1:1 relationship between
/// consumed scroll offset and consumed paint extent. For example, if the
/// sliver always paints the same amount but consumes a scroll offset extent
/// that is proportional to the [SliverConstraints.scrollOffset], then this
/// function's results will not be consistent.
// This could be a static method but isn't, because it would be less convenient
// to call it from subclasses if it was.
double calculatePaintOffset(SliverConstraints constraints, { required double from, required double to }) {
assert(from <= to);
final double a = constraints.scrollOffset;
final double b = constraints.scrollOffset + constraints.remainingPaintExtent;
// the clamp on the next line is to avoid floating point rounding errors
return clampDouble(clampDouble(to, a, b) - clampDouble(from, a, b), 0.0, constraints.remainingPaintExtent);
}
/// Computes the portion of the region from `from` to `to` that is within
/// the cache extent of the viewport, assuming that only the region from the
/// [SliverConstraints.cacheOrigin] that is
/// [SliverConstraints.remainingCacheExtent] high is visible, and that
/// the relationship between scroll offsets and paint offsets is linear.
///
/// This method is not useful if there is not a 1:1 relationship between
/// consumed scroll offset and consumed cache extent.
double calculateCacheOffset(SliverConstraints constraints, { required double from, required double to }) {
assert(from <= to);
final double a = constraints.scrollOffset + constraints.cacheOrigin;
final double b = constraints.scrollOffset + constraints.remainingCacheExtent;
// the clamp on the next line is to avoid floating point rounding errors
return clampDouble(clampDouble(to, a, b) - clampDouble(from, a, b), 0.0, constraints.remainingCacheExtent);
}
/// Returns the distance from the leading _visible_ edge of the sliver to the
/// side of the given child closest to that edge.
///
/// For example, if the [constraints] describe this sliver as having an axis
/// direction of [AxisDirection.down], then this is the distance from the top
/// of the visible portion of the sliver to the top of the child. On the other
/// hand, if the [constraints] describe this sliver as having an axis
/// direction of [AxisDirection.up], then this is the distance from the bottom
/// of the visible portion of the sliver to the bottom of the child. In both
/// cases, this is the direction of increasing
/// [SliverConstraints.scrollOffset] and
/// [SliverLogicalParentData.layoutOffset].
///
/// For children that are [RenderSliver]s, the leading edge of the _child_
/// will be the leading _visible_ edge of the child, not the part of the child
/// that would locally be a scroll offset 0.0. For children that are not
/// [RenderSliver]s, for example a [RenderBox] child, it's the actual distance
/// to the edge of the box, since those boxes do not know how to handle being
/// scrolled.
///
/// This method differs from [childScrollOffset] in that
/// [childMainAxisPosition] gives the distance from the leading _visible_ edge
/// of the sliver whereas [childScrollOffset] gives the distance from the
/// sliver's zero scroll offset.
///
/// Calling this for a child that is not visible is not valid.
@protected
double childMainAxisPosition(covariant RenderObject child) {
assert(() {
throw FlutterError('${objectRuntimeType(this, 'RenderSliver')} does not implement childPosition.');
}());
return 0.0;
}
/// Returns the distance along the cross axis from the zero of the cross axis
/// in this sliver's [paint] coordinate space to the nearest side of the given
/// child.
///
/// For example, if the [constraints] describe this sliver as having an axis
/// direction of [AxisDirection.down], then this is the distance from the left
/// of the sliver to the left of the child. Similarly, if the [constraints]
/// describe this sliver as having an axis direction of [AxisDirection.up],
/// then this is value is the same. If the axis direction is
/// [AxisDirection.left] or [AxisDirection.right], then it is the distance
/// from the top of the sliver to the top of the child.
///
/// Calling this for a child that is not visible is not valid.
@protected
double childCrossAxisPosition(covariant RenderObject child) => 0.0;
/// Returns the scroll offset for the leading edge of the given child.
///
/// The `child` must be a child of this sliver.
///
/// This method differs from [childMainAxisPosition] in that
/// [childMainAxisPosition] gives the distance from the leading _visible_ edge
/// of the sliver whereas [childScrollOffset] gives the distance from sliver's
/// zero scroll offset.
double? childScrollOffset(covariant RenderObject child) {
assert(child.parent == this);
return 0.0;
}
@override
void applyPaintTransform(RenderObject child, Matrix4 transform) {
assert(() {
throw FlutterError('${objectRuntimeType(this, 'RenderSliver')} does not implement applyPaintTransform.');
}());
}
/// This returns a [Size] with dimensions relative to the leading edge of the
/// sliver, specifically the same offset that is given to the [paint] method.
/// This means that the dimensions may be negative.
///
/// This is only valid after [layout] has completed.
///
/// See also:
///
/// * [getAbsoluteSize], which returns absolute size.
@protected
Size getAbsoluteSizeRelativeToOrigin() {
assert(geometry != null);
assert(!debugNeedsLayout);
return switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) {
AxisDirection.up => Size(constraints.crossAxisExtent, -geometry!.paintExtent),
AxisDirection.down => Size(constraints.crossAxisExtent, geometry!.paintExtent),
AxisDirection.left => Size(-geometry!.paintExtent, constraints.crossAxisExtent),
AxisDirection.right => Size(geometry!.paintExtent, constraints.crossAxisExtent),
};
}
/// This returns the absolute [Size] of the sliver.
///
/// The dimensions are always positive and calling this is only valid after
/// [layout] has completed.
///
/// See also:
///
/// * [getAbsoluteSizeRelativeToOrigin], which returns the size relative to
/// the leading edge of the sliver.
@protected
Size getAbsoluteSize() {
assert(geometry != null);
assert(!debugNeedsLayout);
switch (constraints.axisDirection) {
case AxisDirection.up:
case AxisDirection.down:
return Size(constraints.crossAxisExtent, geometry!.paintExtent);
case AxisDirection.right:
case AxisDirection.left:
return Size(geometry!.paintExtent, constraints.crossAxisExtent);
}
}
void _debugDrawArrow(Canvas canvas, Paint paint, Offset p0, Offset p1, GrowthDirection direction) {
assert(() {
if (p0 == p1) {
return true;
}
assert(p0.dx == p1.dx || p0.dy == p1.dy); // must be axis-aligned
final double d = (p1 - p0).distance * 0.2;
final Offset temp;
double dx1, dx2, dy1, dy2;
switch (direction) {
case GrowthDirection.forward:
dx1 = dx2 = dy1 = dy2 = d;
case GrowthDirection.reverse:
temp = p0;
p0 = p1;
p1 = temp;
dx1 = dx2 = dy1 = dy2 = -d;
}
if (p0.dx == p1.dx) {
dx2 = -dx2;
} else {
dy2 = -dy2;
}
canvas.drawPath(
Path()
..moveTo(p0.dx, p0.dy)
..lineTo(p1.dx, p1.dy)
..moveTo(p1.dx - dx1, p1.dy - dy1)
..lineTo(p1.dx, p1.dy)
..lineTo(p1.dx - dx2, p1.dy - dy2),
paint,
);
return true;
}());
}
@override
void debugPaint(PaintingContext context, Offset offset) {
assert(() {
if (debugPaintSizeEnabled) {
final double strokeWidth = math.min(4.0, geometry!.paintExtent / 30.0);
final Paint paint = Paint()
..color = const Color(0xFF33CC33)
..strokeWidth = strokeWidth
..style = PaintingStyle.stroke
..maskFilter = MaskFilter.blur(BlurStyle.solid, strokeWidth);
final double arrowExtent = geometry!.paintExtent;
final double padding = math.max(2.0, strokeWidth);
final Canvas canvas = context.canvas;
canvas.drawCircle(
offset.translate(padding, padding),
padding * 0.5,
paint,
);
switch (constraints.axis) {
case Axis.vertical:
canvas.drawLine(
offset,
offset.translate(constraints.crossAxisExtent, 0.0),
paint,
);
_debugDrawArrow(
canvas,
paint,
offset.translate(constraints.crossAxisExtent * 1.0 / 4.0, padding),
offset.translate(constraints.crossAxisExtent * 1.0 / 4.0, arrowExtent - padding),
constraints.normalizedGrowthDirection,
);
_debugDrawArrow(
canvas,
paint,
offset.translate(constraints.crossAxisExtent * 3.0 / 4.0, padding),
offset.translate(constraints.crossAxisExtent * 3.0 / 4.0, arrowExtent - padding),
constraints.normalizedGrowthDirection,
);
case Axis.horizontal:
canvas.drawLine(
offset,
offset.translate(0.0, constraints.crossAxisExtent),
paint,
);
_debugDrawArrow(
canvas,
paint,
offset.translate(padding, constraints.crossAxisExtent * 1.0 / 4.0),
offset.translate(arrowExtent - padding, constraints.crossAxisExtent * 1.0 / 4.0),
constraints.normalizedGrowthDirection,
);
_debugDrawArrow(
canvas,
paint,
offset.translate(padding, constraints.crossAxisExtent * 3.0 / 4.0),
offset.translate(arrowExtent - padding, constraints.crossAxisExtent * 3.0 / 4.0),
constraints.normalizedGrowthDirection,
);
}
}
return true;
}());
}
// This override exists only to change the type of the second argument.
@override
void handleEvent(PointerEvent event, SliverHitTestEntry entry) { }
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<SliverGeometry>('geometry', geometry));
}
}
/// Mixin for [RenderSliver] subclasses that provides some utility functions.
mixin RenderSliverHelpers implements RenderSliver {
bool _getRightWayUp(SliverConstraints constraints) {
final bool reversed = axisDirectionIsReversed(constraints.axisDirection);
return switch (constraints.growthDirection) {
GrowthDirection.forward => !reversed,
GrowthDirection.reverse => reversed,
};
}
/// Utility function for [hitTestChildren] for use when the children are
/// [RenderBox] widgets.
///
/// This function takes care of converting the position from the sliver
/// coordinate system to the Cartesian coordinate system used by [RenderBox].
///
/// This function relies on [childMainAxisPosition] to determine the position of
/// child in question.
///
/// Calling this for a child that is not visible is not valid.
@protected
bool hitTestBoxChild(BoxHitTestResult result, RenderBox child, { required double mainAxisPosition, required double crossAxisPosition }) {
final bool rightWayUp = _getRightWayUp(constraints);
double delta = childMainAxisPosition(child);
final double crossAxisDelta = childCrossAxisPosition(child);
double absolutePosition = mainAxisPosition - delta;
final double absoluteCrossAxisPosition = crossAxisPosition - crossAxisDelta;
Offset paintOffset, transformedPosition;
switch (constraints.axis) {
case Axis.horizontal:
if (!rightWayUp) {
absolutePosition = child.size.width - absolutePosition;
delta = geometry!.paintExtent - child.size.width - delta;
}
paintOffset = Offset(delta, crossAxisDelta);
transformedPosition = Offset(absolutePosition, absoluteCrossAxisPosition);
case Axis.vertical:
if (!rightWayUp) {
absolutePosition = child.size.height - absolutePosition;
delta = geometry!.paintExtent - child.size.height - delta;
}
paintOffset = Offset(crossAxisDelta, delta);
transformedPosition = Offset(absoluteCrossAxisPosition, absolutePosition);
}
return result.addWithOutOfBandPosition(
paintOffset: paintOffset,
hitTest: (BoxHitTestResult result) {
return child.hitTest(result, position: transformedPosition);
},
);
}
/// Utility function for [applyPaintTransform] for use when the children are
/// [RenderBox] widgets.
///
/// This function turns the value returned by [childMainAxisPosition] and
/// [childCrossAxisPosition]for the child in question into a translation that
/// it then applies to the given matrix.
///
/// Calling this for a child that is not visible is not valid.
@protected
void applyPaintTransformForBoxChild(RenderBox child, Matrix4 transform) {
final bool rightWayUp = _getRightWayUp(constraints);
double delta = childMainAxisPosition(child);
final double crossAxisDelta = childCrossAxisPosition(child);
switch (constraints.axis) {
case Axis.horizontal:
if (!rightWayUp) {
delta = geometry!.paintExtent - child.size.width - delta;
}
transform.translate(delta, crossAxisDelta);
case Axis.vertical:
if (!rightWayUp) {
delta = geometry!.paintExtent - child.size.height - delta;
}
transform.translate(crossAxisDelta, delta);
}
}
}
// ADAPTER FOR RENDER BOXES INSIDE SLIVERS
// Transitions from the RenderSliver world to the RenderBox world.
/// An abstract class for [RenderSliver]s that contains a single [RenderBox].
///
/// See also:
///
/// * [RenderSliver], which explains more about the Sliver protocol.
/// * [RenderBox], which explains more about the Box protocol.
/// * [RenderSliverToBoxAdapter], which extends this class to size the child
/// according to its preferred size.
/// * [RenderSliverFillRemaining], which extends this class to size the child
/// to fill the remaining space in the viewport.
abstract class RenderSliverSingleBoxAdapter extends RenderSliver with RenderObjectWithChildMixin<RenderBox>, RenderSliverHelpers {
/// Creates a [RenderSliver] that wraps a [RenderBox].
RenderSliverSingleBoxAdapter({
RenderBox? child,
}) {
this.child = child;
}
@override
void setupParentData(RenderObject child) {
if (child.parentData is! SliverPhysicalParentData) {
child.parentData = SliverPhysicalParentData();
}
}
/// Sets the [SliverPhysicalParentData.paintOffset] for the given child
/// according to the [SliverConstraints.axisDirection] and
/// [SliverConstraints.growthDirection] and the given geometry.
@protected
void setChildParentData(RenderObject child, SliverConstraints constraints, SliverGeometry geometry) {
final SliverPhysicalParentData childParentData = child.parentData! as SliverPhysicalParentData;
childParentData.paintOffset = switch (applyGrowthDirectionToAxisDirection(constraints.axisDirection, constraints.growthDirection)) {
AxisDirection.up => Offset(0.0, geometry.paintExtent + constraints.scrollOffset - geometry.scrollExtent),
AxisDirection.left => Offset(geometry.paintExtent + constraints.scrollOffset - geometry.scrollExtent, 0.0),
AxisDirection.right => Offset(-constraints.scrollOffset, 0.0),
AxisDirection.down => Offset(0.0, -constraints.scrollOffset),
};
}
@override
bool hitTestChildren(SliverHitTestResult result, { required double mainAxisPosition, required double crossAxisPosition }) {
assert(geometry!.hitTestExtent > 0.0);
if (child != null) {
return hitTestBoxChild(BoxHitTestResult.wrap(result), child!, mainAxisPosition: mainAxisPosition, crossAxisPosition: crossAxisPosition);
}
return false;
}
@override
double childMainAxisPosition(RenderBox child) {
return -constraints.scrollOffset;
}
@override
void applyPaintTransform(RenderObject child, Matrix4 transform) {
assert(child == this.child);
final SliverPhysicalParentData childParentData = child.parentData! as SliverPhysicalParentData;
childParentData.applyPaintTransform(transform);
}
@override
void paint(PaintingContext context, Offset offset) {
if (child != null && geometry!.visible) {
final SliverPhysicalParentData childParentData = child!.parentData! as SliverPhysicalParentData;
context.paintChild(child!, offset + childParentData.paintOffset);
}
}
}
/// A [RenderSliver] that contains a single [RenderBox].
///
/// The child will not be laid out if it is not visible. It is sized according
/// to the child's preferences in the main axis, and with a tight constraint
/// forcing it to the dimensions of the viewport in the cross axis.
///
/// See also:
///
/// * [RenderSliver], which explains more about the Sliver protocol.
/// * [RenderBox], which explains more about the Box protocol.
/// * [RenderViewport], which allows [RenderSliver] objects to be placed inside
/// a [RenderBox] (the opposite of this class).
class RenderSliverToBoxAdapter extends RenderSliverSingleBoxAdapter {
/// Creates a [RenderSliver] that wraps a [RenderBox].
RenderSliverToBoxAdapter({
super.child,
});
@override
void performLayout() {
if (child == null) {
geometry = SliverGeometry.zero;
return;
}
final SliverConstraints constraints = this.constraints;
child!.layout(constraints.asBoxConstraints(), parentUsesSize: true);
final double childExtent = switch (constraints.axis) {
Axis.horizontal => child!.size.width,
Axis.vertical => child!.size.height,
};
final double paintedChildSize = calculatePaintOffset(constraints, from: 0.0, to: childExtent);
final double cacheExtent = calculateCacheOffset(constraints, from: 0.0, to: childExtent);
assert(paintedChildSize.isFinite);
assert(paintedChildSize >= 0.0);
geometry = SliverGeometry(
scrollExtent: childExtent,
paintExtent: paintedChildSize,
cacheExtent: cacheExtent,
maxPaintExtent: childExtent,
hitTestExtent: paintedChildSize,
hasVisualOverflow: childExtent > constraints.remainingPaintExtent || constraints.scrollOffset > 0.0,
);
setChildParentData(child!, constraints, geometry!);
}
}
| flutter/packages/flutter/lib/src/rendering/sliver.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/rendering/sliver.dart",
"repo_id": "flutter",
"token_count": 25843
} | 636 |
// 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/foundation.dart';
/// The direction of a scroll, relative to the positive scroll offset axis given
/// by an [AxisDirection] and a [GrowthDirection].
///
/// This is similar to [GrowthDirection], but contrasts in that it has a third
/// value, [idle], for the case where no scroll is occurring.
///
/// This is used by [RenderSliverFloatingPersistentHeader] to only expand when
/// the user is scrolling in the same direction as the detected scroll offset
/// change.
///
/// {@template flutter.rendering.ScrollDirection.sample}
/// {@tool dartpad}
/// This sample shows a [CustomScrollView], with [Radio] buttons in the
/// [AppBar.bottom] that change the [AxisDirection] to illustrate different
/// configurations. With a [NotificationListener] to listen to
/// [UserScrollNotification]s, which occur when the [ScrollDirection] changes
/// or stops.
///
/// ** See code in examples/api/lib/rendering/scroll_direction/scroll_direction.0.dart **
/// {@end-tool}
/// {@endtemplate}
///
/// See also:
///
/// * [AxisDirection], which is a directional version of this enum (with values
/// like left and right, rather than just horizontal).
/// * [GrowthDirection], the direction in which slivers and their content are
/// ordered, relative to the scroll offset axis as specified by
/// [AxisDirection].
/// * [UserScrollNotification], which will notify listeners when the
/// [ScrollDirection] changes.
enum ScrollDirection {
/// No scrolling is underway.
idle,
/// Scrolling is happening in the negative scroll offset direction.
///
/// For example, for the [GrowthDirection.forward] part of a vertical
/// [AxisDirection.down] list, which is the default directional configuration
/// of all scroll views, this means the content is going down, exposing
/// earlier content as it approaches the zero position.
///
/// An anecdote for this most common case is 'forward is toward' the zero
/// position.
forward,
/// Scrolling is happening in the positive scroll offset direction.
///
/// For example, for the [GrowthDirection.forward] part of a vertical
/// [AxisDirection.down] list, which is the default directional configuration
/// of all scroll views, this means the content is moving up, exposing
/// lower content.
///
/// An anecdote for this most common case is reversing, or backing away, from
/// the zero position.
reverse,
}
/// Returns the opposite of the given [ScrollDirection].
///
/// Specifically, returns [ScrollDirection.reverse] for [ScrollDirection.forward]
/// (and vice versa) and returns [ScrollDirection.idle] for
/// [ScrollDirection.idle].
ScrollDirection flipScrollDirection(ScrollDirection direction) {
return switch (direction) {
ScrollDirection.idle => ScrollDirection.idle,
ScrollDirection.forward => ScrollDirection.reverse,
ScrollDirection.reverse => ScrollDirection.forward,
};
}
/// Which part of the content inside the viewport should be visible.
///
/// The [pixels] value determines the scroll offset that the viewport uses to
/// select which part of its content to display. As the user scrolls the
/// viewport, this value changes, which changes the content that is displayed.
///
/// This object is a [Listenable] that notifies its listeners when [pixels]
/// changes.
///
/// See also:
///
/// * [ScrollPosition], which is a commonly used concrete subclass.
/// * [RenderViewportBase], which is a render object that uses viewport
/// offsets.
abstract class ViewportOffset extends ChangeNotifier {
/// Default constructor.
///
/// Allows subclasses to construct this object directly.
ViewportOffset() {
if (kFlutterMemoryAllocationsEnabled) {
ChangeNotifier.maybeDispatchObjectCreation(this);
}
}
/// Creates a viewport offset with the given [pixels] value.
///
/// The [pixels] value does not change unless the viewport issues a
/// correction.
factory ViewportOffset.fixed(double value) = _FixedViewportOffset;
/// Creates a viewport offset with a [pixels] value of 0.0.
///
/// The [pixels] value does not change unless the viewport issues a
/// correction.
factory ViewportOffset.zero() = _FixedViewportOffset.zero;
/// The number of pixels to offset the children in the opposite of the axis direction.
///
/// For example, if the axis direction is down, then the pixel value
/// represents the number of logical pixels to move the children _up_ the
/// screen. Similarly, if the axis direction is left, then the pixels value
/// represents the number of logical pixels to move the children to _right_.
///
/// This object notifies its listeners when this value changes (except when
/// the value changes due to [correctBy]).
double get pixels;
/// Whether the [pixels] property is available.
bool get hasPixels;
/// Called when the viewport's extents are established.
///
/// The argument is the dimension of the [RenderViewport] in the main axis
/// (e.g. the height, for a vertical viewport).
///
/// This may be called redundantly, with the same value, each frame. This is
/// called during layout for the [RenderViewport]. If the viewport is
/// configured to shrink-wrap its contents, it may be called several times,
/// since the layout is repeated each time the scroll offset is corrected.
///
/// If this is called, it is called before [applyContentDimensions]. If this
/// is called, [applyContentDimensions] will be called soon afterwards in the
/// same layout phase. If the viewport is not configured to shrink-wrap its
/// contents, then this will only be called when the viewport recomputes its
/// size (i.e. when its parent lays out), and not during normal scrolling.
///
/// If applying the viewport dimensions changes the scroll offset, return
/// false. Otherwise, return true. If you return false, the [RenderViewport]
/// will be laid out again with the new scroll offset. This is expensive. (The
/// return value is answering the question "did you accept these viewport
/// dimensions unconditionally?"; if the new dimensions change the
/// [ViewportOffset]'s actual [pixels] value, then the viewport will need to
/// be laid out again.)
bool applyViewportDimension(double viewportDimension);
/// Called when the viewport's content extents are established.
///
/// The arguments are the minimum and maximum scroll extents respectively. The
/// minimum will be equal to or less than the maximum. In the case of slivers,
/// the minimum will be equal to or less than zero, the maximum will be equal
/// to or greater than zero.
///
/// The maximum scroll extent has the viewport dimension subtracted from it.
/// For instance, if there is 100.0 pixels of scrollable content, and the
/// viewport is 80.0 pixels high, then the minimum scroll extent will
/// typically be 0.0 and the maximum scroll extent will typically be 20.0,
/// because there's only 20.0 pixels of actual scroll slack.
///
/// If applying the content dimensions changes the scroll offset, return
/// false. Otherwise, return true. If you return false, the [RenderViewport]
/// will be laid out again with the new scroll offset. This is expensive. (The
/// return value is answering the question "did you accept these content
/// dimensions unconditionally?"; if the new dimensions change the
/// [ViewportOffset]'s actual [pixels] value, then the viewport will need to
/// be laid out again.)
///
/// This is called at least once each time the [RenderViewport] is laid out,
/// even if the values have not changed. It may be called many times if the
/// scroll offset is corrected (if this returns false). This is always called
/// after [applyViewportDimension], if that method is called.
bool applyContentDimensions(double minScrollExtent, double maxScrollExtent);
/// Apply a layout-time correction to the scroll offset.
///
/// This method should change the [pixels] value by `correction`, but without
/// calling [notifyListeners]. It is called during layout by the
/// [RenderViewport], before [applyContentDimensions]. After this method is
/// called, the layout will be recomputed and that may result in this method
/// being called again, though this should be very rare.
///
/// See also:
///
/// * [jumpTo], for also changing the scroll position when not in layout.
/// [jumpTo] applies the change immediately and notifies its listeners.
void correctBy(double correction);
/// Jumps [pixels] from its current value to the given value,
/// without animation, and without checking if the new value is in range.
///
/// See also:
///
/// * [correctBy], for changing the current offset in the middle of layout
/// and that defers the notification of its listeners until after layout.
void jumpTo(double pixels);
/// Animates [pixels] from its current value to the given value.
///
/// The returned [Future] will complete when the animation ends, whether it
/// completed successfully or whether it was interrupted prematurely.
///
/// The duration must not be zero. To jump to a particular value without an
/// animation, use [jumpTo].
Future<void> animateTo(
double to, {
required Duration duration,
required Curve curve,
});
/// Calls [jumpTo] if duration is null or [Duration.zero], otherwise
/// [animateTo] is called.
///
/// If [animateTo] is called then [curve] defaults to [Curves.ease]. The
/// [clamp] parameter is ignored by this stub implementation but subclasses
/// like [ScrollPosition] handle it by adjusting [to] to prevent over or
/// underscroll.
Future<void> moveTo(
double to, {
Duration? duration,
Curve? curve,
bool? clamp,
}) {
if (duration == null || duration == Duration.zero) {
jumpTo(to);
return Future<void>.value();
} else {
return animateTo(to, duration: duration, curve: curve ?? Curves.ease);
}
}
/// The direction in which the user is trying to change [pixels], relative to
/// the viewport's [RenderViewportBase.axisDirection].
///
/// If the _user_ is not scrolling, this will return [ScrollDirection.idle]
/// even if there is (for example) a [ScrollActivity] currently animating the
/// position.
///
/// This is exposed in [SliverConstraints.userScrollDirection], which is used
/// by some slivers to determine how to react to a change in scroll offset.
/// For example, [RenderSliverFloatingPersistentHeader] will only expand a
/// floating app bar when the [userScrollDirection] is in the positive scroll
/// offset direction.
///
/// {@macro flutter.rendering.ScrollDirection.sample}
ScrollDirection get userScrollDirection;
/// Whether a viewport is allowed to change [pixels] implicitly to respond to
/// a call to [RenderObject.showOnScreen].
///
/// [RenderObject.showOnScreen] is, for example, used to bring a text field
/// fully on screen after it has received focus. This property controls
/// whether the viewport associated with this offset is allowed to change the
/// offset's [pixels] value to fulfill such a request.
bool get allowImplicitScrolling;
@override
String toString() {
final List<String> description = <String>[];
debugFillDescription(description);
return '${describeIdentity(this)}(${description.join(", ")})';
}
/// Add additional information to the given description for use by [toString].
///
/// This method makes it easier for subclasses to coordinate to provide a
/// high-quality [toString] implementation. The [toString] implementation on
/// the [State] base class calls [debugFillDescription] to collect useful
/// information from subclasses to incorporate into its return value.
///
/// Implementations of this method should start with a call to the inherited
/// method, as in `super.debugFillDescription(description)`.
@mustCallSuper
void debugFillDescription(List<String> description) {
if (hasPixels) {
description.add('offset: ${pixels.toStringAsFixed(1)}');
}
}
}
class _FixedViewportOffset extends ViewportOffset {
_FixedViewportOffset(this._pixels);
_FixedViewportOffset.zero() : _pixels = 0.0;
double _pixels;
@override
double get pixels => _pixels;
@override
bool get hasPixels => true;
@override
bool applyViewportDimension(double viewportDimension) => true;
@override
bool applyContentDimensions(double minScrollExtent, double maxScrollExtent) => true;
@override
void correctBy(double correction) {
_pixels += correction;
}
@override
void jumpTo(double pixels) {
// Do nothing, viewport is fixed.
}
@override
Future<void> animateTo(
double to, {
required Duration duration,
required Curve curve,
}) async { }
@override
ScrollDirection get userScrollDirection => ScrollDirection.idle;
@override
bool get allowImplicitScrolling => false;
}
| flutter/packages/flutter/lib/src/rendering/viewport_offset.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/rendering/viewport_offset.dart",
"repo_id": "flutter",
"token_count": 3562
} | 637 |
// 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 'text_input.dart';
export 'text_input.dart' show TextEditingValue, TextInputClient, TextInputConfiguration, TextInputConnection;
/// A collection of commonly used autofill hint strings on different platforms.
///
/// Each hint is pre-defined on at least one supported platform. See their
/// documentation for their availability on each platform, and the platform
/// values each autofill hint corresponds to.
abstract final class AutofillHints {
/// The input field expects an address locality (city/town).
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_POSTAL_ADDRESS_LOCALITY](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_POSTAL_ADDRESS_LOCALITY).
/// * iOS: [addressCity](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * Otherwise, the hint string will be used as-is.
static const String addressCity = 'addressCity';
/// The input field expects a city name combined with a state name.
///
/// This hint will be translated to the below values on different platforms:
///
/// * iOS: [addressCityAndState](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * Otherwise, the hint string will be used as-is.
static const String addressCityAndState = 'addressCityAndState';
/// The input field expects a region/state.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_POSTAL_ADDRESS_REGION](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_POSTAL_ADDRESS_REGION).
/// * iOS: [addressState](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * Otherwise, the hint string will be used as-is.
static const String addressState = 'addressState';
/// The input field expects a person's full birth date.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_BIRTH_DATE_FULL](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_BIRTH_DATE_FULL).
/// * web: ["bday"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String birthday = 'birthday';
/// The input field expects a person's birth day(of the month).
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_BIRTH_DATE_DAY](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_BIRTH_DATE_DAY).
/// * web: ["bday-day"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String birthdayDay = 'birthdayDay';
/// The input field expects a person's birth month.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_BIRTH_DATE_MONTH](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_BIRTH_DATE_MONTH).
/// * web: ["bday-month"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String birthdayMonth = 'birthdayMonth';
/// The input field expects a person's birth year.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_BIRTH_DATE_YEAR](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_BIRTH_DATE_YEAR).
/// * web: ["bday-year"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String birthdayYear = 'birthdayYear';
/// The input field expects an
/// [ISO 3166-1-alpha-2](https://www.iso.org/standard/63545.html) country code.
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["country"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String countryCode = 'countryCode';
/// The input field expects a country name.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_POSTAL_ADDRESS_COUNTRY](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_POSTAL_ADDRESS_COUNTRY).
/// * iOS: [countryName](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["country-name"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String countryName = 'countryName';
/// The input field expects a credit card expiration date.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_CREDIT_CARD_NUMBER](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_CREDIT_CARD_NUMBER).
/// * web: ["cc-exp"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String creditCardExpirationDate = 'creditCardExpirationDate';
/// The input field expects a credit card expiration day.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DAY).
/// * Otherwise, the hint string will be used as-is.
static const String creditCardExpirationDay = 'creditCardExpirationDay';
/// The input field expects a credit card expiration month.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_MONTH).
/// * web: ["cc-exp-month"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String creditCardExpirationMonth = 'creditCardExpirationMonth';
/// The input field expects a credit card expiration year.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_YEAR).
/// * web: ["cc-exp-year"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String creditCardExpirationYear = 'creditCardExpirationYear';
/// The input field expects the holder's last/family name as given on a credit
/// card.
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["cc-family-name"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String creditCardFamilyName = 'creditCardFamilyName';
/// The input field expects the holder's first/given name as given on a credit
/// card.
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["cc-given-name"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String creditCardGivenName = 'creditCardGivenName';
/// The input field expects the holder's middle name as given on a credit
/// card.
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["cc-additional-name"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String creditCardMiddleName = 'creditCardMiddleName';
/// The input field expects the holder's full name as given on a credit card.
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["cc-name"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String creditCardName = 'creditCardName';
/// The input field expects a credit card number.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_CREDIT_CARD_NUMBER](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_CREDIT_CARD_NUMBER).
/// * iOS: [creditCardNumber](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["cc-number"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String creditCardNumber = 'creditCardNumber';
/// The input field expects a credit card security code.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_CREDIT_CARD_SECURITY_CODE).
/// * web: ["cc-csc"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String creditCardSecurityCode = 'creditCardSecurityCode';
/// The input field expects the type of a credit card, for example "Visa".
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["cc-type"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String creditCardType = 'creditCardType';
/// The input field expects an email address.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_EMAIL_ADDRESS](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_EMAIL_ADDRESS).
/// * iOS: [emailAddress](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["email"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String email = 'email';
/// The input field expects a person's last/family name.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_PERSON_NAME_FAMILY](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_PERSON_NAME_FAMILY).
/// * iOS: [familyName](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["family-name"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String familyName = 'familyName';
/// The input field expects a street address that fully identifies a location.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_POSTAL_ADDRESS_STREET_ADDRESS](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_POSTAL_ADDRESS_STREET_ADDRESS).
/// * iOS: [fullStreetAddress](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["street-address"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String fullStreetAddress = 'fullStreetAddress';
/// The input field expects a gender.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_GENDER](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_GENDER).
/// * web: ["sex"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String gender = 'gender';
/// The input field expects a person's first/given name.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_PERSON_NAME_GIVEN](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_PERSON_NAME_GIVEN).
/// * iOS: [givenName](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["given-name"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String givenName = 'givenName';
/// The input field expects a URL representing an instant messaging protocol
/// endpoint.
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["impp"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String impp = 'impp';
/// The input field expects a job title.
///
/// This hint will be translated to the below values on different platforms:
///
/// * iOS: [jobTitle](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["organization-title"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String jobTitle = 'jobTitle';
/// The input field expects the preferred language of the user.
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["language"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String language = 'language';
/// The input field expects a location, such as a point of interest, an
/// address,or another way to identify a location.
///
/// This hint will be translated to the below values on different platforms:
///
/// * iOS: [location](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * Otherwise, the hint string will be used as-is.
static const String location = 'location';
/// The input field expects a person's middle initial.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_PERSON_NAME_MIDDLE_INITIAL](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_PERSON_NAME_MIDDLE_INITIAL).
/// * Otherwise, the hint string will be used as-is.
static const String middleInitial = 'middleInitial';
/// The input field expects a person's middle name.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_PERSON_NAME_MIDDLE](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_PERSON_NAME_MIDDLE).
/// * iOS: [middleName](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["additional-name"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String middleName = 'middleName';
/// The input field expects a person's full name.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_PERSON_NAME](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_PERSON_NAME).
/// * iOS: [name](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["name"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String name = 'name';
/// The input field expects a person's name prefix or title, such as "Dr.".
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_PERSON_NAME_PREFIX](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_PERSON_NAME_PREFIX).
/// * iOS: [namePrefix](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["honorific-prefix"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String namePrefix = 'namePrefix';
/// The input field expects a person's name suffix, such as "Jr.".
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_PERSON_NAME_SUFFIX](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_PERSON_NAME_SUFFIX).
/// * iOS: [nameSuffix](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["honorific-suffix"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String nameSuffix = 'nameSuffix';
/// The input field expects a newly created password for save/update.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_NEW_PASSWORD](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_NEW_PASSWORD).
/// * iOS: [newPassword](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["new-password"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String newPassword = 'newPassword';
/// The input field expects a newly created username for save/update.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_NEW_USERNAME](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_NEW_USERNAME).
/// * Otherwise, the hint string will be used as-is.
static const String newUsername = 'newUsername';
/// The input field expects a nickname.
///
/// This hint will be translated to the below values on different platforms:
///
/// * iOS: [nickname](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["nickname"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String nickname = 'nickname';
/// The input field expects a SMS one-time code.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_SMS_OTP](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_SMS_OTP).
/// * iOS: [oneTimeCode](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["one-time-code"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String oneTimeCode = 'oneTimeCode';
/// The input field expects an organization name corresponding to the person,
/// address, or contact information in the other fields associated with this
/// field.
///
/// This hint will be translated to the below values on different platforms:
///
/// * iOS: [organizationName](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["organization"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String organizationName = 'organizationName';
/// The input field expects a password.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_PASSWORD](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_PASSWORD).
/// * iOS: [password](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["current-password"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String password = 'password';
/// The input field expects a photograph, icon, or other image corresponding
/// to the company, person, address, or contact information in the other
/// fields associated with this field.
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["photo"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String photo = 'photo';
/// The input field expects a postal address.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_POSTAL_ADDRESS](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_POSTAL_ADDRESS).
/// * Otherwise, the hint string will be used as-is.
static const String postalAddress = 'postalAddress';
/// The input field expects an auxiliary address details.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_POSTAL_ADDRESS_EXTENDED_ADDRESS](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_POSTAL_ADDRESS_EXTENDED_ADDRESS).
/// * Otherwise, the hint string will be used as-is.
static const String postalAddressExtended = 'postalAddressExtended';
/// The input field expects an extended ZIP/POSTAL code.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_POSTAL_ADDRESS_EXTENDED_POSTAL_CODE](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_POSTAL_ADDRESS_EXTENDED_POSTAL_CODE).
/// * Otherwise, the hint string will be used as-is.
static const String postalAddressExtendedPostalCode = 'postalAddressExtendedPostalCode';
/// The input field expects a postal code.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_POSTAL_CODE](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_POSTAL_CODE).
/// * iOS: [postalCode](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["postal-code"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String postalCode = 'postalCode';
/// The first administrative level in the address. This is typically the
/// province in which the address is located. In the United States, this would
/// be the state. In Switzerland, the canton. In the United Kingdom, the post
/// town.
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["address-level1"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String streetAddressLevel1 = 'streetAddressLevel1';
/// The second administrative level, in addresses with at least two of them.
/// In countries with two administrative levels, this would typically be the
/// city, town, village, or other locality in which the address is located.
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["address-level2"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String streetAddressLevel2 = 'streetAddressLevel2';
/// The third administrative level, in addresses with at least three
/// administrative levels.
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["address-level3"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String streetAddressLevel3 = 'streetAddressLevel3';
/// The finest-grained administrative level, in addresses which have four
/// levels.
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["address-level4"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String streetAddressLevel4 = 'streetAddressLevel4';
/// The input field expects the first line of a street address.
///
/// This hint will be translated to the below values on different platforms:
///
/// * iOS: [streetAddressLine1](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["address-line1"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String streetAddressLine1 = 'streetAddressLine1';
/// The input field expects the second line of a street address.
///
/// This hint will be translated to the below values on different platforms:
///
/// * iOS: [streetAddressLine2](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// As of iOS 14.2 this hint does not trigger autofill.
/// * web: ["address-line2"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String streetAddressLine2 = 'streetAddressLine2';
/// The input field expects the third line of a street address.
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["address-line3"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String streetAddressLine3 = 'streetAddressLine3';
/// The input field expects a sublocality.
///
/// This hint will be translated to the below values on different platforms:
///
/// * iOS: [sublocality](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * Otherwise, the hint string will be used as-is.
static const String sublocality = 'sublocality';
/// The input field expects a telephone number.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_PHONE_NUMBER](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_PHONE_NUMBER).
/// * iOS: [telephoneNumber](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["tel"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String telephoneNumber = 'telephoneNumber';
/// The input field expects a phone number's area code, with a country
/// -internal prefix applied if applicable.
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["tel-area-code"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String telephoneNumberAreaCode = 'telephoneNumberAreaCode';
/// The input field expects a phone number's country code.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_PHONE_COUNTRY_CODE](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_PHONE_COUNTRY_CODE).
/// * web: ["tel-country-code"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String telephoneNumberCountryCode = 'telephoneNumberCountryCode';
/// The input field expects the current device's phone number, usually for
/// Sign Up / OTP flows.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_PHONE_NUMBER_DEVICE](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_PHONE_NUMBER_DEVICE).
/// * Otherwise, the hint string will be used as-is.
static const String telephoneNumberDevice = 'telephoneNumberDevice';
/// The input field expects a phone number's internal extension code.
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["tel-extension"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String telephoneNumberExtension = 'telephoneNumberExtension';
/// The input field expects a phone number without the country code and area
/// code components.
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["tel-local"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String telephoneNumberLocal = 'telephoneNumberLocal';
/// The input field expects the first part of the component of the telephone
/// number that follows the area code, when that component is split into two
/// components.
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["tel-local-prefix"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String telephoneNumberLocalPrefix = 'telephoneNumberLocalPrefix';
/// The input field expects the second part of the component of the telephone
/// number that follows the area code, when that component is split into two
/// components.
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["tel-local-suffix"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String telephoneNumberLocalSuffix = 'telephoneNumberLocalSuffix';
/// The input field expects a phone number without country code.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_PHONE_NATIONAL](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_PHONE_NATIONAL).
/// * web: ["tel-national"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String telephoneNumberNational = 'telephoneNumberNational';
/// The amount that the user would like for the transaction (e.g. when
/// entering a bid or sale price).
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["transaction-amount"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String transactionAmount = 'transactionAmount';
/// The currency that the user would prefer the transaction to use, in [ISO
/// 4217 currency code](https://www.iso.org/iso-4217-currency-codes.html).
///
/// This hint will be translated to the below values on different platforms:
///
/// * web: ["transaction-currency"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String transactionCurrency = 'transactionCurrency';
/// The input field expects a URL.
///
/// This hint will be translated to the below values on different platforms:
///
/// * iOS: [URL](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["url"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String url = 'url';
/// The input field expects a username or an account name.
///
/// This hint will be translated to the below values on different platforms:
///
/// * Android: [AUTOFILL_HINT_USERNAME](https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_USERNAME).
/// * iOS: [username](https://developer.apple.com/documentation/uikit/uitextcontenttype).
/// * web: ["username"](https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#autofilling-form-controls:-the-autocomplete-attribute).
/// * Otherwise, the hint string will be used as-is.
static const String username = 'username';
}
/// A collection of autofill related information that represents an [AutofillClient].
///
/// Typically used in [TextInputConfiguration.autofillConfiguration].
@immutable
class AutofillConfiguration {
/// Creates autofill related configuration information that can be sent to the
/// platform.
const AutofillConfiguration({
required String uniqueIdentifier,
required List<String> autofillHints,
required TextEditingValue currentEditingValue,
String? hintText,
}) : this._(
enabled: true,
uniqueIdentifier: uniqueIdentifier,
autofillHints: autofillHints,
currentEditingValue: currentEditingValue,
hintText: hintText,
);
const AutofillConfiguration._({
required this.enabled,
required this.uniqueIdentifier,
this.autofillHints = const <String>[],
this.hintText,
required this.currentEditingValue,
});
/// An [AutofillConfiguration] that indicates the [AutofillClient] does not
/// wish to be autofilled.
static const AutofillConfiguration disabled = AutofillConfiguration._(
enabled: false,
uniqueIdentifier: '',
currentEditingValue: TextEditingValue.empty,
);
/// Whether autofill should be enabled for the [AutofillClient].
///
/// To retrieve a disabled [AutofillConfiguration], use [disabled].
final bool enabled;
/// A string that uniquely identifies the current [AutofillClient].
///
/// The identifier needs to be unique within the [AutofillScope] for the
/// [AutofillClient] to receive the correct autofill value.
final String uniqueIdentifier;
/// A list of strings that helps the autofill service identify the type of the
/// [AutofillClient].
///
/// {@template flutter.services.AutofillConfiguration.autofillHints}
/// For the best results, hint strings need to be understood by the platform's
/// autofill service. The common values of hint strings can be found in
/// [AutofillHints], as well as their availability on different platforms.
///
/// If an autofillable input field needs to use a custom hint that translates to
/// different strings on different platforms, the easiest way to achieve that
/// is to return different hint strings based on the value of
/// [defaultTargetPlatform].
///
/// Each hint in the list, if not ignored, will be translated to the platform's
/// autofill hint type understood by its autofill services:
///
/// * On iOS, only the first hint in the list is accounted for. The hint will
/// be translated to a
/// [UITextContentType](https://developer.apple.com/documentation/uikit/uitextcontenttype).
///
/// * On Android, all hints in the list are translated to Android hint strings.
///
/// * On web, only the first hint is accounted for and will be translated to
/// an "autocomplete" string.
///
/// Providing an autofill hint that is predefined on the platform does not
/// automatically grant the input field eligibility for autofill. Ultimately,
/// it comes down to the autofill service currently in charge to determine
/// whether an input field is suitable for autofill and what the autofill
/// candidates are.
///
/// See also:
///
/// * [AutofillHints], a list of autofill hint strings that is predefined on at
/// least one platform.
///
/// * [UITextContentType](https://developer.apple.com/documentation/uikit/uitextcontenttype),
/// the iOS equivalent.
///
/// * Android [autofillHints](https://developer.android.com/reference/android/view/View#setAutofillHints(java.lang.String...)),
/// the Android equivalent.
///
/// * The [autocomplete](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/autocomplete) attribute,
/// the web equivalent.
/// {@endtemplate}
final List<String> autofillHints;
/// The current [TextEditingValue] of the [AutofillClient].
final TextEditingValue currentEditingValue;
/// The optional hint text placed on the view that typically suggests what
/// sort of input the field accepts, for example "enter your password here".
///
/// If the developer does not specify any [autofillHints], the [hintText] can
/// be a useful indication to the platform autofill service.
final String? hintText;
/// Returns a representation of this object as a JSON object.
Map<String, dynamic>? toJson() {
return enabled
? <String, dynamic>{
'uniqueIdentifier': uniqueIdentifier,
'hints': autofillHints,
'editingValue': currentEditingValue.toJSON(),
if (hintText != null) 'hintText': hintText,
}
: null;
}
}
/// An object that represents an autofillable input field in the autofill workflow.
///
/// An [AutofillClient] provides autofill-related information of the input field
/// it represents to the platform, and consumes autofill inputs from the platform.
abstract class AutofillClient {
/// The unique identifier of this [AutofillClient].
///
/// The identifier must not be changed.
String get autofillId;
/// The [TextInputConfiguration] that describes this [AutofillClient].
///
/// In order to participate in autofill, its
/// [TextInputConfiguration.autofillConfiguration] must not be null.
TextInputConfiguration get textInputConfiguration;
/// Requests this [AutofillClient] update its [TextEditingValue] to the given
/// value.
void autofill(TextEditingValue newEditingValue);
}
/// An ordered group within which [AutofillClient]s are logically connected.
///
/// {@template flutter.services.AutofillScope}
/// [AutofillClient]s within the same [AutofillScope] are isolated from other
/// input fields during autofill. That is, when an autofillable [TextInputClient]
/// gains focus, only the [AutofillClient]s within the same [AutofillScope] will
/// be visible to the autofill service, in the same order as they appear in
/// [AutofillScope.autofillClients].
///
/// [AutofillScope] also allows [TextInput] to redirect autofill values from the
/// platform to the [AutofillClient] with the given identifier, by calling
/// [AutofillScope.getAutofillClient].
///
/// An [AutofillClient] that's not tied to any [AutofillScope] will only
/// participate in autofill if the autofill is directly triggered by its own
/// [TextInputClient].
/// {@endtemplate}
abstract class AutofillScope {
/// Gets the [AutofillScope] associated with the given [autofillId], in
/// this [AutofillScope].
///
/// Returns null if there's no matching [AutofillClient].
AutofillClient? getAutofillClient(String autofillId);
/// The collection of [AutofillClient]s currently tied to this [AutofillScope].
///
/// Every [AutofillClient] in this list must have autofill enabled (i.e. its
/// [AutofillClient.textInputConfiguration] must have a non-null
/// [AutofillConfiguration].)
Iterable<AutofillClient> get autofillClients;
/// Allows a [TextInputClient] to attach to this scope. This method should be
/// called in lieu of [TextInput.attach], when the [TextInputClient] wishes to
/// participate in autofill.
TextInputConnection attach(TextInputClient trigger, TextInputConfiguration configuration);
}
@immutable
class _AutofillScopeTextInputConfiguration extends TextInputConfiguration {
_AutofillScopeTextInputConfiguration({
required this.allConfigurations,
required TextInputConfiguration currentClientConfiguration,
}) : super(inputType: currentClientConfiguration.inputType,
obscureText: currentClientConfiguration.obscureText,
autocorrect: currentClientConfiguration.autocorrect,
smartDashesType: currentClientConfiguration.smartDashesType,
smartQuotesType: currentClientConfiguration.smartQuotesType,
enableSuggestions: currentClientConfiguration.enableSuggestions,
inputAction: currentClientConfiguration.inputAction,
textCapitalization: currentClientConfiguration.textCapitalization,
keyboardAppearance: currentClientConfiguration.keyboardAppearance,
actionLabel: currentClientConfiguration.actionLabel,
autofillConfiguration: currentClientConfiguration.autofillConfiguration,
);
final Iterable<TextInputConfiguration> allConfigurations;
@override
Map<String, dynamic> toJson() {
final Map<String, dynamic> result = super.toJson();
result['fields'] = allConfigurations
.map((TextInputConfiguration configuration) => configuration.toJson())
.toList(growable: false);
return result;
}
}
/// A partial implementation of [AutofillScope].
///
/// The mixin provides a default implementation for [AutofillScope.attach].
mixin AutofillScopeMixin implements AutofillScope {
@override
TextInputConnection attach(TextInputClient trigger, TextInputConfiguration configuration) {
assert(
!autofillClients.any((AutofillClient client) => !client.textInputConfiguration.autofillConfiguration.enabled),
'Every client in AutofillScope.autofillClients must enable autofill',
);
final TextInputConfiguration inputConfiguration = _AutofillScopeTextInputConfiguration(
allConfigurations: autofillClients.map((AutofillClient client) => client.textInputConfiguration),
currentClientConfiguration: configuration,
);
return TextInput.attach(trigger, inputConfiguration);
}
}
| flutter/packages/flutter/lib/src/services/autofill.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/services/autofill.dart",
"repo_id": "flutter",
"token_count": 13643
} | 638 |
// 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:convert';
import 'dart:typed_data';
import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer;
import 'message_codec.dart';
export 'dart:typed_data' show ByteData;
export 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer;
export 'message_codec.dart' show MethodCall;
const int _writeBufferStartCapacity = 64;
/// [MessageCodec] with unencoded binary messages represented using [ByteData].
///
/// On Android, messages will be represented using `java.nio.ByteBuffer`.
/// On iOS, messages will be represented using `NSData`.
///
/// When sending outgoing messages from Android, be sure to use direct `ByteBuffer`
/// as opposed to indirect. The `wrap()` API provides indirect buffers by default
/// and you will get empty `ByteData` objects in Dart.
class BinaryCodec implements MessageCodec<ByteData> {
/// Creates a [MessageCodec] with unencoded binary messages represented using
/// [ByteData].
const BinaryCodec();
@override
ByteData? decodeMessage(ByteData? message) => message;
@override
ByteData? encodeMessage(ByteData? message) => message;
}
/// [MessageCodec] with UTF-8 encoded String messages.
///
/// On Android, messages will be represented using `java.util.String`.
/// On iOS, messages will be represented using `NSString`.
class StringCodec implements MessageCodec<String> {
/// Creates a [MessageCodec] with UTF-8 encoded String messages.
const StringCodec();
@override
String? decodeMessage(ByteData? message) {
if (message == null) {
return null;
}
return utf8.decode(Uint8List.sublistView(message));
}
@override
ByteData? encodeMessage(String? message) {
if (message == null) {
return null;
}
return ByteData.sublistView(utf8.encode(message));
}
}
/// [MessageCodec] with UTF-8 encoded JSON messages.
///
/// Supported messages are acyclic values of these forms:
///
/// * null
/// * [bool]s
/// * [num]s
/// * [String]s
/// * [List]s of supported values
/// * [Map]s from strings to supported values
///
/// On Android, messages are decoded using the `org.json` library.
/// On iOS, messages are decoded using the `NSJSONSerialization` library.
/// In both cases, the use of top-level simple messages (null, [bool], [num],
/// and [String]) is supported (by the Flutter SDK). The decoded value will be
/// null/nil for null, and identical to what would result from decoding a
/// singleton JSON array with a Boolean, number, or string value, and then
/// extracting its single element.
///
/// The type returned from [decodeMessage] is `dynamic` (not `Object?`), which
/// means *no type checking is performed on its return value*. It is strongly
/// recommended that the return value be immediately cast to a known type to
/// prevent runtime errors due to typos that the type checker could otherwise
/// catch.
class JSONMessageCodec implements MessageCodec<Object?> {
// The codec serializes messages as defined by the JSON codec of the
// dart:convert package. The format used must match the Android and
// iOS counterparts.
/// Creates a [MessageCodec] with UTF-8 encoded JSON messages.
const JSONMessageCodec();
@override
ByteData? encodeMessage(Object? message) {
if (message == null) {
return null;
}
return const StringCodec().encodeMessage(json.encode(message));
}
@override
dynamic decodeMessage(ByteData? message) {
if (message == null) {
return message;
}
return json.decode(const StringCodec().decodeMessage(message)!);
}
}
/// [MethodCodec] with UTF-8 encoded JSON method calls and result envelopes.
///
/// Values supported as method arguments and result payloads are those supported
/// by [JSONMessageCodec].
class JSONMethodCodec implements MethodCodec {
// The codec serializes method calls, and result envelopes as outlined below.
// This format must match the Android and iOS counterparts.
//
// * Individual values are serialized as defined by the JSON codec of the
// dart:convert package.
// * Method calls are serialized as two-element maps, with the method name
// keyed by 'method' and the arguments keyed by 'args'.
// * Reply envelopes are serialized as either:
// * one-element lists containing the successful result as its single
// element, or
// * three-element lists containing, in order, an error code String, an
// error message String, and an error details value.
/// Creates a [MethodCodec] with UTF-8 encoded JSON method calls and result
/// envelopes.
const JSONMethodCodec();
@override
ByteData encodeMethodCall(MethodCall methodCall) {
return const JSONMessageCodec().encodeMessage(<String, Object?>{
'method': methodCall.method,
'args': methodCall.arguments,
})!;
}
@override
MethodCall decodeMethodCall(ByteData? methodCall) {
final Object? decoded = const JSONMessageCodec().decodeMessage(methodCall);
if (decoded is! Map) {
throw FormatException('Expected method call Map, got $decoded');
}
final Object? method = decoded['method'];
final Object? arguments = decoded['args'];
if (method is String) {
return MethodCall(method, arguments);
}
throw FormatException('Invalid method call: $decoded');
}
@override
dynamic decodeEnvelope(ByteData envelope) {
final Object? decoded = const JSONMessageCodec().decodeMessage(envelope);
if (decoded is! List) {
throw FormatException('Expected envelope List, got $decoded');
}
if (decoded.length == 1) {
return decoded[0];
}
if (decoded.length == 3
&& decoded[0] is String
&& (decoded[1] == null || decoded[1] is String)) {
throw PlatformException(
code: decoded[0] as String,
message: decoded[1] as String?,
details: decoded[2],
);
}
if (decoded.length == 4
&& decoded[0] is String
&& (decoded[1] == null || decoded[1] is String)
&& (decoded[3] == null || decoded[3] is String)) {
throw PlatformException(
code: decoded[0] as String,
message: decoded[1] as String?,
details: decoded[2],
stacktrace: decoded[3] as String?,
);
}
throw FormatException('Invalid envelope: $decoded');
}
@override
ByteData encodeSuccessEnvelope(Object? result) {
return const JSONMessageCodec().encodeMessage(<Object?>[result])!;
}
@override
ByteData encodeErrorEnvelope({ required String code, String? message, Object? details}) {
return const JSONMessageCodec().encodeMessage(<Object?>[code, message, details])!;
}
}
/// [MessageCodec] using the Flutter standard binary encoding.
///
/// Supported messages are acyclic values of these forms:
///
/// * null
/// * [bool]s
/// * [num]s
/// * [String]s
/// * [Uint8List]s, [Int32List]s, [Int64List]s, [Float64List]s
/// * [List]s of supported values
/// * [Map]s from supported values to supported values
///
/// Decoded values will use `List<Object?>` and `Map<Object?, Object?>`
/// irrespective of content.
///
/// The type returned from [decodeMessage] is `dynamic` (not `Object?`), which
/// means *no type checking is performed on its return value*. It is strongly
/// recommended that the return value be immediately cast to a known type to
/// prevent runtime errors due to typos that the type checker could otherwise
/// catch.
///
/// The codec is extensible by subclasses overriding [writeValue] and
/// [readValueOfType].
///
/// ## Android specifics
///
/// On Android, messages are represented as follows:
///
/// * null: null
/// * [bool]\: `java.lang.Boolean`
/// * [int]\: `java.lang.Integer` for values that are representable using 32-bit
/// two's complement; `java.lang.Long` otherwise
/// * [double]\: `java.lang.Double`
/// * [String]\: `java.lang.String`
/// * [Uint8List]\: `byte[]`
/// * [Int32List]\: `int[]`
/// * [Int64List]\: `long[]`
/// * [Float64List]\: `double[]`
/// * [List]\: `java.util.ArrayList`
/// * [Map]\: `java.util.HashMap`
///
/// When sending a `java.math.BigInteger` from Java, it is converted into a
/// [String] with the hexadecimal representation of the integer. (The value is
/// tagged as being a big integer; subclasses of this class could be made to
/// support it natively; see the discussion at [writeValue].) This codec does
/// not support sending big integers from Dart.
///
/// ## iOS specifics
///
/// On iOS, messages are represented as follows:
///
/// * null: nil
/// * [bool]\: `NSNumber numberWithBool:`
/// * [int]\: `NSNumber numberWithInt:` for values that are representable using
/// 32-bit two's complement; `NSNumber numberWithLong:` otherwise
/// * [double]\: `NSNumber numberWithDouble:`
/// * [String]\: `NSString`
/// * [Uint8List], [Int32List], [Int64List], [Float64List]\:
/// `FlutterStandardTypedData`
/// * [List]\: `NSArray`
/// * [Map]\: `NSDictionary`
class StandardMessageCodec implements MessageCodec<Object?> {
/// Creates a [MessageCodec] using the Flutter standard binary encoding.
const StandardMessageCodec();
// The codec serializes messages as outlined below. This format must match the
// Android and iOS counterparts and cannot change (as it's possible for
// someone to end up using this for persistent storage).
//
// * A single byte with one of the constant values below determines the
// type of the value.
// * The serialization of the value itself follows the type byte.
// * Numbers are represented using the host endianness throughout.
// * Lengths and sizes of serialized parts are encoded using an expanding
// format optimized for the common case of small non-negative integers:
// * values 0..253 inclusive using one byte with that value;
// * values 254..2^16 inclusive using three bytes, the first of which is
// 254, the next two the usual unsigned representation of the value;
// * values 2^16+1..2^32 inclusive using five bytes, the first of which is
// 255, the next four the usual unsigned representation of the value.
// * null, true, and false have empty serialization; they are encoded directly
// in the type byte (using _valueNull, _valueTrue, _valueFalse)
// * Integers representable in 32 bits are encoded using 4 bytes two's
// complement representation.
// * Larger integers are encoded using 8 bytes two's complement
// representation.
// * doubles are encoded using the IEEE 754 64-bit double-precision binary
// format. Zero bytes are added before the encoded double value to align it
// to a 64 bit boundary in the full message.
// * Strings are encoded using their UTF-8 representation. First the length
// of that in bytes is encoded using the expanding format, then follows the
// UTF-8 encoding itself.
// * Uint8Lists, Int32Lists, Int64Lists, Float32Lists, and Float64Lists are
// encoded by first encoding the list's element count in the expanding
// format, then the smallest number of zero bytes needed to align the
// position in the full message with a multiple of the number of bytes per
// element, then the encoding of the list elements themselves, end-to-end
// with no additional type information, using two's complement or IEEE 754
// as applicable.
// * Lists are encoded by first encoding their length in the expanding format,
// then follows the recursive encoding of each element value, including the
// type byte (Lists are assumed to be heterogeneous).
// * Maps are encoded by first encoding their length in the expanding format,
// then follows the recursive encoding of each key/value pair, including the
// type byte for both (Maps are assumed to be heterogeneous).
//
// The type labels below must not change, since it's possible for this interface
// to be used for persistent storage.
static const int _valueNull = 0;
static const int _valueTrue = 1;
static const int _valueFalse = 2;
static const int _valueInt32 = 3;
static const int _valueInt64 = 4;
static const int _valueLargeInt = 5;
static const int _valueFloat64 = 6;
static const int _valueString = 7;
static const int _valueUint8List = 8;
static const int _valueInt32List = 9;
static const int _valueInt64List = 10;
static const int _valueFloat64List = 11;
static const int _valueList = 12;
static const int _valueMap = 13;
static const int _valueFloat32List = 14;
@override
ByteData? encodeMessage(Object? message) {
if (message == null) {
return null;
}
final WriteBuffer buffer = WriteBuffer(startCapacity: _writeBufferStartCapacity);
writeValue(buffer, message);
return buffer.done();
}
@override
dynamic decodeMessage(ByteData? message) {
if (message == null) {
return null;
}
final ReadBuffer buffer = ReadBuffer(message);
final Object? result = readValue(buffer);
if (buffer.hasRemaining) {
throw const FormatException('Message corrupted');
}
return result;
}
/// Writes [value] to [buffer] by first writing a type discriminator
/// byte, then the value itself.
///
/// This method may be called recursively to serialize container values.
///
/// Type discriminators 0 through 127 inclusive are reserved for use by the
/// base class, as follows:
///
/// * null = 0
/// * true = 1
/// * false = 2
/// * 32 bit integer = 3
/// * 64 bit integer = 4
/// * larger integers = 5 (see below)
/// * 64 bit floating-point number = 6
/// * String = 7
/// * Uint8List = 8
/// * Int32List = 9
/// * Int64List = 10
/// * Float64List = 11
/// * List = 12
/// * Map = 13
/// * Float32List = 14
/// * Reserved for future expansion: 15..127
///
/// The codec can be extended by overriding this method, calling super
/// for values that the extension does not handle. Type discriminators
/// used by extensions must be greater than or equal to 128 in order to avoid
/// clashes with any later extensions to the base class.
///
/// The "larger integers" type, 5, is never used by [writeValue]. A subclass
/// could represent big integers from another package using that type. The
/// format is first the type byte (0x05), then the actual number as an ASCII
/// string giving the hexadecimal representation of the integer, with the
/// string's length as encoded by [writeSize] followed by the string bytes. On
/// Android, that would get converted to a `java.math.BigInteger` object. On
/// iOS, the string representation is returned.
void writeValue(WriteBuffer buffer, Object? value) {
if (value == null) {
buffer.putUint8(_valueNull);
} else if (value is bool) {
buffer.putUint8(value ? _valueTrue : _valueFalse);
} else if (value is double) { // Double precedes int because in JS everything is a double.
// Therefore in JS, both `is int` and `is double` always
// return `true`. If we check int first, we'll end up treating
// all numbers as ints and attempt the int32/int64 conversion,
// which is wrong. This precedence rule is irrelevant when
// decoding because we use tags to detect the type of value.
buffer.putUint8(_valueFloat64);
buffer.putFloat64(value);
} else if (value is int) { // ignore: avoid_double_and_int_checks, JS code always goes through the `double` path above
if (-0x7fffffff - 1 <= value && value <= 0x7fffffff) {
buffer.putUint8(_valueInt32);
buffer.putInt32(value);
} else {
buffer.putUint8(_valueInt64);
buffer.putInt64(value);
}
} else if (value is String) {
buffer.putUint8(_valueString);
final Uint8List asciiBytes = Uint8List(value.length);
Uint8List? utf8Bytes;
int utf8Offset = 0;
// Only do utf8 encoding if we encounter non-ascii characters.
for (int i = 0; i < value.length; i += 1) {
final int char = value.codeUnitAt(i);
if (char <= 0x7f) {
asciiBytes[i] = char;
} else {
utf8Bytes = utf8.encode(value.substring(i));
utf8Offset = i;
break;
}
}
if (utf8Bytes != null) {
writeSize(buffer, utf8Offset + utf8Bytes.length);
buffer.putUint8List(Uint8List.sublistView(asciiBytes, 0, utf8Offset));
buffer.putUint8List(utf8Bytes);
} else {
writeSize(buffer, asciiBytes.length);
buffer.putUint8List(asciiBytes);
}
} else if (value is Uint8List) {
buffer.putUint8(_valueUint8List);
writeSize(buffer, value.length);
buffer.putUint8List(value);
} else if (value is Int32List) {
buffer.putUint8(_valueInt32List);
writeSize(buffer, value.length);
buffer.putInt32List(value);
} else if (value is Int64List) {
buffer.putUint8(_valueInt64List);
writeSize(buffer, value.length);
buffer.putInt64List(value);
} else if (value is Float32List) {
buffer.putUint8(_valueFloat32List);
writeSize(buffer, value.length);
buffer.putFloat32List(value);
} else if (value is Float64List) {
buffer.putUint8(_valueFloat64List);
writeSize(buffer, value.length);
buffer.putFloat64List(value);
} else if (value is List) {
buffer.putUint8(_valueList);
writeSize(buffer, value.length);
for (final Object? item in value) {
writeValue(buffer, item);
}
} else if (value is Map) {
buffer.putUint8(_valueMap);
writeSize(buffer, value.length);
value.forEach((Object? key, Object? value) {
writeValue(buffer, key);
writeValue(buffer, value);
});
} else {
throw ArgumentError.value(value);
}
}
/// Reads a value from [buffer] as written by [writeValue].
///
/// This method is intended for use by subclasses overriding
/// [readValueOfType].
Object? readValue(ReadBuffer buffer) {
if (!buffer.hasRemaining) {
throw const FormatException('Message corrupted');
}
final int type = buffer.getUint8();
return readValueOfType(type, buffer);
}
/// Reads a value of the indicated [type] from [buffer].
///
/// The codec can be extended by overriding this method, calling super for
/// types that the extension does not handle. See the discussion at
/// [writeValue].
Object? readValueOfType(int type, ReadBuffer buffer) {
switch (type) {
case _valueNull:
return null;
case _valueTrue:
return true;
case _valueFalse:
return false;
case _valueInt32:
return buffer.getInt32();
case _valueInt64:
return buffer.getInt64();
case _valueFloat64:
return buffer.getFloat64();
case _valueLargeInt:
case _valueString:
final int length = readSize(buffer);
return utf8.decoder.convert(buffer.getUint8List(length));
case _valueUint8List:
final int length = readSize(buffer);
return buffer.getUint8List(length);
case _valueInt32List:
final int length = readSize(buffer);
return buffer.getInt32List(length);
case _valueInt64List:
final int length = readSize(buffer);
return buffer.getInt64List(length);
case _valueFloat32List:
final int length = readSize(buffer);
return buffer.getFloat32List(length);
case _valueFloat64List:
final int length = readSize(buffer);
return buffer.getFloat64List(length);
case _valueList:
final int length = readSize(buffer);
final List<Object?> result = List<Object?>.filled(length, null);
for (int i = 0; i < length; i++) {
result[i] = readValue(buffer);
}
return result;
case _valueMap:
final int length = readSize(buffer);
final Map<Object?, Object?> result = <Object?, Object?>{};
for (int i = 0; i < length; i++) {
result[readValue(buffer)] = readValue(buffer);
}
return result;
default: throw const FormatException('Message corrupted');
}
}
/// Writes a non-negative 32-bit integer [value] to [buffer]
/// using an expanding 1-5 byte encoding that optimizes for small values.
///
/// This method is intended for use by subclasses overriding
/// [writeValue].
void writeSize(WriteBuffer buffer, int value) {
assert(0 <= value && value <= 0xffffffff);
if (value < 254) {
buffer.putUint8(value);
} else if (value <= 0xffff) {
buffer.putUint8(254);
buffer.putUint16(value);
} else {
buffer.putUint8(255);
buffer.putUint32(value);
}
}
/// Reads a non-negative int from [buffer] as written by [writeSize].
///
/// This method is intended for use by subclasses overriding
/// [readValueOfType].
int readSize(ReadBuffer buffer) {
final int value = buffer.getUint8();
return switch (value) {
254 => buffer.getUint16(),
255 => buffer.getUint32(),
_ => value,
};
}
}
/// [MethodCodec] using the Flutter standard binary encoding.
///
/// The standard codec is guaranteed to be compatible with the corresponding
/// standard codec for FlutterMethodChannels on the host platform. These parts
/// of the Flutter SDK are evolved synchronously.
///
/// Values supported as method arguments and result payloads are those supported
/// by [StandardMessageCodec].
class StandardMethodCodec implements MethodCodec {
// The codec method calls, and result envelopes as outlined below. This format
// must match the Android and iOS counterparts.
//
// * Individual values are encoded using [StandardMessageCodec].
// * Method calls are encoded using the concatenation of the encoding
// of the method name String and the arguments value.
// * Reply envelopes are encoded using first a single byte to distinguish the
// success case (0) from the error case (1). Then follows:
// * In the success case, the encoding of the result value.
// * In the error case, the concatenation of the encoding of the error code
// string, the error message string, and the error details value.
/// Creates a [MethodCodec] using the Flutter standard binary encoding.
const StandardMethodCodec([this.messageCodec = const StandardMessageCodec()]);
/// The message codec that this method codec uses for encoding values.
final StandardMessageCodec messageCodec;
@override
ByteData encodeMethodCall(MethodCall methodCall) {
final WriteBuffer buffer = WriteBuffer(startCapacity: _writeBufferStartCapacity);
messageCodec.writeValue(buffer, methodCall.method);
messageCodec.writeValue(buffer, methodCall.arguments);
return buffer.done();
}
@override
MethodCall decodeMethodCall(ByteData? methodCall) {
final ReadBuffer buffer = ReadBuffer(methodCall!);
final Object? method = messageCodec.readValue(buffer);
final Object? arguments = messageCodec.readValue(buffer);
if (method is String && !buffer.hasRemaining) {
return MethodCall(method, arguments);
} else {
throw const FormatException('Invalid method call');
}
}
@override
ByteData encodeSuccessEnvelope(Object? result) {
final WriteBuffer buffer = WriteBuffer(startCapacity: _writeBufferStartCapacity);
buffer.putUint8(0);
messageCodec.writeValue(buffer, result);
return buffer.done();
}
@override
ByteData encodeErrorEnvelope({ required String code, String? message, Object? details}) {
final WriteBuffer buffer = WriteBuffer(startCapacity: _writeBufferStartCapacity);
buffer.putUint8(1);
messageCodec.writeValue(buffer, code);
messageCodec.writeValue(buffer, message);
messageCodec.writeValue(buffer, details);
return buffer.done();
}
@override
dynamic decodeEnvelope(ByteData envelope) {
// First byte is zero in success case, and non-zero otherwise.
if (envelope.lengthInBytes == 0) {
throw const FormatException('Expected envelope, got nothing');
}
final ReadBuffer buffer = ReadBuffer(envelope);
if (buffer.getUint8() == 0) {
return messageCodec.readValue(buffer);
}
final Object? errorCode = messageCodec.readValue(buffer);
final Object? errorMessage = messageCodec.readValue(buffer);
final Object? errorDetails = messageCodec.readValue(buffer);
final String? errorStacktrace = (buffer.hasRemaining) ? messageCodec.readValue(buffer) as String? : null;
if (errorCode is String && (errorMessage == null || errorMessage is String) && !buffer.hasRemaining) {
throw PlatformException(code: errorCode, message: errorMessage as String?, details: errorDetails, stacktrace: errorStacktrace);
} else {
throw const FormatException('Invalid envelope');
}
}
}
| flutter/packages/flutter/lib/src/services/message_codecs.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/services/message_codecs.dart",
"repo_id": "flutter",
"token_count": 8292
} | 639 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:flutter/foundation.dart';
import 'system_channels.dart';
/// A data structure representing a range of misspelled text and the suggested
/// replacements for this range.
///
/// For example, one [SuggestionSpan] of the
/// [List<SuggestionSpan>] suggestions of the [SpellCheckResults] corresponding
/// to "Hello, wrold!" may be:
/// ```dart
/// SuggestionSpan suggestionSpan =
/// const SuggestionSpan(
/// TextRange(start: 7, end: 12),
/// <String>['word', 'world', 'old'],
/// );
/// ```
@immutable
class SuggestionSpan {
/// Creates a span representing a misspelled range of text and the replacements
/// suggested by a spell checker.
///
/// The [range] and replacement [suggestions] must all not
/// be null.
const SuggestionSpan(this.range, this.suggestions);
/// The misspelled range of text.
final TextRange range;
/// The alternate suggestions for the misspelled range of text.
final List<String> suggestions;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is SuggestionSpan &&
other.range.start == range.start &&
other.range.end == range.end &&
listEquals<String>(other.suggestions, suggestions);
}
@override
int get hashCode => Object.hash(range.start, range.end, Object.hashAll(suggestions));
}
/// A data structure grouping together the [SuggestionSpan]s and related text of
/// results returned by a spell checker.
@immutable
class SpellCheckResults {
/// Creates results based off those received by spell checking some text input.
const SpellCheckResults(this.spellCheckedText, this.suggestionSpans);
/// The text that the [suggestionSpans] correspond to.
final String spellCheckedText;
/// The spell check results of the [spellCheckedText].
///
/// See also:
///
/// * [SuggestionSpan], the ranges of misspelled text and corresponding
/// replacement suggestions.
final List<SuggestionSpan> suggestionSpans;
@override
bool operator ==(Object other) {
if (identical(this, other)) {
return true;
}
return other is SpellCheckResults &&
other.spellCheckedText == spellCheckedText &&
listEquals<SuggestionSpan>(other.suggestionSpans, suggestionSpans);
}
@override
int get hashCode => Object.hash(spellCheckedText, Object.hashAll(suggestionSpans));
}
/// Determines how spell check results are received for text input.
abstract class SpellCheckService {
/// Facilitates a spell check request.
///
/// Returns a [Future] that resolves with a [List] of [SuggestionSpan]s for
/// all misspelled words in the given [String] for the given [Locale].
Future<List<SuggestionSpan>?> fetchSpellCheckSuggestions(
Locale locale, String text
);
}
/// The service used by default to fetch spell check results for text input.
///
/// Any widget may use this service to spell check text by calling
/// `fetchSpellCheckSuggestions(locale, text)` with an instance of this class.
/// This is currently only supported by Android and iOS.
///
/// See also:
///
/// * [SpellCheckService], the service that this implements that may be
/// overridden for use by [EditableText].
/// * [EditableText], which may use this service to fetch results.
class DefaultSpellCheckService implements SpellCheckService {
/// Creates service to spell check text input by default via communication
/// over the spell check [MethodChannel].
DefaultSpellCheckService() {
spellCheckChannel = SystemChannels.spellCheck;
}
/// The last received results from the shell side.
SpellCheckResults? lastSavedResults;
/// The channel used to communicate with the shell side to complete spell
/// check requests.
late MethodChannel spellCheckChannel;
/// Merges two lists of spell check [SuggestionSpan]s.
///
/// Used in cases where the text has not changed, but the spell check results
/// received from the shell side have. This case is caused by IMEs (GBoard,
/// for instance) that ignore the composing region when spell checking text.
///
/// Assumes that the lists provided as parameters are sorted by range start
/// and that both list of [SuggestionSpan]s apply to the same text.
static List<SuggestionSpan> mergeResults(
List<SuggestionSpan> oldResults, List<SuggestionSpan> newResults) {
final List<SuggestionSpan> mergedResults = <SuggestionSpan>[];
SuggestionSpan oldSpan;
SuggestionSpan newSpan;
int oldSpanPointer = 0;
int newSpanPointer = 0;
while (oldSpanPointer < oldResults.length &&
newSpanPointer < newResults.length) {
oldSpan = oldResults[oldSpanPointer];
newSpan = newResults[newSpanPointer];
if (oldSpan.range.start == newSpan.range.start) {
mergedResults.add(oldSpan);
oldSpanPointer++;
newSpanPointer++;
} else {
if (oldSpan.range.start < newSpan.range.start) {
mergedResults.add(oldSpan);
oldSpanPointer++;
} else {
mergedResults.add(newSpan);
newSpanPointer++;
}
}
}
mergedResults.addAll(oldResults.sublist(oldSpanPointer));
mergedResults.addAll(newResults.sublist(newSpanPointer));
return mergedResults;
}
@override
Future<List<SuggestionSpan>?> fetchSpellCheckSuggestions(
Locale locale, String text) async {
final List<dynamic> rawResults;
final String languageTag = locale.toLanguageTag();
try {
rawResults = await spellCheckChannel.invokeMethod(
'SpellCheck.initiateSpellCheck',
<String>[languageTag, text],
) as List<dynamic>;
} catch (e) {
// Spell check request canceled due to pending request.
return null;
}
List<SuggestionSpan> suggestionSpans = <SuggestionSpan>[];
for (final dynamic result in rawResults) {
final Map<String, dynamic> resultMap =
Map<String,dynamic>.from(result as Map<dynamic, dynamic>);
suggestionSpans.add(
SuggestionSpan(
TextRange(
start: resultMap['startIndex'] as int,
end: resultMap['endIndex'] as int),
(resultMap['suggestions'] as List<dynamic>).cast<String>(),
)
);
}
if (lastSavedResults != null) {
// Merge current and previous spell check results if between requests,
// the text has not changed but the spell check results have.
final bool textHasNotChanged = lastSavedResults!.spellCheckedText == text;
final bool spansHaveChanged =
listEquals(lastSavedResults!.suggestionSpans, suggestionSpans);
if (textHasNotChanged && spansHaveChanged) {
suggestionSpans = mergeResults(lastSavedResults!.suggestionSpans, suggestionSpans);
}
}
lastSavedResults = SpellCheckResults(text, suggestionSpans);
return suggestionSpans;
}
}
| flutter/packages/flutter/lib/src/services/spell_check.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/services/spell_check.dart",
"repo_id": "flutter",
"token_count": 2320
} | 640 |
// 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:js_interop';
import 'dart:ui_web' as ui_web;
import 'package:flutter/rendering.dart';
import '../web.dart' as web;
import 'basic.dart';
import 'framework.dart';
import 'platform_view.dart';
import 'selection_container.dart';
const String _viewType = 'Browser__WebContextMenuViewType__';
const String _kClassName = 'web-electable-region-context-menu';
// These css rules hides the dom element with the class name.
const String _kClassSelectionRule = '.$_kClassName::selection { background: transparent; }';
const String _kClassRule = '''
.$_kClassName {
color: transparent;
user-select: text;
-webkit-user-select: text; /* Safari */
-moz-user-select: text; /* Firefox */
-ms-user-select: text; /* IE10+ */
}
''';
const int _kRightClickButton = 2;
typedef _WebSelectionCallBack = void Function(web.HTMLElement, web.MouseEvent);
/// Function signature for `ui_web.platformViewRegistry.registerViewFactory`.
@visibleForTesting
typedef RegisterViewFactory = void Function(String, Object Function(int viewId), {bool isVisible});
/// See `_platform_selectable_region_context_menu_io.dart` for full
/// documentation.
class PlatformSelectableRegionContextMenu extends StatelessWidget {
/// See `_platform_selectable_region_context_menu_io.dart`.
PlatformSelectableRegionContextMenu({
required this.child,
super.key,
}) {
if (_registeredViewType == null) {
_register();
}
}
/// See `_platform_selectable_region_context_menu_io.dart`.
final Widget child;
/// See `_platform_selectable_region_context_menu_io.dart`.
// ignore: use_setters_to_change_properties
static void attach(SelectionContainerDelegate client) {
_activeClient = client;
}
/// See `_platform_selectable_region_context_menu_io.dart`.
static void detach(SelectionContainerDelegate client) {
if (_activeClient != client) {
_activeClient = null;
}
}
static SelectionContainerDelegate? _activeClient;
// Keeps track if this widget has already registered its view factories or not.
static String? _registeredViewType;
static RegisterViewFactory get _registerViewFactory =>
debugOverrideRegisterViewFactory ?? ui_web.platformViewRegistry.registerViewFactory;
/// Override this to provide a custom implementation of [ui_web.platformViewRegistry.registerViewFactory].
///
/// This should only be used for testing.
// See `_platform_selectable_region_context_menu_io.dart`.
@visibleForTesting
static RegisterViewFactory? debugOverrideRegisterViewFactory;
// Registers the view factories for the interceptor widgets.
static void _register() {
assert(_registeredViewType == null);
_registeredViewType = _registerWebSelectionCallback((web.HTMLElement element, web.MouseEvent event) {
final SelectionContainerDelegate? client = _activeClient;
if (client != null) {
// Converts the html right click event to flutter coordinate.
final Offset localOffset = Offset(event.offsetX.toDouble(), event.offsetY.toDouble());
final Matrix4 transform = client.getTransformTo(null);
final Offset globalOffset = MatrixUtils.transformPoint(transform, localOffset);
client.dispatchSelectionEvent(SelectWordSelectionEvent(globalPosition: globalOffset));
// The innerText must contain the text in order to be selected by
// the browser.
element.innerText = client.getSelectedContent()?.plainText ?? '';
// Programmatically select the dom element in browser.
final web.Range range = web.document.createRange();
range.selectNode(element);
final web.Selection? selection = web.window.getSelection();
if (selection != null) {
selection.removeAllRanges();
selection.addRange(range);
}
}
});
}
static String _registerWebSelectionCallback(_WebSelectionCallBack callback) {
_registerViewFactory(_viewType, (int viewId) {
final web.HTMLElement htmlElement = web.document.createElement('div') as web.HTMLElement;
htmlElement
..style.width = '100%'
..style.height = '100%'
..classList.add(_kClassName);
// Create css style for _kClassName.
final web.HTMLStyleElement styleElement = web.document.createElement('style') as web.HTMLStyleElement;
web.document.head!.append(styleElement as JSAny);
final web.CSSStyleSheet sheet = styleElement.sheet!;
sheet.insertRule(_kClassRule, 0);
sheet.insertRule(_kClassSelectionRule, 1);
htmlElement.addEventListener('mousedown', (web.Event event) {
final web.MouseEvent mouseEvent = event as web.MouseEvent;
if (mouseEvent.button != _kRightClickButton) {
return;
}
callback(htmlElement, mouseEvent);
}.toJS);
return htmlElement;
}, isVisible: false);
return _viewType;
}
@override
Widget build(BuildContext context) {
return Stack(
alignment: Alignment.center,
children: <Widget>[
const Positioned.fill(
child: HtmlElementView(
viewType: _viewType,
),
),
child,
],
);
}
}
| flutter/packages/flutter/lib/src/widgets/_platform_selectable_region_context_menu_web.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/_platform_selectable_region_context_menu_web.dart",
"repo_id": "flutter",
"token_count": 1810
} | 641 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:developer' as developer;
import 'dart:ui' show AccessibilityFeatures, AppExitResponse, AppLifecycleState, FrameTiming, Locale, PlatformDispatcher, TimingsCallback;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'app.dart';
import 'debug.dart';
import 'focus_manager.dart';
import 'framework.dart';
import 'platform_menu_bar.dart';
import 'router.dart';
import 'service_extensions.dart';
import 'view.dart';
import 'widget_inspector.dart';
export 'dart:ui' show AppLifecycleState, Locale;
// Examples can assume:
// late FlutterView myFlutterView;
// class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) => const Placeholder(); }
/// Interface for classes that register with the Widgets layer binding.
///
/// This can be used by any class, not just widgets. It provides an interface
/// which is used by [WidgetsBinding.addObserver] and
/// [WidgetsBinding.removeObserver] to notify objects of changes in the
/// environment, such as changes to the device metrics or accessibility
/// settings. It is used to implement features such as [MediaQuery].
///
/// This class can be extended directly, or mixed in, to get default behaviors
/// for all of the handlers. Alternatively it can be used with the
/// `implements` keyword, in which case all the handlers must be implemented
/// (and the analyzer will list those that have been omitted).
///
/// To start receiving notifications, call `WidgetsBinding.instance.addObserver`
/// with a reference to the object implementing the [WidgetsBindingObserver]
/// interface. To avoid memory leaks, call
/// `WidgetsBinding.instance.removeObserver` to unregister the object when it
/// reaches the end of its lifecycle.
///
/// {@tool dartpad}
/// This sample shows how to implement parts of the [State] and
/// [WidgetsBindingObserver] protocols necessary to react to application
/// lifecycle messages. See [didChangeAppLifecycleState].
///
/// To respond to other notifications, replace the [didChangeAppLifecycleState]
/// method in this example with other methods from this class.
///
/// ** See code in examples/api/lib/widgets/binding/widget_binding_observer.0.dart **
/// {@end-tool}
abstract mixin class WidgetsBindingObserver {
/// Called when the system tells the app to pop the current route, such as
/// after a system back button press or back gesture.
///
/// Observers are notified in registration order until one returns
/// true. If none return true, the application quits.
///
/// Observers are expected to return true if they were able to
/// handle the notification, for example by closing an active dialog
/// box, and false otherwise. The [WidgetsApp] widget uses this
/// mechanism to notify the [Navigator] widget that it should pop
/// its current route if possible.
///
/// This method exposes the `popRoute` notification from
/// [SystemChannels.navigation].
///
/// {@macro flutter.widgets.AndroidPredictiveBack}
Future<bool> didPopRoute() => Future<bool>.value(false);
/// Called when the host tells the application to push a new route onto the
/// navigator.
///
/// Observers are expected to return true if they were able to
/// handle the notification. Observers are notified in registration
/// order until one returns true.
///
/// This method exposes the `pushRoute` notification from
/// [SystemChannels.navigation].
@Deprecated(
'Use didPushRouteInformation instead. '
'This feature was deprecated after v3.8.0-14.0.pre.'
)
Future<bool> didPushRoute(String route) => Future<bool>.value(false);
/// Called when the host tells the application to push a new
/// [RouteInformation] and a restoration state onto the router.
///
/// Observers are expected to return true if they were able to
/// handle the notification. Observers are notified in registration
/// order until one returns true.
///
/// This method exposes the `pushRouteInformation` notification from
/// [SystemChannels.navigation].
///
/// The default implementation is to call the [didPushRoute] directly with the
/// string constructed from [RouteInformation.uri]'s path and query parameters.
// TODO(chunhtai): remove the default implementation once `didPushRoute` is
// removed.
Future<bool> didPushRouteInformation(RouteInformation routeInformation) {
final Uri uri = routeInformation.uri;
return didPushRoute(
Uri.decodeComponent(
Uri(
path: uri.path.isEmpty ? '/' : uri.path,
queryParameters: uri.queryParametersAll.isEmpty ? null : uri.queryParametersAll,
fragment: uri.fragment.isEmpty ? null : uri.fragment,
).toString(),
),
);
}
/// Called when the application's dimensions change. For example,
/// when a phone is rotated.
///
/// This method exposes notifications from
/// [dart:ui.PlatformDispatcher.onMetricsChanged].
///
/// {@tool snippet}
///
/// This [StatefulWidget] implements the parts of the [State] and
/// [WidgetsBindingObserver] protocols necessary to react when the device is
/// rotated (or otherwise changes dimensions).
///
/// ```dart
/// class MetricsReactor extends StatefulWidget {
/// const MetricsReactor({ super.key });
///
/// @override
/// State<MetricsReactor> createState() => _MetricsReactorState();
/// }
///
/// class _MetricsReactorState extends State<MetricsReactor> with WidgetsBindingObserver {
/// late Size _lastSize;
///
/// @override
/// void initState() {
/// super.initState();
/// WidgetsBinding.instance.addObserver(this);
/// }
///
/// @override
/// void didChangeDependencies() {
/// super.didChangeDependencies();
/// // [View.of] exposes the view from `WidgetsBinding.instance.platformDispatcher.views`
/// // into which this widget is drawn.
/// _lastSize = View.of(context).physicalSize;
/// }
///
/// @override
/// void dispose() {
/// WidgetsBinding.instance.removeObserver(this);
/// super.dispose();
/// }
///
/// @override
/// void didChangeMetrics() {
/// setState(() { _lastSize = View.of(context).physicalSize; });
/// }
///
/// @override
/// Widget build(BuildContext context) {
/// return Text('Current size: $_lastSize');
/// }
/// }
/// ```
/// {@end-tool}
///
/// In general, this is unnecessary as the layout system takes care of
/// automatically recomputing the application geometry when the application
/// size changes.
///
/// See also:
///
/// * [MediaQuery.sizeOf], which provides a similar service with less
/// boilerplate.
void didChangeMetrics() { }
/// Called when the platform's text scale factor changes.
///
/// This typically happens as the result of the user changing system
/// preferences, and it should affect all of the text sizes in the
/// application.
///
/// This method exposes notifications from
/// [dart:ui.PlatformDispatcher.onTextScaleFactorChanged].
///
/// {@tool snippet}
///
/// ```dart
/// class TextScaleFactorReactor extends StatefulWidget {
/// const TextScaleFactorReactor({ super.key });
///
/// @override
/// State<TextScaleFactorReactor> createState() => _TextScaleFactorReactorState();
/// }
///
/// class _TextScaleFactorReactorState extends State<TextScaleFactorReactor> with WidgetsBindingObserver {
/// @override
/// void initState() {
/// super.initState();
/// WidgetsBinding.instance.addObserver(this);
/// }
///
/// @override
/// void dispose() {
/// WidgetsBinding.instance.removeObserver(this);
/// super.dispose();
/// }
///
/// late double _lastTextScaleFactor;
///
/// @override
/// void didChangeTextScaleFactor() {
/// setState(() { _lastTextScaleFactor = WidgetsBinding.instance.platformDispatcher.textScaleFactor; });
/// }
///
/// @override
/// Widget build(BuildContext context) {
/// return Text('Current scale factor: $_lastTextScaleFactor');
/// }
/// }
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [MediaQuery.textScaleFactorOf], which provides a similar service with less
/// boilerplate.
void didChangeTextScaleFactor() { }
/// Called when the platform brightness changes.
///
/// This method exposes notifications from
/// [dart:ui.PlatformDispatcher.onPlatformBrightnessChanged].
///
/// See also:
///
/// * [MediaQuery.platformBrightnessOf], which provides a similar service with
/// less boilerplate.
void didChangePlatformBrightness() { }
/// Called when the system tells the app that the user's locale has
/// changed. For example, if the user changes the system language
/// settings.
///
/// This method exposes notifications from
/// [dart:ui.PlatformDispatcher.onLocaleChanged].
void didChangeLocales(List<Locale>? locales) { }
/// Called when the system puts the app in the background or returns
/// the app to the foreground.
///
/// An example of implementing this method is provided in the class-level
/// documentation for the [WidgetsBindingObserver] class.
///
/// This method exposes notifications from [SystemChannels.lifecycle].
///
/// See also:
///
/// * [AppLifecycleListener], an alternative API for responding to
/// application lifecycle changes.
void didChangeAppLifecycleState(AppLifecycleState state) { }
/// Called when a request is received from the system to exit the application.
///
/// If any observer responds with [AppExitResponse.cancel], it will cancel the
/// exit. All observers will be asked before exiting.
///
/// {@macro flutter.services.binding.ServicesBinding.requestAppExit}
///
/// See also:
///
/// * [ServicesBinding.exitApplication] for a function to call that will request
/// that the application exits.
Future<AppExitResponse> didRequestAppExit() async {
return AppExitResponse.exit;
}
/// Called when the system is running low on memory.
///
/// This method exposes the `memoryPressure` notification from
/// [SystemChannels.system].
void didHaveMemoryPressure() { }
/// Called when the system changes the set of currently active accessibility
/// features.
///
/// This method exposes notifications from
/// [dart:ui.PlatformDispatcher.onAccessibilityFeaturesChanged].
void didChangeAccessibilityFeatures() { }
}
/// The glue between the widgets layer and the Flutter engine.
///
/// The [WidgetsBinding] manages a single [Element] tree rooted at [rootElement].
/// Calling [runApp] (which indirectly calls [attachRootWidget]) bootstraps that
/// element tree.
///
/// ## Relationship to render trees
///
/// Multiple render trees may be associated with the element tree. Those are
/// managed by the underlying [RendererBinding].
///
/// The element tree is segmented into two types of zones: rendering zones and
/// non-rendering zones.
///
/// A rendering zone is a part of the element tree that is backed by a render
/// tree and it describes the pixels that are drawn on screen. For elements in
/// this zone, [Element.renderObject] never returns null because the elements
/// are all associated with [RenderObject]s. Almost all widgets can be placed in
/// a rendering zone; notable exceptions are the [View] widget, [ViewCollection]
/// widget, and [RootWidget].
///
/// A non-rendering zone is a part of the element tree that is not backed by a
/// render tree. For elements in this zone, [Element.renderObject] returns null
/// because the elements are not associated with any [RenderObject]s. Only
/// widgets that do not produce a [RenderObject] can be used in this zone
/// because there is no render tree to attach the render object to. In other
/// words, [RenderObjectWidget]s cannot be used in this zone. Typically, one
/// would find [InheritedWidget]s, [View]s, and [ViewCollection]s in this zone
/// to inject data across rendering zones into the tree and to organize the
/// rendering zones (and by extension their associated render trees) into a
/// unified element tree.
///
/// The root of the element tree at [rootElement] starts a non-rendering zone.
/// Within a non-rendering zone, the [View] widget is used to start a rendering
/// zone by bootstrapping a render tree. Within a rendering zone, the
/// [ViewAnchor] can be used to start a new non-rendering zone.
///
// TODO(goderbauer): Include an example graph showcasing the different zones.
///
/// To figure out if an element is in a rendering zone it may walk up the tree
/// calling [Element.debugExpectsRenderObjectForSlot] on its ancestors. If it
/// reaches an element that returns false, it is in a non-rendering zone. If it
/// reaches a [RenderObjectElement] ancestor it is in a rendering zone.
mixin WidgetsBinding on BindingBase, ServicesBinding, SchedulerBinding, GestureBinding, RendererBinding, SemanticsBinding {
@override
void initInstances() {
super.initInstances();
_instance = this;
assert(() {
_debugAddStackFilters();
return true;
}());
// Initialization of [_buildOwner] has to be done after
// [super.initInstances] is called, as it requires [ServicesBinding] to
// properly setup the [defaultBinaryMessenger] instance.
_buildOwner = BuildOwner();
buildOwner!.onBuildScheduled = _handleBuildScheduled;
platformDispatcher.onLocaleChanged = handleLocaleChanged;
SystemChannels.navigation.setMethodCallHandler(_handleNavigationInvocation);
assert(() {
FlutterErrorDetails.propertiesTransformers.add(debugTransformDebugCreator);
return true;
}());
platformMenuDelegate = DefaultPlatformMenuDelegate();
}
/// The current [WidgetsBinding], if one has been created.
///
/// Provides access to the features exposed by this mixin. The binding must
/// be initialized before using this getter; this is typically done by calling
/// [runApp] or [WidgetsFlutterBinding.ensureInitialized].
static WidgetsBinding get instance => BindingBase.checkInstance(_instance);
static WidgetsBinding? _instance;
/// If true, forces the widget inspector to be visible.
///
/// Overrides the `debugShowWidgetInspector` value set in [WidgetsApp].
///
/// Used by the `debugShowWidgetInspector` debugging extension.
///
/// The inspector allows the selection of a location on your device or emulator
/// and view what widgets and render objects associated with it. An outline of
/// the selected widget and some summary information is shown on device and
/// more detailed information is shown in the IDE or DevTools.
bool get debugShowWidgetInspectorOverride {
return debugShowWidgetInspectorOverrideNotifier.value;
}
set debugShowWidgetInspectorOverride(bool value) {
debugShowWidgetInspectorOverrideNotifier.value = value;
}
/// Notifier for [debugShowWidgetInspectorOverride].
ValueNotifier<bool> get debugShowWidgetInspectorOverrideNotifier => _debugShowWidgetInspectorOverrideNotifierObject ??= ValueNotifier<bool>(false);
ValueNotifier<bool>? _debugShowWidgetInspectorOverrideNotifierObject;
@visibleForTesting
@override
void resetInternalState() {
// ignore: invalid_use_of_visible_for_testing_member, https://github.com/dart-lang/sdk/issues/41998
super.resetInternalState();
_debugShowWidgetInspectorOverrideNotifierObject?.dispose();
_debugShowWidgetInspectorOverrideNotifierObject = null;
}
void _debugAddStackFilters() {
const PartialStackFrame elementInflateWidget = PartialStackFrame(package: 'package:flutter/src/widgets/framework.dart', className: 'Element', method: 'inflateWidget');
const PartialStackFrame elementUpdateChild = PartialStackFrame(package: 'package:flutter/src/widgets/framework.dart', className: 'Element', method: 'updateChild');
const PartialStackFrame elementRebuild = PartialStackFrame(package: 'package:flutter/src/widgets/framework.dart', className: 'Element', method: 'rebuild');
const PartialStackFrame componentElementPerformRebuild = PartialStackFrame(package: 'package:flutter/src/widgets/framework.dart', className: 'ComponentElement', method: 'performRebuild');
const PartialStackFrame componentElementFirstBuild = PartialStackFrame(package: 'package:flutter/src/widgets/framework.dart', className: 'ComponentElement', method: '_firstBuild');
const PartialStackFrame componentElementMount = PartialStackFrame(package: 'package:flutter/src/widgets/framework.dart', className: 'ComponentElement', method: 'mount');
const PartialStackFrame statefulElementFirstBuild = PartialStackFrame(package: 'package:flutter/src/widgets/framework.dart', className: 'StatefulElement', method: '_firstBuild');
const PartialStackFrame singleChildMount = PartialStackFrame(package: 'package:flutter/src/widgets/framework.dart', className: 'SingleChildRenderObjectElement', method: 'mount');
const PartialStackFrame statefulElementRebuild = PartialStackFrame(package: 'package:flutter/src/widgets/framework.dart', className: 'StatefulElement', method: 'performRebuild');
const String replacementString = '... Normal element mounting';
// ComponentElement variations
FlutterError.addDefaultStackFilter(const RepetitiveStackFrameFilter(
frames: <PartialStackFrame>[
elementInflateWidget,
elementUpdateChild,
componentElementPerformRebuild,
elementRebuild,
componentElementFirstBuild,
componentElementMount,
],
replacement: replacementString,
));
FlutterError.addDefaultStackFilter(const RepetitiveStackFrameFilter(
frames: <PartialStackFrame>[
elementUpdateChild,
componentElementPerformRebuild,
elementRebuild,
componentElementFirstBuild,
componentElementMount,
],
replacement: replacementString,
));
// StatefulElement variations
FlutterError.addDefaultStackFilter(const RepetitiveStackFrameFilter(
frames: <PartialStackFrame>[
elementInflateWidget,
elementUpdateChild,
componentElementPerformRebuild,
statefulElementRebuild,
elementRebuild,
componentElementFirstBuild,
statefulElementFirstBuild,
componentElementMount,
],
replacement: replacementString,
));
FlutterError.addDefaultStackFilter(const RepetitiveStackFrameFilter(
frames: <PartialStackFrame>[
elementUpdateChild,
componentElementPerformRebuild,
statefulElementRebuild,
elementRebuild,
componentElementFirstBuild,
statefulElementFirstBuild,
componentElementMount,
],
replacement: replacementString,
));
// SingleChildRenderObjectElement variations
FlutterError.addDefaultStackFilter(const RepetitiveStackFrameFilter(
frames: <PartialStackFrame>[
elementInflateWidget,
elementUpdateChild,
singleChildMount,
],
replacement: replacementString,
));
FlutterError.addDefaultStackFilter(const RepetitiveStackFrameFilter(
frames: <PartialStackFrame>[
elementUpdateChild,
singleChildMount,
],
replacement: replacementString,
));
}
@override
void initServiceExtensions() {
super.initServiceExtensions();
if (!kReleaseMode) {
registerServiceExtension(
name: WidgetsServiceExtensions.debugDumpApp.name,
callback: (Map<String, String> parameters) async {
final String data = _debugDumpAppString();
return <String, Object>{
'data': data,
};
},
);
registerServiceExtension(
name: WidgetsServiceExtensions.debugDumpFocusTree.name,
callback: (Map<String, String> parameters) async {
final String data = focusManager.toStringDeep();
return <String, Object>{
'data': data,
};
},
);
if (!kIsWeb) {
registerBoolServiceExtension(
name: WidgetsServiceExtensions.showPerformanceOverlay.name,
getter: () =>
Future<bool>.value(WidgetsApp.showPerformanceOverlayOverride),
setter: (bool value) {
if (WidgetsApp.showPerformanceOverlayOverride == value) {
return Future<void>.value();
}
WidgetsApp.showPerformanceOverlayOverride = value;
return _forceRebuild();
},
);
}
registerServiceExtension(
name: WidgetsServiceExtensions.didSendFirstFrameEvent.name,
callback: (_) async {
return <String, dynamic>{
// This is defined to return a STRING, not a boolean.
// Devtools, the Intellij plugin, and the flutter tool all depend
// on it returning a string and not a boolean.
'enabled': _needToReportFirstFrame ? 'false' : 'true',
};
},
);
registerServiceExtension(
name: WidgetsServiceExtensions.didSendFirstFrameRasterizedEvent.name,
callback: (_) async {
return <String, dynamic>{
// This is defined to return a STRING, not a boolean.
// Devtools, the Intellij plugin, and the flutter tool all depend
// on it returning a string and not a boolean.
'enabled': firstFrameRasterized ? 'true' : 'false',
};
},
);
// Expose the ability to send Widget rebuilds as [Timeline] events.
registerBoolServiceExtension(
name: WidgetsServiceExtensions.profileWidgetBuilds.name,
getter: () async => debugProfileBuildsEnabled,
setter: (bool value) async {
debugProfileBuildsEnabled = value;
}
);
registerBoolServiceExtension(
name: WidgetsServiceExtensions.profileUserWidgetBuilds.name,
getter: () async => debugProfileBuildsEnabledUserWidgets,
setter: (bool value) async {
debugProfileBuildsEnabledUserWidgets = value;
}
);
}
assert(() {
registerBoolServiceExtension(
name: WidgetsServiceExtensions.debugAllowBanner.name,
getter: () => Future<bool>.value(WidgetsApp.debugAllowBannerOverride),
setter: (bool value) {
if (WidgetsApp.debugAllowBannerOverride == value) {
return Future<void>.value();
}
WidgetsApp.debugAllowBannerOverride = value;
return _forceRebuild();
},
);
WidgetInspectorService.instance.initServiceExtensions(registerServiceExtension);
return true;
}());
}
Future<void> _forceRebuild() {
if (rootElement != null) {
buildOwner!.reassemble(rootElement!);
return endOfFrame;
}
return Future<void>.value();
}
/// The [BuildOwner] in charge of executing the build pipeline for the
/// widget tree rooted at this binding.
BuildOwner? get buildOwner => _buildOwner;
// Initialization of [_buildOwner] has to be done within the [initInstances]
// method, as it requires [ServicesBinding] to properly setup the
// [defaultBinaryMessenger] instance.
BuildOwner? _buildOwner;
/// The object in charge of the focus tree.
///
/// Rarely used directly. Instead, consider using [FocusScope.of] to obtain
/// the [FocusScopeNode] for a given [BuildContext].
///
/// See [FocusManager] for more details.
FocusManager get focusManager => _buildOwner!.focusManager;
/// A delegate that communicates with a platform plugin for serializing and
/// managing platform-rendered menu bars created by [PlatformMenuBar].
///
/// This is set by default to a [DefaultPlatformMenuDelegate] instance in
/// [initInstances].
late PlatformMenuDelegate platformMenuDelegate;
final List<WidgetsBindingObserver> _observers = <WidgetsBindingObserver>[];
/// Registers the given object as a binding observer. Binding
/// observers are notified when various application events occur,
/// for example when the system locale changes. Generally, one
/// widget in the widget tree registers itself as a binding
/// observer, and converts the system state into inherited widgets.
///
/// For example, the [WidgetsApp] widget registers as a binding
/// observer and passes the screen size to a [MediaQuery] widget
/// each time it is built, which enables other widgets to use the
/// [MediaQuery.sizeOf] static method and (implicitly) the
/// [InheritedWidget] mechanism to be notified whenever the screen
/// size changes (e.g. whenever the screen rotates).
///
/// See also:
///
/// * [removeObserver], to release the resources reserved by this method.
/// * [WidgetsBindingObserver], which has an example of using this method.
void addObserver(WidgetsBindingObserver observer) => _observers.add(observer);
/// Unregisters the given observer. This should be used sparingly as
/// it is relatively expensive (O(N) in the number of registered
/// observers).
///
/// See also:
///
/// * [addObserver], for the method that adds observers in the first place.
/// * [WidgetsBindingObserver], which has an example of using this method.
bool removeObserver(WidgetsBindingObserver observer) => _observers.remove(observer);
@override
Future<AppExitResponse> handleRequestAppExit() async {
bool didCancel = false;
for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.of(_observers)) {
if ((await observer.didRequestAppExit()) == AppExitResponse.cancel) {
didCancel = true;
// Don't early return. For the case where someone is just using the
// observer to know when exit happens, we want to call all the
// observers, even if we already know we're going to cancel.
}
}
return didCancel ? AppExitResponse.cancel : AppExitResponse.exit;
}
@override
void handleMetricsChanged() {
super.handleMetricsChanged();
for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.of(_observers)) {
observer.didChangeMetrics();
}
}
@override
void handleTextScaleFactorChanged() {
super.handleTextScaleFactorChanged();
for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.of(_observers)) {
observer.didChangeTextScaleFactor();
}
}
@override
void handlePlatformBrightnessChanged() {
super.handlePlatformBrightnessChanged();
for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.of(_observers)) {
observer.didChangePlatformBrightness();
}
}
@override
void handleAccessibilityFeaturesChanged() {
super.handleAccessibilityFeaturesChanged();
for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.of(_observers)) {
observer.didChangeAccessibilityFeatures();
}
}
/// Called when the system locale changes.
///
/// Calls [dispatchLocalesChanged] to notify the binding observers.
///
/// See [dart:ui.PlatformDispatcher.onLocaleChanged].
@protected
@mustCallSuper
@visibleForTesting
void handleLocaleChanged() {
dispatchLocalesChanged(platformDispatcher.locales);
}
/// Notify all the observers that the locale has changed (using
/// [WidgetsBindingObserver.didChangeLocales]), giving them the
/// `locales` argument.
///
/// This is called by [handleLocaleChanged] when the
/// [PlatformDispatcher.onLocaleChanged] notification is received.
@protected
@mustCallSuper
void dispatchLocalesChanged(List<Locale>? locales) {
for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.of(_observers)) {
observer.didChangeLocales(locales);
}
}
/// Notify all the observers that the active set of [AccessibilityFeatures]
/// has changed (using [WidgetsBindingObserver.didChangeAccessibilityFeatures]),
/// giving them the `features` argument.
///
/// This is called by [handleAccessibilityFeaturesChanged] when the
/// [PlatformDispatcher.onAccessibilityFeaturesChanged] notification is received.
@protected
@mustCallSuper
void dispatchAccessibilityFeaturesChanged() {
for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.of(_observers)) {
observer.didChangeAccessibilityFeatures();
}
}
/// Called when the system pops the current route.
///
/// This first notifies the binding observers (using
/// [WidgetsBindingObserver.didPopRoute]), in registration order, until one
/// returns true, meaning that it was able to handle the request (e.g. by
/// closing a dialog box). If none return true, then the application is shut
/// down by calling [SystemNavigator.pop].
///
/// [WidgetsApp] uses this in conjunction with a [Navigator] to
/// cause the back button to close dialog boxes, return from modal
/// pages, and so forth.
///
/// This method exposes the `popRoute` notification from
/// [SystemChannels.navigation].
///
/// {@template flutter.widgets.AndroidPredictiveBack}
/// ## Handling backs ahead of time
///
/// Not all system backs will result in a call to this method. Some are
/// handled entirely by the system without informing the Flutter framework.
///
/// Android API 33+ introduced a feature called predictive back, which allows
/// the user to peek behind the current app or route during a back gesture and
/// then decide to cancel or commit the back. Flutter enables or disables this
/// feature ahead of time, before a back gesture occurs, and back gestures
/// that trigger predictive back are handled entirely by the system and do not
/// trigger this method here in the framework.
///
/// By default, the framework communicates when it would like to handle system
/// back gestures using [SystemNavigator.setFrameworkHandlesBack] in
/// [WidgetsApp]. This is done automatically based on the status of the
/// [Navigator] stack and the state of any [PopScope] widgets present.
/// Developers can manually set this by calling the method directly or by
/// using [NavigationNotification].
/// {@endtemplate}
@protected
@visibleForTesting
Future<void> handlePopRoute() async {
for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.of(_observers)) {
if (await observer.didPopRoute()) {
return;
}
}
SystemNavigator.pop();
}
/// Called when the host tells the app to push a new route onto the
/// navigator.
///
/// This notifies the binding observers (using
/// [WidgetsBindingObserver.didPushRoute]), in registration order, until one
/// returns true, meaning that it was able to handle the request (e.g. by
/// opening a dialog box). If none return true, then nothing happens.
///
/// This method exposes the `pushRoute` notification from
/// [SystemChannels.navigation].
@protected
@mustCallSuper
@visibleForTesting
Future<void> handlePushRoute(String route) async {
final RouteInformation routeInformation = RouteInformation(uri: Uri.parse(route));
for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.of(_observers)) {
if (await observer.didPushRouteInformation(routeInformation)) {
return;
}
}
}
Future<void> _handlePushRouteInformation(Map<dynamic, dynamic> routeArguments) async {
final RouteInformation routeInformation = RouteInformation(
uri: Uri.parse(routeArguments['location'] as String),
state: routeArguments['state'] as Object?,
);
for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.of(_observers)) {
if (await observer.didPushRouteInformation(routeInformation)) {
return;
}
}
}
Future<dynamic> _handleNavigationInvocation(MethodCall methodCall) {
return switch (methodCall.method) {
'popRoute' => handlePopRoute(),
'pushRoute' => handlePushRoute(methodCall.arguments as String),
'pushRouteInformation' => _handlePushRouteInformation(methodCall.arguments as Map<dynamic, dynamic>),
_ => Future<dynamic>.value(),
};
}
@override
void handleAppLifecycleStateChanged(AppLifecycleState state) {
super.handleAppLifecycleStateChanged(state);
for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.of(_observers)) {
observer.didChangeAppLifecycleState(state);
}
}
@override
void handleMemoryPressure() {
super.handleMemoryPressure();
for (final WidgetsBindingObserver observer in List<WidgetsBindingObserver>.of(_observers)) {
observer.didHaveMemoryPressure();
}
}
bool _needToReportFirstFrame = true;
final Completer<void> _firstFrameCompleter = Completer<void>();
/// Whether the Flutter engine has rasterized the first frame.
///
/// Usually, the time that a frame is rasterized is very close to the time that
/// it gets presented on the display. Specifically, rasterization is the last
/// expensive phase of a frame that's still in Flutter's control.
///
/// See also:
///
/// * [waitUntilFirstFrameRasterized], the future when [firstFrameRasterized]
/// becomes true.
bool get firstFrameRasterized => _firstFrameCompleter.isCompleted;
/// A future that completes when the Flutter engine has rasterized the first
/// frame.
///
/// Usually, the time that a frame is rasterized is very close to the time that
/// it gets presented on the display. Specifically, rasterization is the last
/// expensive phase of a frame that's still in Flutter's control.
///
/// See also:
///
/// * [firstFrameRasterized], whether this future has completed or not.
Future<void> get waitUntilFirstFrameRasterized => _firstFrameCompleter.future;
/// Whether the first frame has finished building.
///
/// This value can also be obtained over the VM service protocol as
/// `ext.flutter.didSendFirstFrameEvent`.
///
/// See also:
///
/// * [firstFrameRasterized], whether the first frame has finished rendering.
bool get debugDidSendFirstFrameEvent => !_needToReportFirstFrame;
void _handleBuildScheduled() {
// If we're in the process of building dirty elements, then changes
// should not trigger a new frame.
assert(() {
if (debugBuildingDirtyElements) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Build scheduled during frame.'),
ErrorDescription(
'While the widget tree was being built, laid out, and painted, '
'a new frame was scheduled to rebuild the widget tree.',
),
ErrorHint(
'This might be because setState() was called from a layout or '
'paint callback. '
'If a change is needed to the widget tree, it should be applied '
'as the tree is being built. Scheduling a change for the subsequent '
'frame instead results in an interface that lags behind by one frame. '
'If this was done to make your build dependent on a size measured at '
'layout time, consider using a LayoutBuilder, CustomSingleChildLayout, '
'or CustomMultiChildLayout. If, on the other hand, the one frame delay '
'is the desired effect, for example because this is an '
'animation, consider scheduling the frame in a post-frame callback '
'using SchedulerBinding.addPostFrameCallback or '
'using an AnimationController to trigger the animation.',
),
]);
}
return true;
}());
ensureVisualUpdate();
}
/// Whether we are currently in a frame. This is used to verify
/// that frames are not scheduled redundantly.
///
/// This is public so that test frameworks can change it.
///
/// This flag is not used in release builds.
@protected
bool debugBuildingDirtyElements = false;
/// Pump the build and rendering pipeline to generate a frame.
///
/// This method is called by [handleDrawFrame], which itself is called
/// automatically by the engine when it is time to lay out and paint a
/// frame.
///
/// Each frame consists of the following phases:
///
/// 1. The animation phase: The [handleBeginFrame] method, which is registered
/// with [PlatformDispatcher.onBeginFrame], invokes all the transient frame
/// callbacks registered with [scheduleFrameCallback], in registration order.
/// This includes all the [Ticker] instances that are driving
/// [AnimationController] objects, which means all of the active [Animation]
/// objects tick at this point.
///
/// 2. Microtasks: After [handleBeginFrame] returns, any microtasks that got
/// scheduled by transient frame callbacks get to run. This typically includes
/// callbacks for futures from [Ticker]s and [AnimationController]s that
/// completed this frame.
///
/// After [handleBeginFrame], [handleDrawFrame], which is registered with
/// [PlatformDispatcher.onDrawFrame], is called, which invokes all the
/// persistent frame callbacks, of which the most notable is this method,
/// [drawFrame], which proceeds as follows:
///
/// 3. The build phase: All the dirty [Element]s in the widget tree are
/// rebuilt (see [State.build]). See [State.setState] for further details on
/// marking a widget dirty for building. See [BuildOwner] for more information
/// on this step.
///
/// 4. The layout phase: All the dirty [RenderObject]s in the system are laid
/// out (see [RenderObject.performLayout]). See [RenderObject.markNeedsLayout]
/// for further details on marking an object dirty for layout.
///
/// 5. The compositing bits phase: The compositing bits on any dirty
/// [RenderObject] objects are updated. See
/// [RenderObject.markNeedsCompositingBitsUpdate].
///
/// 6. The paint phase: All the dirty [RenderObject]s in the system are
/// repainted (see [RenderObject.paint]). This generates the [Layer] tree. See
/// [RenderObject.markNeedsPaint] for further details on marking an object
/// dirty for paint.
///
/// 7. The compositing phase: The layer tree is turned into a [Scene] and
/// sent to the GPU.
///
/// 8. The semantics phase: All the dirty [RenderObject]s in the system have
/// their semantics updated (see [RenderObject.assembleSemanticsNode]). This
/// generates the [SemanticsNode] tree. See
/// [RenderObject.markNeedsSemanticsUpdate] for further details on marking an
/// object dirty for semantics.
///
/// For more details on steps 4-8, see [PipelineOwner].
///
/// 9. The finalization phase in the widgets layer: The widgets tree is
/// finalized. This causes [State.dispose] to be invoked on any objects that
/// were removed from the widgets tree this frame. See
/// [BuildOwner.finalizeTree] for more details.
///
/// 10. The finalization phase in the scheduler layer: After [drawFrame]
/// returns, [handleDrawFrame] then invokes post-frame callbacks (registered
/// with [addPostFrameCallback]).
//
// When editing the above, also update rendering/binding.dart's copy.
@override
void drawFrame() {
assert(!debugBuildingDirtyElements);
assert(() {
debugBuildingDirtyElements = true;
return true;
}());
TimingsCallback? firstFrameCallback;
bool debugFrameWasSentToEngine = false;
if (_needToReportFirstFrame) {
assert(!_firstFrameCompleter.isCompleted);
firstFrameCallback = (List<FrameTiming> timings) {
assert(debugFrameWasSentToEngine);
if (!kReleaseMode) {
// Change the current user tag back to the default tag. At this point,
// the user tag should be set to "AppStartUp" (originally set in the
// engine), so we need to change it back to the default tag to mark
// the end of app start up for CPU profiles.
developer.UserTag.defaultTag.makeCurrent();
developer.Timeline.instantSync('Rasterized first useful frame');
developer.postEvent('Flutter.FirstFrame', <String, dynamic>{});
}
SchedulerBinding.instance.removeTimingsCallback(firstFrameCallback!);
firstFrameCallback = null;
_firstFrameCompleter.complete();
};
// Callback is only invoked when FlutterView.render is called. When
// sendFramesToEngine is set to false during the frame, it will not be
// called and we need to remove the callback (see below).
SchedulerBinding.instance.addTimingsCallback(firstFrameCallback!);
}
try {
if (rootElement != null) {
buildOwner!.buildScope(rootElement!);
}
super.drawFrame();
assert(() {
debugFrameWasSentToEngine = sendFramesToEngine;
return true;
}());
buildOwner!.finalizeTree();
} finally {
assert(() {
debugBuildingDirtyElements = false;
return true;
}());
}
if (!kReleaseMode) {
if (_needToReportFirstFrame && sendFramesToEngine) {
developer.Timeline.instantSync('Widgets built first useful frame');
}
}
_needToReportFirstFrame = false;
if (firstFrameCallback != null && !sendFramesToEngine) {
// This frame is deferred and not the first frame sent to the engine that
// should be reported.
_needToReportFirstFrame = true;
SchedulerBinding.instance.removeTimingsCallback(firstFrameCallback!);
}
}
/// The [Element] that is at the root of the element tree hierarchy.
///
/// This is initialized the first time [runApp] is called.
Element? get rootElement => _rootElement;
Element? _rootElement;
/// Deprecated. Will be removed in a future version of Flutter.
///
/// Use [rootElement] instead.
@Deprecated(
'Use rootElement instead. '
'This feature was deprecated after v3.9.0-16.0.pre.'
)
Element? get renderViewElement => rootElement;
bool _readyToProduceFrames = false;
@override
bool get framesEnabled => super.framesEnabled && _readyToProduceFrames;
/// Used by [runApp] to wrap the provided `rootWidget` in the default [View].
///
/// The [View] determines into what [FlutterView] the app is rendered into.
/// This is currently [PlatformDispatcher.implicitView] from [platformDispatcher].
///
/// The `rootWidget` widget provided to this method must not already be
/// wrapped in a [View].
Widget wrapWithDefaultView(Widget rootWidget) {
return View(
view: platformDispatcher.implicitView!,
deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner: pipelineOwner,
deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView: renderView,
child: rootWidget,
);
}
/// Schedules a [Timer] for attaching the root widget.
///
/// This is called by [runApp] to configure the widget tree. Consider using
/// [attachRootWidget] if you want to build the widget tree synchronously.
@protected
void scheduleAttachRootWidget(Widget rootWidget) {
Timer.run(() {
attachRootWidget(rootWidget);
});
}
/// Takes a widget and attaches it to the [rootElement], creating it if
/// necessary.
///
/// This is called by [runApp] to configure the widget tree.
///
/// See also:
///
/// * [RenderObjectToWidgetAdapter.attachToRenderTree], which inflates a
/// widget and attaches it to the render tree.
void attachRootWidget(Widget rootWidget) {
attachToBuildOwner(RootWidget(
debugShortDescription: '[root]',
child: rootWidget,
));
}
/// Called by [attachRootWidget] to attach the provided [RootWidget] to the
/// [buildOwner].
///
/// This creates the [rootElement], if necessary, or re-uses an existing one.
///
/// This method is rarely called directly, but it can be useful in tests to
/// restore the element tree to a previous version by providing the
/// [RootWidget] of that version (see [WidgetTester.restartAndRestore] for an
/// exemplary use case).
void attachToBuildOwner(RootWidget widget) {
final bool isBootstrapFrame = rootElement == null;
_readyToProduceFrames = true;
_rootElement = widget.attach(buildOwner!, rootElement as RootElement?);
if (isBootstrapFrame) {
SchedulerBinding.instance.ensureVisualUpdate();
}
}
/// Whether the [rootElement] has been initialized.
///
/// This will be false until [runApp] is called (or [WidgetTester.pumpWidget]
/// is called in the context of a [TestWidgetsFlutterBinding]).
bool get isRootWidgetAttached => _rootElement != null;
@override
Future<void> performReassemble() {
assert(() {
WidgetInspectorService.instance.performReassemble();
return true;
}());
if (rootElement != null) {
buildOwner!.reassemble(rootElement!);
}
return super.performReassemble();
}
/// Computes the locale the current platform would resolve to.
///
/// This method is meant to be used as part of a
/// [WidgetsApp.localeListResolutionCallback]. Since this method may return
/// null, a Flutter/dart algorithm should still be provided as a fallback in
/// case a native resolved locale cannot be determined or if the native
/// resolved locale is undesirable.
///
/// This method may return a null [Locale] if the platform does not support
/// native locale resolution, or if the resolution failed.
///
/// The first `supportedLocale` is treated as the default locale and will be returned
/// if no better match is found.
///
/// Android and iOS are currently supported.
///
/// On Android, the algorithm described in
/// https://developer.android.com/guide/topics/resources/multilingual-support
/// is used to determine the resolved locale. Depending on the android version
/// of the device, either the modern (>= API 24) or legacy (< API 24) algorithm
/// will be used.
///
/// On iOS, the result of `preferredLocalizationsFromArray` method of `NSBundle`
/// is returned. See:
/// https://developer.apple.com/documentation/foundation/nsbundle/1417249-preferredlocalizationsfromarray?language=objc
/// for details on the used method.
///
/// iOS treats script code as necessary for a match, so a user preferred locale of
/// `zh_Hans_CN` will not resolve to a supported locale of `zh_CN`.
///
/// Since implementation may vary by platform and has potential to be heavy,
/// it is recommended to cache the results of this method if the value is
/// used multiple times.
///
/// Second-best (and n-best) matching locales should be obtained by calling this
/// method again with the matched locale of the first call omitted from
/// `supportedLocales`.
Locale? computePlatformResolvedLocale(List<Locale> supportedLocales) {
return platformDispatcher.computePlatformResolvedLocale(supportedLocales);
}
}
/// Inflate the given widget and attach it to the view.
///
// TODO(goderbauer): Update the paragraph below to include the Window widget once that exists.
/// The [runApp] method renders the provided `app` widget into the
/// [PlatformDispatcher.implicitView] by wrapping it in a [View] widget, which
/// will bootstrap the render tree for the app. Apps that want to control which
/// [FlutterView] they render into can use [runWidget] instead.
///
/// The widget is given constraints during layout that force it to fill the
/// entire view. If you wish to align your widget to one side of the view
/// (e.g., the top), consider using the [Align] widget. If you wish to center
/// your widget, you can also use the [Center] widget.
///
/// Calling [runApp] again will detach the previous root widget from the view
/// and attach the given widget in its place. The new widget tree is compared
/// against the previous widget tree and any differences are applied to the
/// underlying render tree, similar to what happens when a [StatefulWidget]
/// rebuilds after calling [State.setState].
///
/// Initializes the binding using [WidgetsFlutterBinding] if necessary.
///
/// {@template flutter.widgets.runApp.shutdown}
/// ## Application shutdown
///
/// This widget tree is not torn down when the application shuts down, because
/// there is no way to predict when that will happen. For example, a user could
/// physically remove power from their device, or the application could crash
/// unexpectedly, or the malware on the device could forcibly terminate the
/// process.
///
/// Applications are responsible for ensuring that they are well-behaved
/// even in the face of a rapid unscheduled termination.
///
/// To listen for platform shutdown messages (and other lifecycle changes),
/// consider the [AppLifecycleListener] API.
/// {@endtemplate}
///
/// To artificially cause the entire widget tree to be disposed, consider
/// calling [runApp] with a widget such as [SizedBox.shrink].
///
/// {@template flutter.widgets.runApp.dismissal}
/// ## Dismissing Flutter UI via platform native methods
///
/// An application may have both Flutter and non-Flutter UI in it. If the
/// application calls non-Flutter methods to remove Flutter based UI such as
/// platform native API to manipulate the platform native navigation stack,
/// the framework does not know if the developer intends to eagerly free
/// resources or not. The widget tree remains mounted and ready to render
/// as soon as it is displayed again.
/// {@endtemplate}
///
/// To release resources more eagerly, establish a [platform channel](https://flutter.dev/platform-channels/)
/// and use it to call [runApp] with a widget such as [SizedBox.shrink] when
/// the framework should dispose of the active widget tree.
///
/// See also:
///
/// * [runWidget], which bootstraps a widget tree without assuming the
/// [FlutterView] into which it will be rendered.
/// * [WidgetsBinding.attachRootWidget], which creates the root widget for the
/// widget hierarchy.
/// * [RenderObjectToWidgetAdapter.attachToRenderTree], which creates the root
/// element for the element hierarchy.
/// * [WidgetsBinding.handleBeginFrame], which pumps the widget pipeline to
/// ensure the widget, element, and render trees are all built.
void runApp(Widget app) {
final WidgetsBinding binding = WidgetsFlutterBinding.ensureInitialized();
_runWidget(binding.wrapWithDefaultView(app), binding, 'runApp');
}
/// Inflate the given widget and bootstrap the widget tree.
///
// TODO(goderbauer): Update the paragraph below to include the Window widget once that exists.
/// Unlike [runApp], this method does not define a [FlutterView] into which the
/// provided `app` widget is rendered into. It is up to the caller to include at
/// least one [View] widget in the provided `app` widget that will bootstrap a
/// render tree and define the [FlutterView] into which content is rendered.
/// [RenderObjectWidget]s without an ancestor [View] widget will result in an
/// exception. Apps that want to render into the default view without dealing
/// with view management should consider calling [runApp] instead.
///
/// {@tool snippet}
/// The sample shows how to utilize [runWidget] to specify the [FlutterView]
/// into which the `MyApp` widget will be drawn:
///
/// ```dart
/// runWidget(
/// View(
/// view: myFlutterView,
/// child: const MyApp(),
/// ),
/// );
/// ```
/// {@end-tool}
///
/// Calling [runWidget] again will detach the previous root widget and attach
/// the given widget in its place. The new widget tree is compared against the
/// previous widget tree and any differences are applied to the underlying
/// render tree, similar to what happens when a [StatefulWidget] rebuilds after
/// calling [State.setState].
///
/// Initializes the binding using [WidgetsFlutterBinding] if necessary.
///
/// {@macro flutter.widgets.runApp.shutdown}
///
/// To artificially cause the entire widget tree to be disposed, consider
/// calling [runWidget] with a [ViewCollection] that does not specify any
/// [ViewCollection.views].
///
/// ## Dismissing Flutter UI via platform native methods
///
/// {@macro flutter.widgets.runApp.dismissal}
///
/// To release resources more eagerly, establish a [platform channel](https://flutter.dev/platform-channels/)
/// and use it to remove the [View] whose widget resources should be released
/// from the `app` widget tree provided to [runWidget].
///
/// See also:
///
/// * [runApp], which bootstraps a widget tree and renders it into a default
/// [FlutterView].
/// * [WidgetsBinding.attachRootWidget], which creates the root widget for the
/// widget hierarchy.
/// * [RenderObjectToWidgetAdapter.attachToRenderTree], which creates the root
/// element for the element hierarchy.
/// * [WidgetsBinding.handleBeginFrame], which pumps the widget pipeline to
/// ensure the widget, element, and render trees are all built.
void runWidget(Widget app) {
final WidgetsBinding binding = WidgetsFlutterBinding.ensureInitialized();
_runWidget(app, binding, 'runWidget');
}
void _runWidget(Widget app, WidgetsBinding binding, String debugEntryPoint) {
assert(binding.debugCheckZone(debugEntryPoint));
binding
..scheduleAttachRootWidget(app)
..scheduleWarmUpFrame();
}
String _debugDumpAppString() {
const String mode = kDebugMode ? 'DEBUG MODE' : kReleaseMode ? 'RELEASE MODE' : 'PROFILE MODE';
final StringBuffer buffer = StringBuffer();
buffer.writeln('${WidgetsBinding.instance.runtimeType} - $mode');
if (WidgetsBinding.instance.rootElement != null) {
buffer.writeln(WidgetsBinding.instance.rootElement!.toStringDeep());
} else {
buffer.writeln('<no tree currently mounted>');
}
return buffer.toString();
}
/// Print a string representation of the currently running app.
void debugDumpApp() {
debugPrint(_debugDumpAppString());
}
/// A widget for the root of the widget tree.
///
/// Exposes an [attach] method to attach the widget tree to a [BuildOwner]. That
/// method also bootstraps the element tree.
///
/// Used by [WidgetsBinding.attachRootWidget] (which is indirectly called by
/// [runApp]) to bootstrap applications.
class RootWidget extends Widget {
/// Creates a [RootWidget].
const RootWidget({
super.key,
this.child,
this.debugShortDescription,
});
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
/// A short description of this widget used by debugging aids.
final String? debugShortDescription;
@override
RootElement createElement() => RootElement(this);
/// Inflate this widget and attaches it to the provided [BuildOwner].
///
/// If `element` is null, this function will create a new element. Otherwise,
/// the given element will have an update scheduled to switch to this widget.
///
/// Used by [WidgetsBinding.attachToBuildOwner] (which is indirectly called by
/// [runApp]) to bootstrap applications.
RootElement attach(BuildOwner owner, [ RootElement? element ]) {
if (element == null) {
owner.lockState(() {
element = createElement();
assert(element != null);
element!.assignOwner(owner);
});
owner.buildScope(element!, () {
element!.mount(/* parent */ null, /* slot */ null);
});
} else {
element._newWidget = this;
element.markNeedsBuild();
}
return element!;
}
@override
String toStringShort() => debugShortDescription ?? super.toStringShort();
}
/// The root of the element tree.
///
/// This element class is the instantiation of a [RootWidget]. It can be used
/// only as the root of an [Element] tree (it cannot be mounted into another
/// [Element]; its parent must be null).
///
/// In typical usage, it will be instantiated for a [RootWidget] by calling
/// [RootWidget.attach]. In this usage, it is normally instantiated by the
/// bootstrapping logic in the [WidgetsFlutterBinding] singleton created by
/// [runApp].
class RootElement extends Element with RootElementMixin {
/// Creates a [RootElement] for the provided [RootWidget].
RootElement(RootWidget super.widget);
Element? _child;
@override
void visitChildren(ElementVisitor visitor) {
if (_child != null) {
visitor(_child!);
}
}
@override
void forgetChild(Element child) {
assert(child == _child);
_child = null;
super.forgetChild(child);
}
@override
void mount(Element? parent, Object? newSlot) {
assert(parent == null); // We are the root!
super.mount(parent, newSlot);
_rebuild();
assert(_child != null);
super.performRebuild(); // clears the "dirty" flag
}
@override
void update(RootWidget newWidget) {
super.update(newWidget);
assert(widget == newWidget);
_rebuild();
}
// When we are assigned a new widget, we store it here
// until we are ready to update to it.
RootWidget? _newWidget;
@override
void performRebuild() {
if (_newWidget != null) {
// _newWidget can be null if, for instance, we were rebuilt
// due to a reassemble.
final RootWidget newWidget = _newWidget!;
_newWidget = null;
update(newWidget);
}
super.performRebuild();
assert(_newWidget == null);
}
void _rebuild() {
try {
_child = updateChild(_child, (widget as RootWidget).child, /* slot */ null);
} catch (exception, stack) {
final FlutterErrorDetails details = FlutterErrorDetails(
exception: exception,
stack: stack,
library: 'widgets library',
context: ErrorDescription('attaching to the render tree'),
);
FlutterError.reportError(details);
// No error widget possible here since it wouldn't have a view to render into.
_child = null;
}
}
@override
bool get debugDoingBuild => false; // This element doesn't have a build phase.
@override
// There is no ancestor RenderObjectElement that the render object could be attached to.
bool debugExpectsRenderObjectForSlot(Object? slot) => false;
}
/// A concrete binding for applications based on the Widgets framework.
///
/// This is the glue that binds the framework to the Flutter engine.
///
/// When using the widgets framework, this binding, or one that
/// implements the same interfaces, must be used. The following
/// mixins are used to implement this binding:
///
/// * [GestureBinding], which implements the basics of hit testing.
/// * [SchedulerBinding], which introduces the concepts of frames.
/// * [ServicesBinding], which provides access to the plugin subsystem.
/// * [PaintingBinding], which enables decoding images.
/// * [SemanticsBinding], which supports accessibility.
/// * [RendererBinding], which handles the render tree.
/// * [WidgetsBinding], which handles the widget tree.
class WidgetsFlutterBinding extends BindingBase with GestureBinding, SchedulerBinding, ServicesBinding, PaintingBinding, SemanticsBinding, RendererBinding, WidgetsBinding {
/// Returns an instance of the binding that implements
/// [WidgetsBinding]. If no binding has yet been initialized, the
/// [WidgetsFlutterBinding] class is used to create and initialize
/// one.
///
/// You only need to call this method if you need the binding to be
/// initialized before calling [runApp].
///
/// In the `flutter_test` framework, [testWidgets] initializes the
/// binding instance to a [TestWidgetsFlutterBinding], not a
/// [WidgetsFlutterBinding]. See
/// [TestWidgetsFlutterBinding.ensureInitialized].
static WidgetsBinding ensureInitialized() {
if (WidgetsBinding._instance == null) {
WidgetsFlutterBinding();
}
return WidgetsBinding.instance;
}
}
| flutter/packages/flutter/lib/src/widgets/binding.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/binding.dart",
"repo_id": "flutter",
"token_count": 18233
} | 642 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'basic.dart';
import 'binding.dart';
import 'framework.dart';
import 'inherited_notifier.dart';
import 'layout_builder.dart';
import 'notification_listener.dart';
import 'scroll_activity.dart';
import 'scroll_context.dart';
import 'scroll_controller.dart';
import 'scroll_notification.dart';
import 'scroll_physics.dart';
import 'scroll_position.dart';
import 'scroll_position_with_single_context.dart';
import 'scroll_simulation.dart';
import 'value_listenable_builder.dart';
/// The signature of a method that provides a [BuildContext] and
/// [ScrollController] for building a widget that may overflow the draggable
/// [Axis] of the containing [DraggableScrollableSheet].
///
/// Users should apply the [scrollController] to a [ScrollView] subclass, such
/// as a [SingleChildScrollView], [ListView] or [GridView], to have the whole
/// sheet be draggable.
typedef ScrollableWidgetBuilder = Widget Function(
BuildContext context,
ScrollController scrollController,
);
/// Controls a [DraggableScrollableSheet].
///
/// Draggable scrollable controllers are typically stored as member variables in
/// [State] objects and are reused in each [State.build]. Controllers can only
/// be used to control one sheet at a time. A controller can be reused with a
/// new sheet if the previous sheet has been disposed.
///
/// The controller's methods cannot be used until after the controller has been
/// passed into a [DraggableScrollableSheet] and the sheet has run initState.
///
/// A [DraggableScrollableController] is a [Listenable]. It notifies its
/// listeners whenever an attached sheet changes sizes. It does not notify its
/// listeners when a sheet is first attached or when an attached sheet's
/// parameters change without affecting the sheet's current size. It does not
/// fire when [pixels] changes without [size] changing. For example, if the
/// constraints provided to an attached sheet change.
class DraggableScrollableController extends ChangeNotifier {
/// Creates a controller for [DraggableScrollableSheet].
DraggableScrollableController() {
if (kFlutterMemoryAllocationsEnabled) {
ChangeNotifier.maybeDispatchObjectCreation(this);
}
}
_DraggableScrollableSheetScrollController? _attachedController;
final Set<AnimationController> _animationControllers = <AnimationController>{};
/// Get the current size (as a fraction of the parent height) of the attached sheet.
double get size {
_assertAttached();
return _attachedController!.extent.currentSize;
}
/// Get the current pixel height of the attached sheet.
double get pixels {
_assertAttached();
return _attachedController!.extent.currentPixels;
}
/// Convert a sheet's size (fractional value of parent container height) to pixels.
double sizeToPixels(double size) {
_assertAttached();
return _attachedController!.extent.sizeToPixels(size);
}
/// Returns Whether any [DraggableScrollableController] objects have attached themselves to the
/// [DraggableScrollableSheet].
///
/// If this is false, then members that interact with the [ScrollPosition],
/// such as [sizeToPixels], [size], [animateTo], and [jumpTo], must not be
/// called.
bool get isAttached => _attachedController != null && _attachedController!.hasClients;
/// Convert a sheet's pixel height to size (fractional value of parent container height).
double pixelsToSize(double pixels) {
_assertAttached();
return _attachedController!.extent.pixelsToSize(pixels);
}
/// Animates the attached sheet from its current size to the given [size], a
/// fractional value of the parent container's height.
///
/// Any active sheet animation is canceled. If the sheet's internal scrollable
/// is currently animating (e.g. responding to a user fling), that animation is
/// canceled as well.
///
/// An animation will be interrupted whenever the user attempts to scroll
/// manually, whenever another activity is started, or when the sheet hits its
/// max or min size (e.g. if you animate to 1 but the max size is .8, the
/// animation will stop playing when it reaches .8).
///
/// The duration must not be zero. To jump to a particular value without an
/// animation, use [jumpTo].
///
/// The sheet will not snap after calling [animateTo] even if [DraggableScrollableSheet.snap]
/// is true. Snapping only occurs after user drags.
///
/// When calling [animateTo] in widget tests, `await`ing the returned
/// [Future] may cause the test to hang and timeout. Instead, use
/// [WidgetTester.pumpAndSettle].
Future<void> animateTo(
double size, {
required Duration duration,
required Curve curve,
}) async {
_assertAttached();
assert(size >= 0 && size <= 1);
assert(duration != Duration.zero);
final AnimationController animationController = AnimationController.unbounded(
vsync: _attachedController!.position.context.vsync,
value: _attachedController!.extent.currentSize,
);
_animationControllers.add(animationController);
_attachedController!.position.goIdle();
// This disables any snapping until the next user interaction with the sheet.
_attachedController!.extent.hasDragged = false;
_attachedController!.extent.hasChanged = true;
_attachedController!.extent.startActivity(onCanceled: () {
// Don't stop the controller if it's already finished and may have been disposed.
if (animationController.isAnimating) {
animationController.stop();
}
});
animationController.addListener(() {
_attachedController!.extent.updateSize(
animationController.value,
_attachedController!.position.context.notificationContext!,
);
});
await animationController.animateTo(
clampDouble(size, _attachedController!.extent.minSize, _attachedController!.extent.maxSize),
duration: duration,
curve: curve,
);
}
/// Jumps the attached sheet from its current size to the given [size], a
/// fractional value of the parent container's height.
///
/// If [size] is outside of a the attached sheet's min or max child size,
/// [jumpTo] will jump the sheet to the nearest valid size instead.
///
/// Any active sheet animation is canceled. If the sheet's inner scrollable
/// is currently animating (e.g. responding to a user fling), that animation is
/// canceled as well.
///
/// The sheet will not snap after calling [jumpTo] even if [DraggableScrollableSheet.snap]
/// is true. Snapping only occurs after user drags.
void jumpTo(double size) {
_assertAttached();
assert(size >= 0 && size <= 1);
// Call start activity to interrupt any other playing activities.
_attachedController!.extent.startActivity(onCanceled: () {});
_attachedController!.position.goIdle();
_attachedController!.extent.hasDragged = false;
_attachedController!.extent.hasChanged = true;
_attachedController!.extent.updateSize(size, _attachedController!.position.context.notificationContext!);
}
/// Reset the attached sheet to its initial size (see: [DraggableScrollableSheet.initialChildSize]).
void reset() {
_assertAttached();
_attachedController!.reset();
}
void _assertAttached() {
assert(
isAttached,
'DraggableScrollableController is not attached to a sheet. A DraggableScrollableController '
'must be used in a DraggableScrollableSheet before any of its methods are called.',
);
}
void _attach(_DraggableScrollableSheetScrollController scrollController) {
assert(_attachedController == null, 'Draggable scrollable controller is already attached to a sheet.');
_attachedController = scrollController;
_attachedController!.extent._currentSize.addListener(notifyListeners);
_attachedController!.onPositionDetached = _disposeAnimationControllers;
}
void _onExtentReplaced(_DraggableSheetExtent previousExtent) {
// When the extent has been replaced, the old extent is already disposed and
// the controller will point to a new extent. We have to add our listener to
// the new extent.
_attachedController!.extent._currentSize.addListener(notifyListeners);
if (previousExtent.currentSize != _attachedController!.extent.currentSize) {
// The listener won't fire for a change in size between two extent
// objects so we have to fire it manually here.
notifyListeners();
}
}
void _detach({bool disposeExtent = false}) {
if (disposeExtent) {
_attachedController?.extent.dispose();
} else {
_attachedController?.extent._currentSize.removeListener(notifyListeners);
}
_disposeAnimationControllers();
_attachedController = null;
}
void _disposeAnimationControllers() {
for (final AnimationController animationController in _animationControllers) {
animationController.dispose();
}
_animationControllers.clear();
}
}
/// A container for a [Scrollable] that responds to drag gestures by resizing
/// the scrollable until a limit is reached, and then scrolling.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=Hgw819mL_78}
///
/// This widget can be dragged along the vertical axis between its
/// [minChildSize], which defaults to `0.25` and [maxChildSize], which defaults
/// to `1.0`. These sizes are percentages of the height of the parent container.
///
/// The widget coordinates resizing and scrolling of the widget returned by
/// builder as the user drags along the horizontal axis.
///
/// The widget will initially be displayed at its initialChildSize which
/// defaults to `0.5`, meaning half the height of its parent. Dragging will work
/// between the range of minChildSize and maxChildSize (as percentages of the
/// parent container's height) as long as the builder creates a widget which
/// uses the provided [ScrollController]. If the widget created by the
/// [ScrollableWidgetBuilder] does not use the provided [ScrollController], the
/// sheet will remain at the initialChildSize.
///
/// By default, the widget will stay at whatever size the user drags it to. To
/// make the widget snap to specific sizes whenever they lift their finger
/// during a drag, set [snap] to `true`. The sheet will snap between
/// [minChildSize] and [maxChildSize]. Use [snapSizes] to add more sizes for
/// the sheet to snap between.
///
/// The snapping effect is only applied on user drags. Programmatically
/// manipulating the sheet size via [DraggableScrollableController.animateTo] or
/// [DraggableScrollableController.jumpTo] will ignore [snap] and [snapSizes].
///
/// By default, the widget will expand its non-occupied area to fill available
/// space in the parent. If this is not desired, e.g. because the parent wants
/// to position sheet based on the space it is taking, the [expand] property
/// may be set to false.
///
/// {@tool dartpad}
///
/// This is a sample widget which shows a [ListView] that has 25 [ListTile]s.
/// It starts out as taking up half the body of the [Scaffold], and can be
/// dragged up to the full height of the scaffold or down to 25% of the height
/// of the scaffold. Upon reaching full height, the list contents will be
/// scrolled up or down, until they reach the top of the list again and the user
/// drags the sheet back down.
///
/// On desktop and web running on desktop platforms, dragging to scroll with a mouse is disabled by default
/// to align with the natural behavior found in other desktop applications.
///
/// This behavior is dictated by the [ScrollBehavior], and can be changed by adding
/// [PointerDeviceKind.mouse] to [ScrollBehavior.dragDevices].
/// For more info on this, please refer to https://docs.flutter.dev/release/breaking-changes/default-scroll-behavior-drag
///
/// Alternatively, this example illustrates how to add a drag handle for desktop applications.
///
/// ** See code in examples/api/lib/widgets/draggable_scrollable_sheet/draggable_scrollable_sheet.0.dart **
/// {@end-tool}
class DraggableScrollableSheet extends StatefulWidget {
/// Creates a widget that can be dragged and scrolled in a single gesture.
const DraggableScrollableSheet({
super.key,
this.initialChildSize = 0.5,
this.minChildSize = 0.25,
this.maxChildSize = 1.0,
this.expand = true,
this.snap = false,
this.snapSizes,
this.snapAnimationDuration,
this.controller,
this.shouldCloseOnMinExtent = true,
required this.builder,
}) : assert(minChildSize >= 0.0),
assert(maxChildSize <= 1.0),
assert(minChildSize <= initialChildSize),
assert(initialChildSize <= maxChildSize),
assert(snapAnimationDuration == null || snapAnimationDuration > Duration.zero);
/// The initial fractional value of the parent container's height to use when
/// displaying the widget.
///
/// Rebuilding the sheet with a new [initialChildSize] will only move
/// the sheet to the new value if the sheet has not yet been dragged since it
/// was first built or since the last call to [DraggableScrollableActuator.reset].
///
/// The default value is `0.5`.
final double initialChildSize;
/// The minimum fractional value of the parent container's height to use when
/// displaying the widget.
///
/// The default value is `0.25`.
final double minChildSize;
/// The maximum fractional value of the parent container's height to use when
/// displaying the widget.
///
/// The default value is `1.0`.
final double maxChildSize;
/// Whether the widget should expand to fill the available space in its parent
/// or not.
///
/// In most cases, this should be true. However, in the case of a parent
/// widget that will position this one based on its desired size (such as a
/// [Center]), this should be set to false.
///
/// The default value is true.
final bool expand;
/// Whether the widget should snap between [snapSizes] when the user lifts
/// their finger during a drag.
///
/// If the user's finger was still moving when they lifted it, the widget will
/// snap to the next snap size (see [snapSizes]) in the direction of the drag.
/// If their finger was still, the widget will snap to the nearest snap size.
///
/// Snapping is not applied when the sheet is programmatically moved by
/// calling [DraggableScrollableController.animateTo] or [DraggableScrollableController.jumpTo].
///
/// Rebuilding the sheet with snap newly enabled will immediately trigger a
/// snap unless the sheet has not yet been dragged away from
/// [initialChildSize] since first being built or since the last call to
/// [DraggableScrollableActuator.reset].
final bool snap;
/// A list of target sizes that the widget should snap to.
///
/// Snap sizes are fractional values of the parent container's height. They
/// must be listed in increasing order and be between [minChildSize] and
/// [maxChildSize].
///
/// The [minChildSize] and [maxChildSize] are implicitly included in snap
/// sizes and do not need to be specified here. For example, `snapSizes = [.5]`
/// will result in a sheet that snaps between [minChildSize], `.5`, and
/// [maxChildSize].
///
/// Any modifications to the [snapSizes] list will not take effect until the
/// `build` function containing this widget is run again.
///
/// Rebuilding with a modified or new list will trigger a snap unless the
/// sheet has not yet been dragged away from [initialChildSize] since first
/// being built or since the last call to [DraggableScrollableActuator.reset].
final List<double>? snapSizes;
/// Defines a duration for the snap animations.
///
/// If it's not set, then the animation duration is the distance to the snap
/// target divided by the velocity of the widget.
final Duration? snapAnimationDuration;
/// A controller that can be used to programmatically control this sheet.
final DraggableScrollableController? controller;
/// Whether the sheet, when dragged (or flung) to its minimum size, should
/// cause its parent sheet to close.
///
/// Set on emitted [DraggableScrollableNotification]s. It is up to parent
/// classes to properly read and handle this value.
final bool shouldCloseOnMinExtent;
/// The builder that creates a child to display in this widget, which will
/// use the provided [ScrollController] to enable dragging and scrolling
/// of the contents.
final ScrollableWidgetBuilder builder;
@override
State<DraggableScrollableSheet> createState() => _DraggableScrollableSheetState();
}
/// A [Notification] related to the extent, which is the size, and scroll
/// offset, which is the position of the child list, of the
/// [DraggableScrollableSheet].
///
/// [DraggableScrollableSheet] widgets notify their ancestors when the size of
/// the sheet changes. When the extent of the sheet changes via a drag,
/// this notification bubbles up through the tree, which means a given
/// [NotificationListener] will receive notifications for all descendant
/// [DraggableScrollableSheet] widgets. To focus on notifications from the
/// nearest [DraggableScrollableSheet] descendant, check that the [depth]
/// property of the notification is zero.
///
/// When an extent notification is received by a [NotificationListener], the
/// listener will already have completed build and layout, and it is therefore
/// too late for that widget to call [State.setState]. Any attempt to adjust the
/// build or layout based on an extent notification would result in a layout
/// that lagged one frame behind, which is a poor user experience. Extent
/// notifications are used primarily to drive animations. The [Scaffold] widget
/// listens for extent notifications and responds by driving animations for the
/// [FloatingActionButton] as the bottom sheet scrolls up.
class DraggableScrollableNotification extends Notification with ViewportNotificationMixin {
/// Creates a notification that the extent of a [DraggableScrollableSheet] has
/// changed.
///
/// All parameters are required. The [minExtent] must be >= 0. The [maxExtent]
/// must be <= 1.0. The [extent] must be between [minExtent] and [maxExtent].
DraggableScrollableNotification({
required this.extent,
required this.minExtent,
required this.maxExtent,
required this.initialExtent,
required this.context,
this.shouldCloseOnMinExtent = true,
}) : assert(0.0 <= minExtent),
assert(maxExtent <= 1.0),
assert(minExtent <= extent),
assert(minExtent <= initialExtent),
assert(extent <= maxExtent),
assert(initialExtent <= maxExtent);
/// The current value of the extent, between [minExtent] and [maxExtent].
final double extent;
/// The minimum value of [extent], which is >= 0.
final double minExtent;
/// The maximum value of [extent].
final double maxExtent;
/// The initially requested value for [extent].
final double initialExtent;
/// The build context of the widget that fired this notification.
///
/// This can be used to find the sheet's render objects to determine the size
/// of the viewport, for instance. A listener can only assume this context
/// is live when it first gets the notification.
final BuildContext context;
/// Whether the widget that fired this notification, when dragged (or flung)
/// to minExtent, should cause its parent sheet to close.
///
/// It is up to parent classes to properly read and handle this value.
final bool shouldCloseOnMinExtent;
@override
void debugFillDescription(List<String> description) {
super.debugFillDescription(description);
description.add('minExtent: $minExtent, extent: $extent, maxExtent: $maxExtent, initialExtent: $initialExtent');
}
}
/// Manages state between [_DraggableScrollableSheetState],
/// [_DraggableScrollableSheetScrollController], and
/// [_DraggableScrollableSheetScrollPosition].
///
/// The State knows the pixels available along the axis the widget wants to
/// scroll, but expects to get a fraction of those pixels to render the sheet.
///
/// The ScrollPosition knows the number of pixels a user wants to move the sheet.
///
/// The [currentSize] will never be null.
/// The [availablePixels] will never be null, but may be `double.infinity`.
class _DraggableSheetExtent {
_DraggableSheetExtent({
required this.minSize,
required this.maxSize,
required this.snap,
required this.snapSizes,
required this.initialSize,
this.snapAnimationDuration,
ValueNotifier<double>? currentSize,
bool? hasDragged,
bool? hasChanged,
this.shouldCloseOnMinExtent = true,
}) : assert(minSize >= 0),
assert(maxSize <= 1),
assert(minSize <= initialSize),
assert(initialSize <= maxSize),
_currentSize = currentSize ?? ValueNotifier<double>(initialSize),
availablePixels = double.infinity,
hasDragged = hasDragged ?? false,
hasChanged = hasChanged ?? false {
// TODO(polina-c): stop duplicating code across disposables
// https://github.com/flutter/flutter/issues/137435
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectCreated(
library: 'package:flutter/widgets.dart',
className: '$_DraggableSheetExtent',
object: this,
);
}
}
VoidCallback? _cancelActivity;
final double minSize;
final double maxSize;
final bool snap;
final List<double> snapSizes;
final Duration? snapAnimationDuration;
final double initialSize;
final bool shouldCloseOnMinExtent;
final ValueNotifier<double> _currentSize;
double availablePixels;
// Used to disable snapping until the user has dragged on the sheet.
bool hasDragged;
// Used to determine if the sheet should move to a new initial size when it
// changes.
// We need both `hasChanged` and `hasDragged` to achieve the following
// behavior:
// 1. The sheet should only snap following user drags (as opposed to
// programmatic sheet changes). See docs for `animateTo` and `jumpTo`.
// 2. The sheet should move to a new initial child size on rebuild iff the
// sheet has not changed, either by drag or programmatic control. See
// docs for `initialChildSize`.
bool hasChanged;
bool get isAtMin => minSize >= _currentSize.value;
bool get isAtMax => maxSize <= _currentSize.value;
double get currentSize => _currentSize.value;
double get currentPixels => sizeToPixels(_currentSize.value);
List<double> get pixelSnapSizes => snapSizes.map(sizeToPixels).toList();
/// Start an activity that affects the sheet and register a cancel call back
/// that will be called if another activity starts.
///
/// The `onCanceled` callback will get called even if the subsequent activity
/// started after this one finished, so `onCanceled` must be safe to call at
/// any time.
void startActivity({required VoidCallback onCanceled}) {
_cancelActivity?.call();
_cancelActivity = onCanceled;
}
/// The scroll position gets inputs in terms of pixels, but the size is
/// expected to be expressed as a number between 0..1.
///
/// This should only be called to respond to a user drag. To update the
/// size in response to a programmatic call, use [updateSize] directly.
void addPixelDelta(double delta, BuildContext context) {
// Stop any playing sheet animations.
_cancelActivity?.call();
_cancelActivity = null;
// The user has interacted with the sheet, set `hasDragged` to true so that
// we'll snap if applicable.
hasDragged = true;
hasChanged = true;
if (availablePixels == 0) {
return;
}
updateSize(currentSize + pixelsToSize(delta), context);
}
/// Set the size to the new value. [newSize] should be a number between
/// [minSize] and [maxSize].
///
/// This can be triggered by a programmatic (e.g. controller triggered) change
/// or a user drag.
void updateSize(double newSize, BuildContext context) {
final double clampedSize = clampDouble(newSize, minSize, maxSize);
if (_currentSize.value == clampedSize) {
return;
}
_currentSize.value = clampedSize;
DraggableScrollableNotification(
minExtent: minSize,
maxExtent: maxSize,
extent: currentSize,
initialExtent: initialSize,
context: context,
shouldCloseOnMinExtent: shouldCloseOnMinExtent,
).dispatch(context);
}
double pixelsToSize(double pixels) {
return pixels / availablePixels * maxSize;
}
double sizeToPixels(double size) {
return size / maxSize * availablePixels;
}
void dispose() {
if (kFlutterMemoryAllocationsEnabled) {
FlutterMemoryAllocations.instance.dispatchObjectDisposed(object: this);
}
_currentSize.dispose();
}
_DraggableSheetExtent copyWith({
required double minSize,
required double maxSize,
required bool snap,
required List<double> snapSizes,
required double initialSize,
Duration? snapAnimationDuration,
bool shouldCloseOnMinExtent = true,
}) {
return _DraggableSheetExtent(
minSize: minSize,
maxSize: maxSize,
snap: snap,
snapSizes: snapSizes,
snapAnimationDuration: snapAnimationDuration,
initialSize: initialSize,
// Set the current size to the possibly updated initial size if the sheet
// hasn't changed yet.
currentSize: ValueNotifier<double>(hasChanged
? clampDouble(_currentSize.value, minSize, maxSize)
: initialSize),
hasDragged: hasDragged,
hasChanged: hasChanged,
shouldCloseOnMinExtent: shouldCloseOnMinExtent,
);
}
}
class _DraggableScrollableSheetState extends State<DraggableScrollableSheet> {
late _DraggableScrollableSheetScrollController _scrollController;
late _DraggableSheetExtent _extent;
@override
void initState() {
super.initState();
_extent = _DraggableSheetExtent(
minSize: widget.minChildSize,
maxSize: widget.maxChildSize,
snap: widget.snap,
snapSizes: _impliedSnapSizes(),
snapAnimationDuration: widget.snapAnimationDuration,
initialSize: widget.initialChildSize,
shouldCloseOnMinExtent: widget.shouldCloseOnMinExtent,
);
_scrollController = _DraggableScrollableSheetScrollController(extent: _extent);
widget.controller?._attach(_scrollController);
}
List<double> _impliedSnapSizes() {
for (int index = 0; index < (widget.snapSizes?.length ?? 0); index += 1) {
final double snapSize = widget.snapSizes![index];
assert(snapSize >= widget.minChildSize && snapSize <= widget.maxChildSize,
'${_snapSizeErrorMessage(index)}\nSnap sizes must be between `minChildSize` and `maxChildSize`. ');
assert(index == 0 || snapSize > widget.snapSizes![index - 1],
'${_snapSizeErrorMessage(index)}\nSnap sizes must be in ascending order. ');
}
// Ensure the snap sizes start and end with the min and max child sizes.
if (widget.snapSizes == null || widget.snapSizes!.isEmpty) {
return <double>[
widget.minChildSize,
widget.maxChildSize,
];
}
return <double>[
if (widget.snapSizes!.first != widget.minChildSize) widget.minChildSize,
...widget.snapSizes!,
if (widget.snapSizes!.last != widget.maxChildSize) widget.maxChildSize,
];
}
@override
void didUpdateWidget(covariant DraggableScrollableSheet oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.controller != oldWidget.controller) {
oldWidget.controller?._detach();
widget.controller?._attach(_scrollController);
}
_replaceExtent(oldWidget);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (_InheritedResetNotifier.shouldReset(context)) {
_scrollController.reset();
}
}
@override
Widget build(BuildContext context) {
return ValueListenableBuilder<double>(
valueListenable: _extent._currentSize,
builder: (BuildContext context, double currentSize, Widget? child) => LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
_extent.availablePixels = widget.maxChildSize * constraints.biggest.height;
final Widget sheet = FractionallySizedBox(
heightFactor: currentSize,
alignment: Alignment.bottomCenter,
child: child,
);
return widget.expand ? SizedBox.expand(child: sheet) : sheet;
},
),
child: widget.builder(context, _scrollController),
);
}
@override
void dispose() {
if (widget.controller == null) {
_extent.dispose();
} else {
widget.controller!._detach(disposeExtent: true);
}
_scrollController.dispose();
super.dispose();
}
void _replaceExtent(covariant DraggableScrollableSheet oldWidget) {
final _DraggableSheetExtent previousExtent = _extent;
_extent = previousExtent.copyWith(
minSize: widget.minChildSize,
maxSize: widget.maxChildSize,
snap: widget.snap,
snapSizes: _impliedSnapSizes(),
snapAnimationDuration: widget.snapAnimationDuration,
initialSize: widget.initialChildSize,
);
// Modify the existing scroll controller instead of replacing it so that
// developers listening to the controller do not have to rebuild their listeners.
_scrollController.extent = _extent;
// If an external facing controller was provided, let it know that the
// extent has been replaced.
widget.controller?._onExtentReplaced(previousExtent);
previousExtent.dispose();
if (widget.snap
&& (widget.snap != oldWidget.snap || widget.snapSizes != oldWidget.snapSizes)
&& _scrollController.hasClients
) {
// Trigger a snap in case snap or snapSizes has changed and there is a
// scroll position currently attached. We put this in a post frame
// callback so that `build` can update `_extent.availablePixels` before
// this runs-we can't use the previous extent's available pixels as it may
// have changed when the widget was updated.
WidgetsBinding.instance.addPostFrameCallback((Duration timeStamp) {
for (int index = 0; index < _scrollController.positions.length; index++) {
final _DraggableScrollableSheetScrollPosition position =
_scrollController.positions.elementAt(index) as _DraggableScrollableSheetScrollPosition;
position.goBallistic(0);
}
}, debugLabel: 'DraggableScrollableSheet.snap');
}
}
String _snapSizeErrorMessage(int invalidIndex) {
final List<String> snapSizesWithIndicator = widget.snapSizes!.asMap().keys.map(
(int index) {
final String snapSizeString = widget.snapSizes![index].toString();
if (index == invalidIndex) {
return '>>> $snapSizeString <<<';
}
return snapSizeString;
},
).toList();
return "Invalid snapSize '${widget.snapSizes![invalidIndex]}' at index $invalidIndex of:\n"
' $snapSizesWithIndicator';
}
}
/// A [ScrollController] suitable for use in a [ScrollableWidgetBuilder] created
/// by a [DraggableScrollableSheet].
///
/// If a [DraggableScrollableSheet] contains content that is exceeds the height
/// of its container, this controller will allow the sheet to both be dragged to
/// fill the container and then scroll the child content.
///
/// See also:
///
/// * [_DraggableScrollableSheetScrollPosition], which manages the positioning logic for
/// this controller.
/// * [PrimaryScrollController], which can be used to establish a
/// [_DraggableScrollableSheetScrollController] as the primary controller for
/// descendants.
class _DraggableScrollableSheetScrollController extends ScrollController {
_DraggableScrollableSheetScrollController({
required this.extent,
});
_DraggableSheetExtent extent;
VoidCallback? onPositionDetached;
@override
_DraggableScrollableSheetScrollPosition createScrollPosition(
ScrollPhysics physics,
ScrollContext context,
ScrollPosition? oldPosition,
) {
return _DraggableScrollableSheetScrollPosition(
physics: physics.applyTo(const AlwaysScrollableScrollPhysics()),
context: context,
oldPosition: oldPosition,
getExtent: () => extent,
);
}
@override
void debugFillDescription(List<String> description) {
super.debugFillDescription(description);
description.add('extent: $extent');
}
@override
_DraggableScrollableSheetScrollPosition get position =>
super.position as _DraggableScrollableSheetScrollPosition;
void reset() {
extent._cancelActivity?.call();
extent.hasDragged = false;
extent.hasChanged = false;
// jumpTo can result in trying to replace semantics during build.
// Just animate really fast.
// Avoid doing it at all if the offset is already 0.0.
if (offset != 0.0) {
animateTo(
0.0,
duration: const Duration(milliseconds: 1),
curve: Curves.linear,
);
}
extent.updateSize(extent.initialSize, position.context.notificationContext!);
}
@override
void detach(ScrollPosition position) {
onPositionDetached?.call();
super.detach(position);
}
}
/// A scroll position that manages scroll activities for
/// [_DraggableScrollableSheetScrollController].
///
/// This class is a concrete subclass of [ScrollPosition] logic that handles a
/// single [ScrollContext], such as a [Scrollable]. An instance of this class
/// manages [ScrollActivity] instances, which changes the
/// [_DraggableSheetExtent.currentSize] or visible content offset in the
/// [Scrollable]'s [Viewport]
///
/// See also:
///
/// * [_DraggableScrollableSheetScrollController], which uses this as its [ScrollPosition].
class _DraggableScrollableSheetScrollPosition extends ScrollPositionWithSingleContext {
_DraggableScrollableSheetScrollPosition({
required super.physics,
required super.context,
super.oldPosition,
required this.getExtent,
});
VoidCallback? _dragCancelCallback;
final _DraggableSheetExtent Function() getExtent;
final Set<AnimationController> _ballisticControllers = <AnimationController>{};
bool get listShouldScroll => pixels > 0.0;
_DraggableSheetExtent get extent => getExtent();
@override
void absorb(ScrollPosition other) {
super.absorb(other);
assert(_dragCancelCallback == null);
if (other is! _DraggableScrollableSheetScrollPosition) {
return;
}
if (other._dragCancelCallback != null) {
_dragCancelCallback = other._dragCancelCallback;
other._dragCancelCallback = null;
}
}
@override
void beginActivity(ScrollActivity? newActivity) {
// Cancel the running ballistic simulations
for (final AnimationController ballisticController in _ballisticControllers) {
ballisticController.stop();
}
super.beginActivity(newActivity);
}
@override
void applyUserOffset(double delta) {
if (!listShouldScroll &&
(!(extent.isAtMin || extent.isAtMax) ||
(extent.isAtMin && delta < 0) ||
(extent.isAtMax && delta > 0))) {
extent.addPixelDelta(-delta, context.notificationContext!);
} else {
super.applyUserOffset(delta);
}
}
bool get _isAtSnapSize {
return extent.snapSizes.any(
(double snapSize) {
return (extent.currentSize - snapSize).abs() <= extent.pixelsToSize(physics.toleranceFor(this).distance);
},
);
}
bool get _shouldSnap => extent.snap && extent.hasDragged && !_isAtSnapSize;
@override
void dispose() {
for (final AnimationController ballisticController in _ballisticControllers) {
ballisticController.dispose();
}
_ballisticControllers.clear();
super.dispose();
}
@override
void goBallistic(double velocity) {
if ((velocity == 0.0 && !_shouldSnap) ||
(velocity < 0.0 && listShouldScroll) ||
(velocity > 0.0 && extent.isAtMax)) {
super.goBallistic(velocity);
return;
}
// Scrollable expects that we will dispose of its current _dragCancelCallback
_dragCancelCallback?.call();
_dragCancelCallback = null;
late final Simulation simulation;
if (extent.snap) {
// Snap is enabled, simulate snapping instead of clamping scroll.
simulation = _SnappingSimulation(
position: extent.currentPixels,
initialVelocity: velocity,
pixelSnapSize: extent.pixelSnapSizes,
snapAnimationDuration: extent.snapAnimationDuration,
tolerance: physics.toleranceFor(this),
);
} else {
// The iOS bouncing simulation just isn't right here - once we delegate
// the ballistic back to the ScrollView, it will use the right simulation.
simulation = ClampingScrollSimulation(
// Run the simulation in terms of pixels, not extent.
position: extent.currentPixels,
velocity: velocity,
tolerance: physics.toleranceFor(this),
);
}
final AnimationController ballisticController = AnimationController.unbounded(
debugLabel: objectRuntimeType(this, '_DraggableScrollableSheetPosition'),
vsync: context.vsync,
);
_ballisticControllers.add(ballisticController);
double lastPosition = extent.currentPixels;
void tick() {
final double delta = ballisticController.value - lastPosition;
lastPosition = ballisticController.value;
extent.addPixelDelta(delta, context.notificationContext!);
if ((velocity > 0 && extent.isAtMax) || (velocity < 0 && extent.isAtMin)) {
// Make sure we pass along enough velocity to keep scrolling - otherwise
// we just "bounce" off the top making it look like the list doesn't
// have more to scroll.
velocity = ballisticController.velocity + (physics.toleranceFor(this).velocity * ballisticController.velocity.sign);
super.goBallistic(velocity);
ballisticController.stop();
} else if (ballisticController.isCompleted) {
super.goBallistic(0);
}
}
ballisticController
..addListener(tick)
..animateWith(simulation).whenCompleteOrCancel(
() {
if (_ballisticControllers.contains(ballisticController)) {
_ballisticControllers.remove(ballisticController);
ballisticController.dispose();
}
},
);
}
@override
Drag drag(DragStartDetails details, VoidCallback dragCancelCallback) {
// Save this so we can call it later if we have to [goBallistic] on our own.
_dragCancelCallback = dragCancelCallback;
return super.drag(details, dragCancelCallback);
}
}
/// A widget that can notify a descendent [DraggableScrollableSheet] that it
/// should reset its position to the initial state.
///
/// The [Scaffold] uses this widget to notify a persistent bottom sheet that
/// the user has tapped back if the sheet has started to cover more of the body
/// than when at its initial position. This is important for users of assistive
/// technology, where dragging may be difficult to communicate.
///
/// This is just a wrapper on top of [DraggableScrollableController]. It is
/// primarily useful for controlling a sheet in a part of the widget tree that
/// the current code does not control (e.g. library code trying to affect a sheet
/// in library users' code). Generally, it's easier to control the sheet
/// directly by creating a controller and passing the controller to the sheet in
/// its constructor (see [DraggableScrollableSheet.controller]).
class DraggableScrollableActuator extends StatefulWidget {
/// Creates a widget that can notify descendent [DraggableScrollableSheet]s
/// to reset to their initial position.
///
/// The [child] parameter is required.
const DraggableScrollableActuator({
super.key,
required this.child,
});
/// This child's [DraggableScrollableSheet] descendant will be reset when the
/// [reset] method is applied to a context that includes it.
final Widget child;
/// Notifies any descendant [DraggableScrollableSheet] that it should reset
/// to its initial position.
///
/// Returns `true` if a [DraggableScrollableActuator] is available and
/// some [DraggableScrollableSheet] is listening for updates, `false`
/// otherwise.
static bool reset(BuildContext context) {
final _InheritedResetNotifier? notifier = context.dependOnInheritedWidgetOfExactType<_InheritedResetNotifier>();
return notifier?._sendReset() ?? false;
}
@override
State<DraggableScrollableActuator> createState() => _DraggableScrollableActuatorState();
}
class _DraggableScrollableActuatorState extends State<DraggableScrollableActuator> {
final _ResetNotifier _notifier = _ResetNotifier();
@override
Widget build(BuildContext context) {
return _InheritedResetNotifier(notifier: _notifier, child: widget.child);
}
@override
void dispose() {
_notifier.dispose();
super.dispose();
}
}
/// A [ChangeNotifier] to use with [InheritedResetNotifier] to notify
/// descendants that they should reset to initial state.
class _ResetNotifier extends ChangeNotifier {
_ResetNotifier() {
if (kFlutterMemoryAllocationsEnabled) {
ChangeNotifier.maybeDispatchObjectCreation(this);
}
}
/// Whether someone called [sendReset] or not.
///
/// This flag should be reset after checking it.
bool _wasCalled = false;
/// Fires a reset notification to descendants.
///
/// Returns false if there are no listeners.
bool sendReset() {
if (!hasListeners) {
return false;
}
_wasCalled = true;
notifyListeners();
return true;
}
}
class _InheritedResetNotifier extends InheritedNotifier<_ResetNotifier> {
/// Creates an [InheritedNotifier] that the [DraggableScrollableSheet] will
/// listen to for an indication that it should reset itself back to [DraggableScrollableSheet.initialChildSize].
const _InheritedResetNotifier({
required super.child,
required _ResetNotifier super.notifier,
});
bool _sendReset() => notifier!.sendReset();
/// Specifies whether the [DraggableScrollableSheet] should reset to its
/// initial position.
///
/// Returns true if the notifier requested a reset, false otherwise.
static bool shouldReset(BuildContext context) {
final InheritedWidget? widget = context.dependOnInheritedWidgetOfExactType<_InheritedResetNotifier>();
if (widget == null) {
return false;
}
assert(widget is _InheritedResetNotifier);
final _InheritedResetNotifier inheritedNotifier = widget as _InheritedResetNotifier;
final bool wasCalled = inheritedNotifier.notifier!._wasCalled;
inheritedNotifier.notifier!._wasCalled = false;
return wasCalled;
}
}
class _SnappingSimulation extends Simulation {
_SnappingSimulation({
required this.position,
required double initialVelocity,
required List<double> pixelSnapSize,
Duration? snapAnimationDuration,
super.tolerance,
}) {
_pixelSnapSize = _getSnapSize(initialVelocity, pixelSnapSize);
if (snapAnimationDuration != null && snapAnimationDuration.inMilliseconds > 0) {
velocity = (_pixelSnapSize - position) * 1000 / snapAnimationDuration.inMilliseconds;
}
// Check the direction of the target instead of the sign of the velocity because
// we may snap in the opposite direction of velocity if velocity is very low.
else if (_pixelSnapSize < position) {
velocity = math.min(-minimumSpeed, initialVelocity);
} else {
velocity = math.max(minimumSpeed, initialVelocity);
}
}
final double position;
late final double velocity;
// A minimum speed to snap at. Used to ensure that the snapping animation
// does not play too slowly.
static const double minimumSpeed = 1600.0;
late final double _pixelSnapSize;
@override
double dx(double time) {
if (isDone(time)) {
return 0;
}
return velocity;
}
@override
bool isDone(double time) {
return x(time) == _pixelSnapSize;
}
@override
double x(double time) {
final double newPosition = position + velocity * time;
if ((velocity >= 0 && newPosition > _pixelSnapSize) ||
(velocity < 0 && newPosition < _pixelSnapSize)) {
// We're passed the snap size, return it instead.
return _pixelSnapSize;
}
return newPosition;
}
// Find the two closest snap sizes to the position. If the velocity is
// non-zero, select the size in the velocity's direction. Otherwise,
// the nearest snap size.
double _getSnapSize(double initialVelocity, List<double> pixelSnapSizes) {
final int indexOfNextSize = pixelSnapSizes
.indexWhere((double size) => size >= position);
if (indexOfNextSize == 0) {
return pixelSnapSizes.first;
}
final double nextSize = pixelSnapSizes[indexOfNextSize];
final double previousSize = pixelSnapSizes[indexOfNextSize - 1];
if (initialVelocity.abs() <= tolerance.velocity) {
// If velocity is zero, snap to the nearest snap size with the minimum velocity.
if (position - previousSize < nextSize - position) {
return previousSize;
} else {
return nextSize;
}
}
// Snap forward or backward depending on current velocity.
if (initialVelocity < 0.0) {
return pixelSnapSizes[indexOfNextSize - 1];
}
return pixelSnapSizes[indexOfNextSize];
}
}
| flutter/packages/flutter/lib/src/widgets/draggable_scrollable_sheet.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/draggable_scrollable_sheet.dart",
"repo_id": "flutter",
"token_count": 14217
} | 643 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:io' show File;
import 'package:flutter/foundation.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/semantics.dart';
import 'basic.dart';
import 'binding.dart';
import 'disposable_build_context.dart';
import 'framework.dart';
import 'localizations.dart';
import 'media_query.dart';
import 'placeholder.dart';
import 'scroll_aware_image_provider.dart';
import 'text.dart';
import 'ticker_provider.dart';
export 'package:flutter/painting.dart' show
AssetImage,
ExactAssetImage,
FileImage,
FilterQuality,
ImageConfiguration,
ImageInfo,
ImageProvider,
ImageStream,
MemoryImage,
NetworkImage;
// Examples can assume:
// late Widget image;
// late ImageProvider _image;
/// Creates an [ImageConfiguration] based on the given [BuildContext] (and
/// optionally size).
///
/// This is the object that must be passed to [BoxPainter.paint] and to
/// [ImageProvider.resolve].
///
/// If this is not called from a build method, then it should be reinvoked
/// whenever the dependencies change, e.g. by calling it from
/// [State.didChangeDependencies], so that any changes in the environment are
/// picked up (e.g. if the device pixel ratio changes).
///
/// See also:
///
/// * [ImageProvider], which has an example showing how this might be used.
ImageConfiguration createLocalImageConfiguration(BuildContext context, { Size? size }) {
return ImageConfiguration(
bundle: DefaultAssetBundle.of(context),
devicePixelRatio: MediaQuery.maybeDevicePixelRatioOf(context) ?? 1.0,
locale: Localizations.maybeLocaleOf(context),
textDirection: Directionality.maybeOf(context),
size: size,
platform: defaultTargetPlatform,
);
}
/// Prefetches an image into the image cache.
///
/// Returns a [Future] that will complete when the first image yielded by the
/// [ImageProvider] is available or failed to load.
///
/// If the image is later used by an [Image] or [BoxDecoration] or [FadeInImage],
/// it will probably be loaded faster. The consumer of the image does not need
/// to use the same [ImageProvider] instance. The [ImageCache] will find the image
/// as long as both images share the same key, and the image is held by the
/// cache.
///
/// The cache may refuse to hold the image if it is disabled, the image is too
/// large, or some other criteria implemented by a custom [ImageCache]
/// implementation.
///
/// The [ImageCache] holds a reference to all images passed to
/// [ImageCache.putIfAbsent] as long as their [ImageStreamCompleter] has at
/// least one listener. This method will wait until the end of the frame after
/// its future completes before releasing its own listener. This gives callers a
/// chance to listen to the stream if necessary. A caller can determine if the
/// image ended up in the cache by calling [ImageProvider.obtainCacheStatus]. If
/// it is only held as [ImageCacheStatus.live], and the caller wishes to keep
/// the resolved image in memory, the caller should immediately call
/// `provider.resolve` and add a listener to the returned [ImageStream]. The
/// image will remain pinned in memory at least until the caller removes its
/// listener from the stream, even if it would not otherwise fit into the cache.
///
/// Callers should be cautious about pinning large images or a large number of
/// images in memory, as this can result in running out of memory and being
/// killed by the operating system. The lower the available physical memory, the
/// more susceptible callers will be to running into OOM issues. These issues
/// manifest as immediate process death, sometimes with no other error messages.
///
/// The [BuildContext] and [Size] are used to select an image configuration
/// (see [createLocalImageConfiguration]).
///
/// The returned future will not complete with error, even if precaching
/// failed. The `onError` argument can be used to manually handle errors while
/// pre-caching.
///
/// See also:
///
/// * [ImageCache], which holds images that may be reused.
Future<void> precacheImage(
ImageProvider provider,
BuildContext context, {
Size? size,
ImageErrorListener? onError,
}) {
final ImageConfiguration config = createLocalImageConfiguration(context, size: size);
final Completer<void> completer = Completer<void>();
final ImageStream stream = provider.resolve(config);
ImageStreamListener? listener;
listener = ImageStreamListener(
(ImageInfo? image, bool sync) {
if (!completer.isCompleted) {
completer.complete();
}
// Give callers until at least the end of the frame to subscribe to the
// image stream.
// See ImageCache._liveImages
SchedulerBinding.instance.addPostFrameCallback((Duration timeStamp) {
image?.dispose();
stream.removeListener(listener!);
}, debugLabel: 'precacheImage.removeListener');
},
onError: (Object exception, StackTrace? stackTrace) {
if (!completer.isCompleted) {
completer.complete();
}
stream.removeListener(listener!);
if (onError != null) {
onError(exception, stackTrace);
} else {
FlutterError.reportError(FlutterErrorDetails(
context: ErrorDescription('image failed to precache'),
library: 'image resource service',
exception: exception,
stack: stackTrace,
silent: true,
));
}
},
);
stream.addListener(listener);
return completer.future;
}
/// Signature used by [Image.frameBuilder] to control the widget that will be
/// used when an [Image] is built.
///
/// The `child` argument contains the default image widget and is guaranteed to
/// be non-null. Typically, this builder will wrap the `child` widget in some
/// way and return the wrapped widget. If this builder returns `child` directly,
/// it will yield the same result as if [Image.frameBuilder] was null.
///
/// The `frame` argument specifies the index of the current image frame being
/// rendered. It will be null before the first image frame is ready, and zero
/// for the first image frame. For single-frame images, it will never be greater
/// than zero. For multi-frame images (such as animated GIFs), it will increase
/// by one every time a new image frame is shown (including when the image
/// animates in a loop).
///
/// The `wasSynchronouslyLoaded` argument specifies whether the image was
/// available synchronously (on the same
/// [rendering pipeline frame](rendering/RendererBinding/drawFrame.html) as the
/// `Image` widget itself was created) and thus able to be painted immediately.
/// If this is false, then there was one or more rendering pipeline frames where
/// the image wasn't yet available to be painted. For multi-frame images (such
/// as animated GIFs), the value of this argument will be the same for all image
/// frames. In other words, if the first image frame was available immediately,
/// then this argument will be true for all image frames.
///
/// This builder must not return null.
///
/// See also:
///
/// * [Image.frameBuilder], which makes use of this signature in the [Image]
/// widget.
typedef ImageFrameBuilder = Widget Function(
BuildContext context,
Widget child,
int? frame,
bool wasSynchronouslyLoaded,
);
/// Signature used by [Image.loadingBuilder] to build a representation of the
/// image's loading progress.
///
/// This is useful for images that are incrementally loaded (e.g. over a local
/// file system or a network), and the application wishes to give the user an
/// indication of when the image will be displayed.
///
/// The `child` argument contains the default image widget and is guaranteed to
/// be non-null. Typically, this builder will wrap the `child` widget in some
/// way and return the wrapped widget. If this builder returns `child` directly,
/// it will yield the same result as if [Image.loadingBuilder] was null.
///
/// The `loadingProgress` argument contains the current progress towards loading
/// the image. This argument will be non-null while the image is loading, but it
/// will be null in the following cases:
///
/// * When the widget is first rendered before any bytes have been loaded.
/// * When an image has been fully loaded and is available to be painted.
///
/// If callers are implementing custom [ImageProvider] and [ImageStream]
/// instances (which is very rare), it's possible to produce image streams that
/// continue to fire image chunk events after an image frame has been loaded.
/// In such cases, the `child` parameter will represent the current
/// fully-loaded image frame.
///
/// This builder must not return null.
///
/// See also:
///
/// * [Image.loadingBuilder], which makes use of this signature in the [Image]
/// widget.
/// * [ImageChunkListener], a lower-level signature for listening to raw
/// [ImageChunkEvent]s.
typedef ImageLoadingBuilder = Widget Function(
BuildContext context,
Widget child,
ImageChunkEvent? loadingProgress,
);
/// Signature used by [Image.errorBuilder] to create a replacement widget to
/// render instead of the image.
typedef ImageErrorWidgetBuilder = Widget Function(
BuildContext context,
Object error,
StackTrace? stackTrace,
);
/// A widget that displays an image.
///
/// {@youtube 560 315 https://www.youtube.com/watch?v=7oIAs-0G4mw}
///
/// Several constructors are provided for the various ways that an image can be
/// specified:
///
/// * [Image.new], for obtaining an image from an [ImageProvider].
/// * [Image.asset], for obtaining an image from an [AssetBundle]
/// using a key.
/// * [Image.network], for obtaining an image from a URL.
/// * [Image.file], for obtaining an image from a [File].
/// * [Image.memory], for obtaining an image from a [Uint8List].
///
/// The following image formats are supported: {@macro dart.ui.imageFormats}
///
/// To automatically perform pixel-density-aware asset resolution, specify the
/// image using an [AssetImage] and make sure that a [MaterialApp], [WidgetsApp],
/// or [MediaQuery] widget exists above the [Image] widget in the widget tree.
///
/// The image is painted using [paintImage], which describes the meanings of the
/// various fields on this class in more detail.
///
/// {@tool snippet}
/// The default constructor can be used with any [ImageProvider], such as a
/// [NetworkImage], to display an image from the internet.
///
/// 
///
/// ```dart
/// const Image(
/// image: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl.jpg'),
/// )
/// ```
/// {@end-tool}
///
/// {@tool snippet}
/// The [Image] Widget also provides several constructors to display different
/// types of images for convenience. In this example, use the [Image.network]
/// constructor to display an image from the internet.
///
/// 
///
/// ```dart
/// Image.network('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg')
/// ```
/// {@end-tool}
///
/// ## Memory usage
///
/// The image is stored in memory in uncompressed form (so that it can be
/// rendered). Large images will use a lot of memory: a 4K image (3840×2160)
/// will use over 30MB of RAM (assuming 32 bits per pixel).
///
/// This problem is exacerbated by the images being cached in the [ImageCache],
/// so large images can use memory for even longer than they are displayed.
///
/// The [Image.asset], [Image.network], [Image.file], and [Image.memory]
/// constructors allow a custom decode size to be specified through `cacheWidth`
/// and `cacheHeight` parameters. The engine will then decode and store the
/// image at the specified size, instead of the image's natural size.
///
/// This can significantly reduce the memory usage. For example, a 4K image that
/// will be rendered at only 384×216 pixels (one-tenth the horizontal and
/// vertical dimensions) would only use 330KB if those dimensions are specified
/// using the `cacheWidth` and `cacheHeight` parameters, a 100-fold reduction in
/// memory usage.
///
/// ### Web considerations
///
/// In the case where a network image is used on the Web platform, the
/// `cacheWidth` and `cacheHeight` parameters are only supported when the
/// application is running with the CanvasKit renderer. When the application is
/// using the HTML renderer, the web engine delegates image decoding of network
/// images to the Web, which does not support custom decode sizes.
///
/// ## Custom image providers
///
/// {@tool dartpad}
/// In this example, a variant of [NetworkImage] is created that passes all the
/// [ImageConfiguration] information (locale, platform, size, etc) to the server
/// using query arguments in the image URL.
///
/// ** See code in examples/api/lib/painting/image_provider/image_provider.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [Icon], which shows an image from a font.
/// * [Ink.image], which is the preferred way to show an image in a
/// material application (especially if the image is in a [Material] and will
/// have an [InkWell] on top of it).
/// * [Image](dart-ui/Image-class.html), the class in the [dart:ui] library.
/// * Cookbook: [Display images from the internet](https://flutter.dev/docs/cookbook/images/network-image)
/// * Cookbook: [Work with cached images](https://flutter.dev/docs/cookbook/images/cached-images)
/// * Cookbook: [Fade in images with a placeholder](https://flutter.dev/docs/cookbook/images/fading-in-images)
class Image extends StatefulWidget {
/// Creates a widget that displays an image.
///
/// To show an image from the network or from an asset bundle, consider using
/// [Image.network] and [Image.asset] respectively.
///
/// Either the [width] and [height] arguments should be specified, or the
/// widget should be placed in a context that sets tight layout constraints.
/// Otherwise, the image dimensions will change as the image is loaded, which
/// will result in ugly layout changes.
///
/// {@template flutter.widgets.image.filterQualityParameter}
/// Use [filterQuality] to specify the rendering quality of the image.
/// {@endtemplate}
///
/// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
const Image({
super.key,
required this.image,
this.frameBuilder,
this.loadingBuilder,
this.errorBuilder,
this.semanticLabel,
this.excludeFromSemantics = false,
this.width,
this.height,
this.color,
this.opacity,
this.colorBlendMode,
this.fit,
this.alignment = Alignment.center,
this.repeat = ImageRepeat.noRepeat,
this.centerSlice,
this.matchTextDirection = false,
this.gaplessPlayback = false,
this.isAntiAlias = false,
this.filterQuality = FilterQuality.low,
});
/// Creates a widget that displays an [ImageStream] obtained from the network.
///
/// Either the [width] and [height] arguments should be specified, or the
/// widget should be placed in a context that sets tight layout constraints.
/// Otherwise, the image dimensions will change as the image is loaded, which
/// will result in ugly layout changes.
///
/// All network images are cached regardless of HTTP headers.
///
/// An optional [headers] argument can be used to send custom HTTP headers
/// with the image request.
///
/// {@macro flutter.widgets.image.filterQualityParameter}
///
/// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
///
/// If `cacheWidth` or `cacheHeight` are provided, they indicate to the
/// engine that the image should be decoded at the specified size. The image
/// will be rendered to the constraints of the layout or [width] and [height]
/// regardless of these parameters. These parameters are primarily intended
/// to reduce the memory usage of [ImageCache].
///
/// In the case where the network image is on the Web platform, the [cacheWidth]
/// and [cacheHeight] parameters are ignored as the web engine delegates
/// image decoding to the web which does not support custom decode sizes.
Image.network(
String src, {
super.key,
double scale = 1.0,
this.frameBuilder,
this.loadingBuilder,
this.errorBuilder,
this.semanticLabel,
this.excludeFromSemantics = false,
this.width,
this.height,
this.color,
this.opacity,
this.colorBlendMode,
this.fit,
this.alignment = Alignment.center,
this.repeat = ImageRepeat.noRepeat,
this.centerSlice,
this.matchTextDirection = false,
this.gaplessPlayback = false,
this.filterQuality = FilterQuality.low,
this.isAntiAlias = false,
Map<String, String>? headers,
int? cacheWidth,
int? cacheHeight,
}) : image = ResizeImage.resizeIfNeeded(cacheWidth, cacheHeight, NetworkImage(src, scale: scale, headers: headers)),
assert(cacheWidth == null || cacheWidth > 0),
assert(cacheHeight == null || cacheHeight > 0);
/// Creates a widget that displays an [ImageStream] obtained from a [File].
///
/// Either the [width] and [height] arguments should be specified, or the
/// widget should be placed in a context that sets tight layout constraints.
/// Otherwise, the image dimensions will change as the image is loaded, which
/// will result in ugly layout changes.
///
/// On Android, this may require the
/// `android.permission.READ_EXTERNAL_STORAGE` permission.
///
/// {@macro flutter.widgets.image.filterQualityParameter}
///
/// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
///
/// If `cacheWidth` or `cacheHeight` are provided, they indicate to the
/// engine that the image must be decoded at the specified size. The image
/// will be rendered to the constraints of the layout or [width] and [height]
/// regardless of these parameters. These parameters are primarily intended
/// to reduce the memory usage of [ImageCache].
///
/// Loading an image from a file creates an in memory copy of the file,
/// which is retained in the [ImageCache]. The underlying file is not
/// monitored for changes. If it does change, the application should evict
/// the entry from the [ImageCache].
///
/// See also:
///
/// * [FileImage] provider for evicting the underlying file easily.
Image.file(
File file, {
super.key,
double scale = 1.0,
this.frameBuilder,
this.errorBuilder,
this.semanticLabel,
this.excludeFromSemantics = false,
this.width,
this.height,
this.color,
this.opacity,
this.colorBlendMode,
this.fit,
this.alignment = Alignment.center,
this.repeat = ImageRepeat.noRepeat,
this.centerSlice,
this.matchTextDirection = false,
this.gaplessPlayback = false,
this.isAntiAlias = false,
this.filterQuality = FilterQuality.low,
int? cacheWidth,
int? cacheHeight,
}) :
// FileImage is not supported on Flutter Web therefore neither this method.
assert(
!kIsWeb,
'Image.file is not supported on Flutter Web. '
'Consider using either Image.asset or Image.network instead.',
),
image = ResizeImage.resizeIfNeeded(cacheWidth, cacheHeight, FileImage(file, scale: scale)),
loadingBuilder = null,
assert(cacheWidth == null || cacheWidth > 0),
assert(cacheHeight == null || cacheHeight > 0);
// TODO(ianh): Implement the following (see ../services/image_resolution.dart):
//
// * If [width] and [height] are both specified, and [scale] is not, then
// size-aware asset resolution will be attempted also, with the given
// dimensions interpreted as logical pixels.
//
// * If the images have platform, locale, or directionality variants, the
// current platform, locale, and directionality are taken into account
// during asset resolution as well.
/// Creates a widget that displays an [ImageStream] obtained from an asset
/// bundle. The key for the image is given by the `name` argument.
///
/// The `package` argument must be non-null when displaying an image from a
/// package and null otherwise. See the `Assets in packages` section for
/// details.
///
/// If the `bundle` argument is omitted or null, then the
/// [DefaultAssetBundle] will be used.
///
/// By default, the pixel-density-aware asset resolution will be attempted. In
/// addition:
///
/// * If the `scale` argument is provided and is not null, then the exact
/// asset specified will be used. To display an image variant with a specific
/// density, the exact path must be provided (e.g. `images/2x/cat.png`).
///
/// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
///
/// If `cacheWidth` or `cacheHeight` are provided, they indicate to the
/// engine that the image must be decoded at the specified size. The image
/// will be rendered to the constraints of the layout or [width] and [height]
/// regardless of these parameters. These parameters are primarily intended
/// to reduce the memory usage of [ImageCache].
///
/// Either the [width] and [height] arguments should be specified, or the
/// widget should be placed in a context that sets tight layout constraints.
/// Otherwise, the image dimensions will change as the image is loaded, which
/// will result in ugly layout changes.
///
/// {@macro flutter.widgets.image.filterQualityParameter}
///
/// {@tool snippet}
///
/// Suppose that the project's `pubspec.yaml` file contains the following:
///
/// ```yaml
/// flutter:
/// assets:
/// - images/cat.png
/// - images/2x/cat.png
/// - images/3.5x/cat.png
/// ```
/// {@end-tool}
///
/// On a screen with a device pixel ratio of 2.0, the following widget would
/// render the `images/2x/cat.png` file:
///
/// ```dart
/// Image.asset('images/cat.png')
/// ```
///
/// This corresponds to the file that is in the project's `images/2x/`
/// directory with the name `cat.png` (the paths are relative to the
/// `pubspec.yaml` file).
///
/// On a device with a 4.0 device pixel ratio, the `images/3.5x/cat.png` asset
/// would be used. On a device with a 1.0 device pixel ratio, the
/// `images/cat.png` resource would be used.
///
/// The `images/cat.png` image can be omitted from disk (though it must still
/// be present in the manifest). If it is omitted, then on a device with a 1.0
/// device pixel ratio, the `images/2x/cat.png` image would be used instead.
///
///
/// ## Assets in packages
///
/// To create the widget with an asset from a package, the [package] argument
/// must be provided. For instance, suppose a package called `my_icons` has
/// `icons/heart.png` .
///
/// {@tool snippet}
/// Then to display the image, use:
///
/// ```dart
/// Image.asset('icons/heart.png', package: 'my_icons')
/// ```
/// {@end-tool}
///
/// Assets used by the package itself should also be displayed using the
/// [package] argument as above.
///
/// If the desired asset is specified in the `pubspec.yaml` of the package, it
/// is bundled automatically with the app. In particular, assets used by the
/// package itself must be specified in its `pubspec.yaml`.
///
/// A package can also choose to have assets in its 'lib/' folder that are not
/// specified in its `pubspec.yaml`. In this case for those images to be
/// bundled, the app has to specify which ones to include. For instance a
/// package named `fancy_backgrounds` could have:
///
/// lib/backgrounds/background1.png
/// lib/backgrounds/background2.png
/// lib/backgrounds/background3.png
///
/// To include, say the first image, the `pubspec.yaml` of the app should
/// specify it in the assets section:
///
/// ```yaml
/// assets:
/// - packages/fancy_backgrounds/backgrounds/background1.png
/// ```
///
/// The `lib/` is implied, so it should not be included in the asset path.
///
///
/// See also:
///
/// * [AssetImage], which is used to implement the behavior when the scale is
/// omitted.
/// * [ExactAssetImage], which is used to implement the behavior when the
/// scale is present.
/// * <https://flutter.dev/assets-and-images/>, an introduction to assets in
/// Flutter.
Image.asset(
String name, {
super.key,
AssetBundle? bundle,
this.frameBuilder,
this.errorBuilder,
this.semanticLabel,
this.excludeFromSemantics = false,
double? scale,
this.width,
this.height,
this.color,
this.opacity,
this.colorBlendMode,
this.fit,
this.alignment = Alignment.center,
this.repeat = ImageRepeat.noRepeat,
this.centerSlice,
this.matchTextDirection = false,
this.gaplessPlayback = false,
this.isAntiAlias = false,
String? package,
this.filterQuality = FilterQuality.low,
int? cacheWidth,
int? cacheHeight,
}) : image = ResizeImage.resizeIfNeeded(
cacheWidth,
cacheHeight,
scale != null
? ExactAssetImage(name, bundle: bundle, scale: scale, package: package)
: AssetImage(name, bundle: bundle, package: package),
),
loadingBuilder = null,
assert(cacheWidth == null || cacheWidth > 0),
assert(cacheHeight == null || cacheHeight > 0);
/// Creates a widget that displays an [ImageStream] obtained from a [Uint8List].
///
/// The `bytes` argument specifies encoded image bytes, which can be encoded
/// in any of the following supported image formats:
/// {@macro dart.ui.imageFormats}
///
/// The `scale` argument specifies the linear scale factor for drawing this
/// image at its intended size and applies to both the width and the height.
/// {@macro flutter.painting.imageInfo.scale}
///
/// This only accepts compressed image formats (e.g. PNG). Uncompressed
/// formats like rawRgba (the default format of [dart:ui.Image.toByteData])
/// will lead to exceptions.
///
/// Either the [width] and [height] arguments should be specified, or the
/// widget should be placed in a context that sets tight layout constraints.
/// Otherwise, the image dimensions will change as the image is loaded, which
/// will result in ugly layout changes.
///
/// {@macro flutter.widgets.image.filterQualityParameter}
///
/// If [excludeFromSemantics] is true, then [semanticLabel] will be ignored.
///
/// If `cacheWidth` or `cacheHeight` are provided, they indicate to the
/// engine that the image must be decoded at the specified size. The image
/// will be rendered to the constraints of the layout or [width] and [height]
/// regardless of these parameters. These parameters are primarily intended
/// to reduce the memory usage of [ImageCache].
Image.memory(
Uint8List bytes, {
super.key,
double scale = 1.0,
this.frameBuilder,
this.errorBuilder,
this.semanticLabel,
this.excludeFromSemantics = false,
this.width,
this.height,
this.color,
this.opacity,
this.colorBlendMode,
this.fit,
this.alignment = Alignment.center,
this.repeat = ImageRepeat.noRepeat,
this.centerSlice,
this.matchTextDirection = false,
this.gaplessPlayback = false,
this.isAntiAlias = false,
this.filterQuality = FilterQuality.low,
int? cacheWidth,
int? cacheHeight,
}) : image = ResizeImage.resizeIfNeeded(cacheWidth, cacheHeight, MemoryImage(bytes, scale: scale)),
loadingBuilder = null,
assert(cacheWidth == null || cacheWidth > 0),
assert(cacheHeight == null || cacheHeight > 0);
/// The image to display.
final ImageProvider image;
/// A builder function responsible for creating the widget that represents
/// this image.
///
/// If this is null, this widget will display an image that is painted as
/// soon as the first image frame is available (and will appear to "pop" in
/// if it becomes available asynchronously). Callers might use this builder to
/// add effects to the image (such as fading the image in when it becomes
/// available) or to display a placeholder widget while the image is loading.
///
/// To have finer-grained control over the way that an image's loading
/// progress is communicated to the user, see [loadingBuilder].
///
/// ## Chaining with [loadingBuilder]
///
/// If a [loadingBuilder] has _also_ been specified for an image, the two
/// builders will be chained together: the _result_ of this builder will
/// be passed as the `child` argument to the [loadingBuilder]. For example,
/// consider the following builders used in conjunction:
///
/// {@template flutter.widgets.Image.frameBuilder.chainedBuildersExample}
/// ```dart
/// Image(
/// image: _image,
/// frameBuilder: (BuildContext context, Widget child, int? frame, bool? wasSynchronouslyLoaded) {
/// return Padding(
/// padding: const EdgeInsets.all(8.0),
/// child: child,
/// );
/// },
/// loadingBuilder: (BuildContext context, Widget child, ImageChunkEvent? loadingProgress) {
/// return Center(child: child);
/// },
/// )
/// ```
///
/// In this example, the widget hierarchy will contain the following:
///
/// ```dart
/// Center(
/// child: Padding(
/// padding: const EdgeInsets.all(8.0),
/// child: image,
/// ),
/// ),
/// ```
/// {@endtemplate}
///
/// {@tool dartpad}
/// The following sample demonstrates how to use this builder to implement an
/// image that fades in once it's been loaded.
///
/// This sample contains a limited subset of the functionality that the
/// [FadeInImage] widget provides out of the box.
///
/// ** See code in examples/api/lib/widgets/image/image.frame_builder.0.dart **
/// {@end-tool}
final ImageFrameBuilder? frameBuilder;
/// A builder that specifies the widget to display to the user while an image
/// is still loading.
///
/// If this is null, and the image is loaded incrementally (e.g. over a
/// network), the user will receive no indication of the progress as the
/// bytes of the image are loaded.
///
/// For more information on how to interpret the arguments that are passed to
/// this builder, see the documentation on [ImageLoadingBuilder].
///
/// ## Performance implications
///
/// If a [loadingBuilder] is specified for an image, the [Image] widget is
/// likely to be rebuilt on every
/// [rendering pipeline frame](rendering/RendererBinding/drawFrame.html) until
/// the image has loaded. This is useful for cases such as displaying a loading
/// progress indicator, but for simpler cases such as displaying a placeholder
/// widget that doesn't depend on the loading progress (e.g. static "loading"
/// text), [frameBuilder] will likely work and not incur as much cost.
///
/// ## Chaining with [frameBuilder]
///
/// If a [frameBuilder] has _also_ been specified for an image, the two
/// builders will be chained together: the `child` argument to this
/// builder will contain the _result_ of the [frameBuilder]. For example,
/// consider the following builders used in conjunction:
///
/// {@macro flutter.widgets.Image.frameBuilder.chainedBuildersExample}
///
/// {@tool dartpad}
/// The following sample uses [loadingBuilder] to show a
/// [CircularProgressIndicator] while an image loads over the network.
///
/// ** See code in examples/api/lib/widgets/image/image.loading_builder.0.dart **
/// {@end-tool}
///
/// Run against a real-world image on a slow network, the previous example
/// renders the following loading progress indicator while the image loads
/// before rendering the completed image.
///
/// {@animation 400 400 https://flutter.github.io/assets-for-api-docs/assets/widgets/loading_progress_image.mp4}
final ImageLoadingBuilder? loadingBuilder;
/// A builder function that is called if an error occurs during image loading.
///
/// If this builder is not provided, any exceptions will be reported to
/// [FlutterError.onError]. If it is provided, the caller should either handle
/// the exception by providing a replacement widget, or rethrow the exception.
///
/// {@tool dartpad}
/// The following sample uses [errorBuilder] to show a '😢' in place of the
/// image that fails to load, and prints the error to the console.
///
/// ** See code in examples/api/lib/widgets/image/image.error_builder.0.dart **
/// {@end-tool}
final ImageErrorWidgetBuilder? errorBuilder;
/// If non-null, require the image to have this width (in logical pixels).
///
/// If null, the image will pick a size that best preserves its intrinsic
/// aspect ratio.
///
/// It is strongly recommended that either both the [width] and the [height]
/// be specified, or that the widget be placed in a context that sets tight
/// layout constraints, so that the image does not change size as it loads.
/// Consider using [fit] to adapt the image's rendering to fit the given width
/// and height if the exact image dimensions are not known in advance.
final double? width;
/// If non-null, require the image to have this height (in logical pixels).
///
/// If null, the image will pick a size that best preserves its intrinsic
/// aspect ratio.
///
/// It is strongly recommended that either both the [width] and the [height]
/// be specified, or that the widget be placed in a context that sets tight
/// layout constraints, so that the image does not change size as it loads.
/// Consider using [fit] to adapt the image's rendering to fit the given width
/// and height if the exact image dimensions are not known in advance.
final double? height;
/// If non-null, this color is blended with each image pixel using [colorBlendMode].
final Color? color;
/// If non-null, the value from the [Animation] is multiplied with the opacity
/// of each image pixel before painting onto the canvas.
///
/// This is more efficient than using [FadeTransition] to change the opacity
/// of an image, since this avoids creating a new composited layer. Composited
/// layers may double memory usage as the image is painted onto an offscreen
/// render target.
///
/// See also:
///
/// * [AlwaysStoppedAnimation], which allows you to create an [Animation]
/// from a single opacity value.
final Animation<double>? opacity;
/// The rendering quality of the image.
///
/// {@template flutter.widgets.image.filterQuality}
/// If the image is of a high quality and its pixels are perfectly aligned
/// with the physical screen pixels, extra quality enhancement may not be
/// necessary. If so, then [FilterQuality.none] would be the most efficient.
///
/// If the pixels are not perfectly aligned with the screen pixels, or if the
/// image itself is of a low quality, [FilterQuality.none] may produce
/// undesirable artifacts. Consider using other [FilterQuality] values to
/// improve the rendered image quality in this case. Pixels may be misaligned
/// with the screen pixels as a result of transforms or scaling.
///
/// See also:
///
/// * [FilterQuality], the enum containing all possible filter quality
/// options.
/// {@endtemplate}
final FilterQuality filterQuality;
/// Used to combine [color] with this image.
///
/// The default is [BlendMode.srcIn]. In terms of the blend mode, [color] is
/// the source and this image is the destination.
///
/// See also:
///
/// * [BlendMode], which includes an illustration of the effect of each blend mode.
final BlendMode? colorBlendMode;
/// How to inscribe the image into the space allocated during layout.
///
/// The default varies based on the other fields. See the discussion at
/// [paintImage].
final BoxFit? fit;
/// How to align the image within its bounds.
///
/// The alignment aligns the given position in the image to the given position
/// in the layout bounds. For example, an [Alignment] alignment of (-1.0,
/// -1.0) aligns the image to the top-left corner of its layout bounds, while an
/// [Alignment] alignment of (1.0, 1.0) aligns the bottom right of the
/// image with the bottom right corner of its layout bounds. Similarly, an
/// alignment of (0.0, 1.0) aligns the bottom middle of the image with the
/// middle of the bottom edge of its layout bounds.
///
/// To display a subpart of an image, consider using a [CustomPainter] and
/// [Canvas.drawImageRect].
///
/// If the [alignment] is [TextDirection]-dependent (i.e. if it is a
/// [AlignmentDirectional]), then an ambient [Directionality] widget
/// must be in scope.
///
/// Defaults to [Alignment.center].
///
/// See also:
///
/// * [Alignment], a class with convenient constants typically used to
/// specify an [AlignmentGeometry].
/// * [AlignmentDirectional], like [Alignment] for specifying alignments
/// relative to text direction.
final AlignmentGeometry alignment;
/// How to paint any portions of the layout bounds not covered by the image.
final ImageRepeat repeat;
/// The center slice for a nine-patch image.
///
/// The region of the image inside the center slice will be stretched both
/// horizontally and vertically to fit the image into its destination. The
/// region of the image above and below the center slice will be stretched
/// only horizontally and the region of the image to the left and right of
/// the center slice will be stretched only vertically.
final Rect? centerSlice;
/// Whether to paint the image in the direction of the [TextDirection].
///
/// If this is true, then in [TextDirection.ltr] contexts, the image will be
/// drawn with its origin in the top left (the "normal" painting direction for
/// images); and in [TextDirection.rtl] contexts, the image will be drawn with
/// a scaling factor of -1 in the horizontal direction so that the origin is
/// in the top right.
///
/// This is occasionally used with images in right-to-left environments, for
/// images that were designed for left-to-right locales. Be careful, when
/// using this, to not flip images with integral shadows, text, or other
/// effects that will look incorrect when flipped.
///
/// If this is true, there must be an ambient [Directionality] widget in
/// scope.
final bool matchTextDirection;
/// Whether to continue showing the old image (true), or briefly show nothing
/// (false), when the image provider changes. The default value is false.
///
/// ## Design discussion
///
/// ### Why is the default value of [gaplessPlayback] false?
///
/// Having the default value of [gaplessPlayback] be false helps prevent
/// situations where stale or misleading information might be presented.
/// Consider the following case:
///
/// We have constructed a 'Person' widget that displays an avatar [Image] of
/// the currently loaded person along with their name. We could request for a
/// new person to be loaded into the widget at any time. Suppose we have a
/// person currently loaded and the widget loads a new person. What happens
/// if the [Image] fails to load?
///
/// * Option A ([gaplessPlayback] = false): The new person's name is coupled
/// with a blank image.
///
/// * Option B ([gaplessPlayback] = true): The widget displays the avatar of
/// the previous person and the name of the newly loaded person.
///
/// This is why the default value is false. Most of the time, when you change
/// the image provider you're not just changing the image, you're removing the
/// old widget and adding a new one and not expecting them to have any
/// relationship. With [gaplessPlayback] on you might accidentally break this
/// expectation and re-use the old widget.
final bool gaplessPlayback;
/// A Semantic description of the image.
///
/// Used to provide a description of the image to TalkBack on Android, and
/// VoiceOver on iOS.
final String? semanticLabel;
/// Whether to exclude this image from semantics.
///
/// Useful for images which do not contribute meaningful information to an
/// application.
final bool excludeFromSemantics;
/// Whether to paint the image with anti-aliasing.
///
/// Anti-aliasing alleviates the sawtooth artifact when the image is rotated.
final bool isAntiAlias;
@override
State<Image> createState() => _ImageState();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<ImageProvider>('image', image));
properties.add(DiagnosticsProperty<Function>('frameBuilder', frameBuilder));
properties.add(DiagnosticsProperty<Function>('loadingBuilder', loadingBuilder));
properties.add(DoubleProperty('width', width, defaultValue: null));
properties.add(DoubleProperty('height', height, defaultValue: null));
properties.add(ColorProperty('color', color, defaultValue: null));
properties.add(DiagnosticsProperty<Animation<double>?>('opacity', opacity, defaultValue: null));
properties.add(EnumProperty<BlendMode>('colorBlendMode', colorBlendMode, defaultValue: null));
properties.add(EnumProperty<BoxFit>('fit', fit, defaultValue: null));
properties.add(DiagnosticsProperty<AlignmentGeometry>('alignment', alignment, defaultValue: null));
properties.add(EnumProperty<ImageRepeat>('repeat', repeat, defaultValue: ImageRepeat.noRepeat));
properties.add(DiagnosticsProperty<Rect>('centerSlice', centerSlice, defaultValue: null));
properties.add(FlagProperty('matchTextDirection', value: matchTextDirection, ifTrue: 'match text direction'));
properties.add(StringProperty('semanticLabel', semanticLabel, defaultValue: null));
properties.add(DiagnosticsProperty<bool>('this.excludeFromSemantics', excludeFromSemantics));
properties.add(EnumProperty<FilterQuality>('filterQuality', filterQuality));
}
}
class _ImageState extends State<Image> with WidgetsBindingObserver {
ImageStream? _imageStream;
ImageInfo? _imageInfo;
ImageChunkEvent? _loadingProgress;
bool _isListeningToStream = false;
late bool _invertColors;
int? _frameNumber;
bool _wasSynchronouslyLoaded = false;
late DisposableBuildContext<State<Image>> _scrollAwareContext;
Object? _lastException;
StackTrace? _lastStack;
ImageStreamCompleterHandle? _completerHandle;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_scrollAwareContext = DisposableBuildContext<State<Image>>(this);
}
@override
void dispose() {
assert(_imageStream != null);
WidgetsBinding.instance.removeObserver(this);
_stopListeningToStream();
_completerHandle?.dispose();
_scrollAwareContext.dispose();
_replaceImage(info: null);
super.dispose();
}
@override
void didChangeDependencies() {
_updateInvertColors();
_resolveImage();
if (TickerMode.of(context)) {
_listenToStream();
} else {
_stopListeningToStream(keepStreamAlive: true);
}
super.didChangeDependencies();
}
@override
void didUpdateWidget(Image oldWidget) {
super.didUpdateWidget(oldWidget);
if (_isListeningToStream &&
(widget.loadingBuilder == null) != (oldWidget.loadingBuilder == null)) {
final ImageStreamListener oldListener = _getListener();
_imageStream!.addListener(_getListener(recreateListener: true));
_imageStream!.removeListener(oldListener);
}
if (widget.image != oldWidget.image) {
_resolveImage();
}
}
@override
void didChangeAccessibilityFeatures() {
super.didChangeAccessibilityFeatures();
setState(() {
_updateInvertColors();
});
}
@override
void reassemble() {
_resolveImage(); // in case the image cache was flushed
super.reassemble();
}
void _updateInvertColors() {
_invertColors = MediaQuery.maybeInvertColorsOf(context)
?? SemanticsBinding.instance.accessibilityFeatures.invertColors;
}
void _resolveImage() {
final ScrollAwareImageProvider provider = ScrollAwareImageProvider<Object>(
context: _scrollAwareContext,
imageProvider: widget.image,
);
final ImageStream newStream =
provider.resolve(createLocalImageConfiguration(
context,
size: widget.width != null && widget.height != null ? Size(widget.width!, widget.height!) : null,
));
_updateSourceStream(newStream);
}
ImageStreamListener? _imageStreamListener;
ImageStreamListener _getListener({bool recreateListener = false}) {
if (_imageStreamListener == null || recreateListener) {
_lastException = null;
_lastStack = null;
_imageStreamListener = ImageStreamListener(
_handleImageFrame,
onChunk: widget.loadingBuilder == null ? null : _handleImageChunk,
onError: widget.errorBuilder != null || kDebugMode
? (Object error, StackTrace? stackTrace) {
setState(() {
_lastException = error;
_lastStack = stackTrace;
});
assert(() {
if (widget.errorBuilder == null) {
// ignore: only_throw_errors, since we're just proxying the error.
throw error; // Ensures the error message is printed to the console.
}
return true;
}());
}
: null,
);
}
return _imageStreamListener!;
}
void _handleImageFrame(ImageInfo imageInfo, bool synchronousCall) {
setState(() {
_replaceImage(info: imageInfo);
_loadingProgress = null;
_lastException = null;
_lastStack = null;
_frameNumber = _frameNumber == null ? 0 : _frameNumber! + 1;
_wasSynchronouslyLoaded = _wasSynchronouslyLoaded | synchronousCall;
});
}
void _handleImageChunk(ImageChunkEvent event) {
assert(widget.loadingBuilder != null);
setState(() {
_loadingProgress = event;
_lastException = null;
_lastStack = null;
});
}
void _replaceImage({required ImageInfo? info}) {
final ImageInfo? oldImageInfo = _imageInfo;
SchedulerBinding.instance.addPostFrameCallback(
(_) => oldImageInfo?.dispose(),
debugLabel: 'Image.disposeOldInfo'
);
_imageInfo = info;
}
// Updates _imageStream to newStream, and moves the stream listener
// registration from the old stream to the new stream (if a listener was
// registered).
void _updateSourceStream(ImageStream newStream) {
if (_imageStream?.key == newStream.key) {
return;
}
if (_isListeningToStream) {
_imageStream!.removeListener(_getListener());
}
if (!widget.gaplessPlayback) {
setState(() { _replaceImage(info: null); });
}
setState(() {
_loadingProgress = null;
_frameNumber = null;
_wasSynchronouslyLoaded = false;
});
_imageStream = newStream;
if (_isListeningToStream) {
_imageStream!.addListener(_getListener());
}
}
void _listenToStream() {
if (_isListeningToStream) {
return;
}
_imageStream!.addListener(_getListener());
_completerHandle?.dispose();
_completerHandle = null;
_isListeningToStream = true;
}
/// Stops listening to the image stream, if this state object has attached a
/// listener.
///
/// If the listener from this state is the last listener on the stream, the
/// stream will be disposed. To keep the stream alive, set `keepStreamAlive`
/// to true, which create [ImageStreamCompleterHandle] to keep the completer
/// alive and is compatible with the [TickerMode] being off.
void _stopListeningToStream({bool keepStreamAlive = false}) {
if (!_isListeningToStream) {
return;
}
if (keepStreamAlive && _completerHandle == null && _imageStream?.completer != null) {
_completerHandle = _imageStream!.completer!.keepAlive();
}
_imageStream!.removeListener(_getListener());
_isListeningToStream = false;
}
Widget _debugBuildErrorWidget(BuildContext context, Object error) {
return Stack(
alignment: Alignment.center,
children: <Widget>[
const Positioned.fill(
child: Placeholder(
color: Color(0xCF8D021F),
),
),
Padding(
padding: const EdgeInsets.all(4.0),
child: FittedBox(
child: Text(
'$error',
textAlign: TextAlign.center,
textDirection: TextDirection.ltr,
style: const TextStyle(
shadows: <Shadow>[
Shadow(blurRadius: 1.0),
],
),
),
),
),
],
);
}
@override
Widget build(BuildContext context) {
if (_lastException != null) {
if (widget.errorBuilder != null) {
return widget.errorBuilder!(context, _lastException!, _lastStack);
}
if (kDebugMode) {
return _debugBuildErrorWidget(context, _lastException!);
}
}
Widget result = RawImage(
// Do not clone the image, because RawImage is a stateless wrapper.
// The image will be disposed by this state object when it is not needed
// anymore, such as when it is unmounted or when the image stream pushes
// a new image.
image: _imageInfo?.image,
debugImageLabel: _imageInfo?.debugLabel,
width: widget.width,
height: widget.height,
scale: _imageInfo?.scale ?? 1.0,
color: widget.color,
opacity: widget.opacity,
colorBlendMode: widget.colorBlendMode,
fit: widget.fit,
alignment: widget.alignment,
repeat: widget.repeat,
centerSlice: widget.centerSlice,
matchTextDirection: widget.matchTextDirection,
invertColors: _invertColors,
isAntiAlias: widget.isAntiAlias,
filterQuality: widget.filterQuality,
);
if (!widget.excludeFromSemantics) {
result = Semantics(
container: widget.semanticLabel != null,
image: true,
label: widget.semanticLabel ?? '',
child: result,
);
}
if (widget.frameBuilder != null) {
result = widget.frameBuilder!(context, result, _frameNumber, _wasSynchronouslyLoaded);
}
if (widget.loadingBuilder != null) {
result = widget.loadingBuilder!(context, result, _loadingProgress);
}
return result;
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder description) {
super.debugFillProperties(description);
description.add(DiagnosticsProperty<ImageStream>('stream', _imageStream));
description.add(DiagnosticsProperty<ImageInfo>('pixels', _imageInfo));
description.add(DiagnosticsProperty<ImageChunkEvent>('loadingProgress', _loadingProgress));
description.add(DiagnosticsProperty<int>('frameNumber', _frameNumber));
description.add(DiagnosticsProperty<bool>('wasSynchronouslyLoaded', _wasSynchronouslyLoaded));
}
}
| flutter/packages/flutter/lib/src/widgets/image.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/image.dart",
"repo_id": "flutter",
"token_count": 15702
} | 644 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:math' as math;
import 'basic.dart';
import 'debug.dart';
import 'framework.dart';
/// [NavigationToolbar] is a layout helper to position 3 widgets or groups of
/// widgets along a horizontal axis that's sensible for an application's
/// navigation bar such as in Material Design and in iOS.
///
/// The [leading] and [trailing] widgets occupy the edges of the widget with
/// reasonable size constraints while the [middle] widget occupies the remaining
/// space in either a center aligned or start aligned fashion.
///
/// Either directly use the themed app bars such as the Material [AppBar] or
/// the iOS [CupertinoNavigationBar] or wrap this widget with more theming
/// specifications for your own custom app bar.
class NavigationToolbar extends StatelessWidget {
/// Creates a widget that lays out its children in a manner suitable for a
/// toolbar.
const NavigationToolbar({
super.key,
this.leading,
this.middle,
this.trailing,
this.centerMiddle = true,
this.middleSpacing = kMiddleSpacing,
});
/// The default spacing around the [middle] widget in dp.
static const double kMiddleSpacing = 16.0;
/// Widget to place at the start of the horizontal toolbar.
final Widget? leading;
/// Widget to place in the middle of the horizontal toolbar, occupying
/// as much remaining space as possible.
final Widget? middle;
/// Widget to place at the end of the horizontal toolbar.
final Widget? trailing;
/// Whether to align the [middle] widget to the center of this widget or
/// next to the [leading] widget when false.
final bool centerMiddle;
/// The spacing around the [middle] widget on horizontal axis.
///
/// Defaults to [kMiddleSpacing].
final double middleSpacing;
@override
Widget build(BuildContext context) {
assert(debugCheckHasDirectionality(context));
final TextDirection textDirection = Directionality.of(context);
return CustomMultiChildLayout(
delegate: _ToolbarLayout(
centerMiddle: centerMiddle,
middleSpacing: middleSpacing,
textDirection: textDirection,
),
children: <Widget>[
if (leading != null) LayoutId(id: _ToolbarSlot.leading, child: leading!),
if (middle != null) LayoutId(id: _ToolbarSlot.middle, child: middle!),
if (trailing != null) LayoutId(id: _ToolbarSlot.trailing, child: trailing!),
],
);
}
}
enum _ToolbarSlot {
leading,
middle,
trailing,
}
class _ToolbarLayout extends MultiChildLayoutDelegate {
_ToolbarLayout({
required this.centerMiddle,
required this.middleSpacing,
required this.textDirection,
});
// If false the middle widget should be start-justified within the space
// between the leading and trailing widgets.
// If true the middle widget is centered within the toolbar (not within the horizontal
// space between the leading and trailing widgets).
final bool centerMiddle;
/// The spacing around middle widget on horizontal axis.
final double middleSpacing;
final TextDirection textDirection;
@override
void performLayout(Size size) {
double leadingWidth = 0.0;
double trailingWidth = 0.0;
if (hasChild(_ToolbarSlot.leading)) {
final BoxConstraints constraints = BoxConstraints(
maxWidth: size.width,
minHeight: size.height, // The height should be exactly the height of the bar.
maxHeight: size.height,
);
leadingWidth = layoutChild(_ToolbarSlot.leading, constraints).width;
final double leadingX = switch (textDirection) {
TextDirection.rtl => size.width - leadingWidth,
TextDirection.ltr => 0.0,
};
positionChild(_ToolbarSlot.leading, Offset(leadingX, 0.0));
}
if (hasChild(_ToolbarSlot.trailing)) {
final BoxConstraints constraints = BoxConstraints.loose(size);
final Size trailingSize = layoutChild(_ToolbarSlot.trailing, constraints);
final double trailingX = switch (textDirection) {
TextDirection.rtl => 0.0,
TextDirection.ltr => size.width - trailingSize.width,
};
final double trailingY = (size.height - trailingSize.height) / 2.0;
trailingWidth = trailingSize.width;
positionChild(_ToolbarSlot.trailing, Offset(trailingX, trailingY));
}
if (hasChild(_ToolbarSlot.middle)) {
final double maxWidth = math.max(size.width - leadingWidth - trailingWidth - middleSpacing * 2.0, 0.0);
final BoxConstraints constraints = BoxConstraints.loose(size).copyWith(maxWidth: maxWidth);
final Size middleSize = layoutChild(_ToolbarSlot.middle, constraints);
final double middleStartMargin = leadingWidth + middleSpacing;
double middleStart = middleStartMargin;
final double middleY = (size.height - middleSize.height) / 2.0;
// If the centered middle will not fit between the leading and trailing
// widgets, then align its left or right edge with the adjacent boundary.
if (centerMiddle) {
middleStart = (size.width - middleSize.width) / 2.0;
if (middleStart + middleSize.width > size.width - trailingWidth) {
middleStart = size.width - trailingWidth - middleSize.width - middleSpacing;
} else if (middleStart < middleStartMargin) {
middleStart = middleStartMargin;
}
}
final double middleX = switch (textDirection) {
TextDirection.rtl => size.width - middleSize.width - middleStart,
TextDirection.ltr => middleStart,
};
positionChild(_ToolbarSlot.middle, Offset(middleX, middleY));
}
}
@override
bool shouldRelayout(_ToolbarLayout oldDelegate) {
return oldDelegate.centerMiddle != centerMiddle
|| oldDelegate.middleSpacing != middleSpacing
|| oldDelegate.textDirection != textDirection;
}
}
| flutter/packages/flutter/lib/src/widgets/navigation_toolbar.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/navigation_toolbar.dart",
"repo_id": "flutter",
"token_count": 1924
} | 645 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import '_html_element_view_io.dart' if (dart.library.js_util) '_html_element_view_web.dart';
import 'basic.dart';
import 'debug.dart';
import 'focus_manager.dart';
import 'focus_scope.dart';
import 'framework.dart';
// Examples can assume:
// PlatformViewController createFooWebView(PlatformViewCreationParams params) { return (null as dynamic) as PlatformViewController; }
// Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers = <Factory<OneSequenceGestureRecognizer>>{};
// late PlatformViewController _controller;
/// Embeds an Android view in the Widget hierarchy.
///
/// Requires Android API level 23 or greater.
///
/// Embedding Android views is an expensive operation and should be avoided when a Flutter
/// equivalent is possible.
///
/// The embedded Android view is painted just like any other Flutter widget and transformations
/// apply to it as well.
///
/// {@template flutter.widgets.AndroidView.layout}
/// The widget fills all available space, the parent of this object must provide bounded layout
/// constraints.
/// {@endtemplate}
///
/// {@template flutter.widgets.AndroidView.gestures}
/// The widget participates in Flutter's gesture arenas, and dispatches touch events to the
/// platform view iff it won the arena. Specific gestures that should be dispatched to the platform
/// view can be specified in the `gestureRecognizers` constructor parameter. If
/// the set of gesture recognizers is empty, a gesture will be dispatched to the platform
/// view iff it was not claimed by any other gesture recognizer.
/// {@endtemplate}
///
/// The Android view object is created using a [PlatformViewFactory](/javadoc/io/flutter/plugin/platform/PlatformViewFactory.html).
/// Plugins can register platform view factories with [PlatformViewRegistry#registerViewFactory](/javadoc/io/flutter/plugin/platform/PlatformViewRegistry.html#registerViewFactory-java.lang.String-io.flutter.plugin.platform.PlatformViewFactory-).
///
/// Registration is typically done in the plugin's registerWith method, e.g:
///
/// ```java
/// public static void registerWith(Registrar registrar) {
/// registrar.platformViewRegistry().registerViewFactory("webview", WebViewFactory(registrar.messenger()));
/// }
/// ```
///
/// {@template flutter.widgets.AndroidView.lifetime}
/// The platform view's lifetime is the same as the lifetime of the [State] object for this widget.
/// When the [State] is disposed the platform view (and auxiliary resources) are lazily
/// released (some resources are immediately released and some by platform garbage collector).
/// A stateful widget's state is disposed when the widget is removed from the tree or when it is
/// moved within the tree. If the stateful widget has a key and it's only moved relative to its siblings,
/// or it has a [GlobalKey] and it's moved within the tree, it will not be disposed.
/// {@endtemplate}
class AndroidView extends StatefulWidget {
/// Creates a widget that embeds an Android view.
///
/// {@template flutter.widgets.AndroidView.constructorArgs}
/// If `creationParams` is not null then `creationParamsCodec` must not be null.
/// {@endtemplate}
const AndroidView({
super.key,
required this.viewType,
this.onPlatformViewCreated,
this.hitTestBehavior = PlatformViewHitTestBehavior.opaque,
this.layoutDirection,
this.gestureRecognizers,
this.creationParams,
this.creationParamsCodec,
this.clipBehavior = Clip.hardEdge,
}) : assert(creationParams == null || creationParamsCodec != null);
/// The unique identifier for Android view type to be embedded by this widget.
///
/// A [PlatformViewFactory](/javadoc/io/flutter/plugin/platform/PlatformViewFactory.html)
/// for this type must have been registered.
///
/// See also:
///
/// * [AndroidView] for an example of registering a platform view factory.
final String viewType;
/// {@template flutter.widgets.AndroidView.onPlatformViewCreated}
/// Callback to invoke after the platform view has been created.
///
/// May be null.
/// {@endtemplate}
final PlatformViewCreatedCallback? onPlatformViewCreated;
/// {@template flutter.widgets.AndroidView.hitTestBehavior}
/// How this widget should behave during hit testing.
///
/// This defaults to [PlatformViewHitTestBehavior.opaque].
/// {@endtemplate}
final PlatformViewHitTestBehavior hitTestBehavior;
/// {@template flutter.widgets.AndroidView.layoutDirection}
/// The text direction to use for the embedded view.
///
/// If this is null, the ambient [Directionality] is used instead.
/// {@endtemplate}
final TextDirection? layoutDirection;
/// Which gestures should be forwarded to the Android view.
///
/// {@template flutter.widgets.AndroidView.gestureRecognizers.descHead}
/// The gesture recognizers built by factories in this set participate in the gesture arena for
/// each pointer that was put down on the widget. If any of these recognizers win the
/// gesture arena, the entire pointer event sequence starting from the pointer down event
/// will be dispatched to the platform view.
///
/// When null, an empty set of gesture recognizer factories is used, in which case a pointer event sequence
/// will only be dispatched to the platform view if no other member of the arena claimed it.
/// {@endtemplate}
///
/// For example, with the following setup vertical drags will not be dispatched to the Android
/// view as the vertical drag gesture is claimed by the parent [GestureDetector].
///
/// ```dart
/// GestureDetector(
/// onVerticalDragStart: (DragStartDetails d) {},
/// child: const AndroidView(
/// viewType: 'webview',
/// ),
/// )
/// ```
///
/// To get the [AndroidView] to claim the vertical drag gestures we can pass a vertical drag
/// gesture recognizer factory in [gestureRecognizers] e.g:
///
/// ```dart
/// GestureDetector(
/// onVerticalDragStart: (DragStartDetails details) {},
/// child: SizedBox(
/// width: 200.0,
/// height: 100.0,
/// child: AndroidView(
/// viewType: 'webview',
/// gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{
/// Factory<OneSequenceGestureRecognizer>(
/// () => EagerGestureRecognizer(),
/// ),
/// },
/// ),
/// ),
/// )
/// ```
///
/// {@template flutter.widgets.AndroidView.gestureRecognizers.descFoot}
/// A platform view can be configured to consume all pointers that were put
/// down in its bounds by passing a factory for an [EagerGestureRecognizer] in
/// [gestureRecognizers]. [EagerGestureRecognizer] is a special gesture
/// recognizer that immediately claims the gesture after a pointer down event.
///
/// The [gestureRecognizers] property must not contain more than one factory
/// with the same [Factory.type].
///
/// Changing [gestureRecognizers] results in rejection of any active gesture
/// arenas (if the platform view is actively participating in an arena).
/// {@endtemplate}
// We use OneSequenceGestureRecognizers as they support gesture arena teams.
// TODO(amirh): get a list of GestureRecognizers here.
// https://github.com/flutter/flutter/issues/20953
final Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers;
/// Passed as the args argument of [PlatformViewFactory#create](/javadoc/io/flutter/plugin/platform/PlatformViewFactory.html#create-android.content.Context-int-java.lang.Object-)
///
/// This can be used by plugins to pass constructor parameters to the embedded Android view.
final dynamic creationParams;
/// The codec used to encode `creationParams` before sending it to the
/// platform side. It should match the codec passed to the constructor of [PlatformViewFactory](/javadoc/io/flutter/plugin/platform/PlatformViewFactory.html#PlatformViewFactory-io.flutter.plugin.common.MessageCodec-).
///
/// This is typically one of: [StandardMessageCodec], [JSONMessageCodec], [StringCodec], or [BinaryCodec].
///
/// This must not be null if [creationParams] is not null.
final MessageCodec<dynamic>? creationParamsCodec;
/// {@macro flutter.material.Material.clipBehavior}
///
/// Defaults to [Clip.hardEdge].
final Clip clipBehavior;
@override
State<AndroidView> createState() => _AndroidViewState();
}
/// Common superclass for iOS and macOS platform views.
///
/// Platform views are used to embed native views in the widget hierarchy, with
/// support for transforms, clips, and opacity similar to any other Flutter widget.
abstract class _DarwinView extends StatefulWidget {
/// Creates a widget that embeds a platform view.
///
/// {@macro flutter.widgets.AndroidView.constructorArgs}
const _DarwinView({
super.key,
required this.viewType,
this.onPlatformViewCreated,
this.hitTestBehavior = PlatformViewHitTestBehavior.opaque,
this.layoutDirection,
this.creationParams,
this.creationParamsCodec,
this.gestureRecognizers,
}) : assert(creationParams == null || creationParamsCodec != null);
// TODO(amirh): reference the iOS API doc once available.
/// The unique identifier for iOS view type to be embedded by this widget.
///
/// A PlatformViewFactory for this type must have been registered.
final String viewType;
/// {@macro flutter.widgets.AndroidView.onPlatformViewCreated}
final PlatformViewCreatedCallback? onPlatformViewCreated;
/// {@macro flutter.widgets.AndroidView.hitTestBehavior}
final PlatformViewHitTestBehavior hitTestBehavior;
/// {@macro flutter.widgets.AndroidView.layoutDirection}
final TextDirection? layoutDirection;
/// Passed as the `arguments` argument of [-\[FlutterPlatformViewFactory createWithFrame:viewIdentifier:arguments:\]](/ios-embedder/protocol_flutter_platform_view_factory-p.html#a4e3c4390cd6ebd982390635e9bca4edc)
///
/// This can be used by plugins to pass constructor parameters to the embedded iOS view.
final dynamic creationParams;
/// The codec used to encode `creationParams` before sending it to the
/// platform side. It should match the codec returned by [-\[FlutterPlatformViewFactory createArgsCodec:\]](/ios-embedder/protocol_flutter_platform_view_factory-p.html#a32c3c067cb45a83dfa720c74a0d5c93c)
///
/// This is typically one of: [StandardMessageCodec], [JSONMessageCodec], [StringCodec], or [BinaryCodec].
///
/// This must not be null if [creationParams] is not null.
final MessageCodec<dynamic>? creationParamsCodec;
/// Which gestures should be forwarded to the UIKit view.
///
/// {@macro flutter.widgets.AndroidView.gestureRecognizers.descHead}
///
/// For example, with the following setup vertical drags will not be dispatched to the UIKit
/// view as the vertical drag gesture is claimed by the parent [GestureDetector].
///
/// ```dart
/// GestureDetector(
/// onVerticalDragStart: (DragStartDetails details) {},
/// child: const UiKitView(
/// viewType: 'webview',
/// ),
/// )
/// ```
///
/// To get the [UiKitView] to claim the vertical drag gestures we can pass a vertical drag
/// gesture recognizer factory in [gestureRecognizers] e.g:
///
/// ```dart
/// GestureDetector(
/// onVerticalDragStart: (DragStartDetails details) {},
/// child: SizedBox(
/// width: 200.0,
/// height: 100.0,
/// child: UiKitView(
/// viewType: 'webview',
/// gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{
/// Factory<OneSequenceGestureRecognizer>(
/// () => EagerGestureRecognizer(),
/// ),
/// },
/// ),
/// ),
/// )
/// ```
///
/// {@macro flutter.widgets.AndroidView.gestureRecognizers.descFoot}
// We use OneSequenceGestureRecognizers as they support gesture arena teams.
// TODO(amirh): get a list of GestureRecognizers here.
// https://github.com/flutter/flutter/issues/20953
final Set<Factory<OneSequenceGestureRecognizer>>? gestureRecognizers;
}
// TODO(amirh): describe the embedding mechanism.
// TODO(ychris): remove the documentation for conic path not supported once https://github.com/flutter/flutter/issues/35062 is resolved.
/// Embeds an iOS view in the Widget hierarchy.
///
/// Embedding iOS views is an expensive operation and should be avoided when a Flutter
/// equivalent is possible.
///
/// {@macro flutter.widgets.AndroidView.layout}
///
/// {@macro flutter.widgets.AndroidView.gestures}
///
/// {@macro flutter.widgets.AndroidView.lifetime}
///
/// Construction of UIViews is done asynchronously, before the UIView is ready this widget paints
/// nothing while maintaining the same layout constraints.
///
/// Clipping operations on a UiKitView can result slow performance.
/// If a conic path clipping is applied to a UIKitView,
/// a quad path is used to approximate the clip due to limitation of Quartz.
class UiKitView extends _DarwinView {
/// Creates a widget that embeds an iOS view.
///
/// {@macro flutter.widgets.AndroidView.constructorArgs}
const UiKitView({
super.key,
required super.viewType,
super.onPlatformViewCreated,
super.hitTestBehavior = PlatformViewHitTestBehavior.opaque,
super.layoutDirection,
super.creationParams,
super.creationParamsCodec,
super.gestureRecognizers,
}) : assert(creationParams == null || creationParamsCodec != null);
@override
State<UiKitView> createState() => _UiKitViewState();
}
/// Widget that contains a macOS AppKit view.
///
/// Embedding macOS views is an expensive operation and should be avoided where
/// a Flutter equivalent is possible.
///
/// The platform view's lifetime is the same as the lifetime of the [State]
/// object for this widget. When the [State] is disposed the platform view (and
/// auxiliary resources) are lazily released (some resources are immediately
/// released and some by platform garbage collector). A stateful widget's state
/// is disposed when the widget is removed from the tree or when it is moved
/// within the tree. If the stateful widget has a key and it's only moved
/// relative to its siblings, or it has a [GlobalKey] and it's moved within the
/// tree, it will not be disposed.
///
/// Construction of AppKitViews is done asynchronously, before the underlying
/// NSView is ready this widget paints nothing while maintaining the same
/// layout constraints.
class AppKitView extends _DarwinView {
/// Creates a widget that embeds a macOS AppKit NSView.
const AppKitView({
super.key,
required super.viewType,
super.onPlatformViewCreated,
super.hitTestBehavior = PlatformViewHitTestBehavior.opaque,
super.layoutDirection,
super.creationParams,
super.creationParamsCodec,
super.gestureRecognizers,
});
@override
State<AppKitView> createState() => _AppKitViewState();
}
/// Callback signature for when the platform view's DOM element was created.
///
/// [element] is the DOM element that was created.
///
/// Also see [HtmlElementView.fromTagName] that uses this callback
/// signature.
typedef ElementCreatedCallback = void Function(Object element);
/// Embeds an HTML element in the Widget hierarchy in Flutter Web.
///
/// *NOTE*: This only works in Flutter Web. To embed web content on other
/// platforms, consider using the `flutter_webview` plugin.
///
/// Embedding HTML is an expensive operation and should be avoided when a
/// Flutter equivalent is possible.
///
/// The embedded HTML is painted just like any other Flutter widget and
/// transformations apply to it as well. This widget should only be used in
/// Flutter Web.
///
/// {@macro flutter.widgets.AndroidView.layout}
///
/// Due to security restrictions with cross-origin `<iframe>` elements, Flutter
/// cannot dispatch pointer events to an HTML view. If an `<iframe>` is the
/// target of an event, the window containing the `<iframe>` is not notified
/// of the event. In particular, this means that any pointer events which land
/// on an `<iframe>` will not be seen by Flutter, and so the HTML view cannot
/// participate in gesture detection with other widgets.
///
/// The way we enable accessibility on Flutter for web is to have a full-page
/// button which waits for a double tap. Placing this full-page button in front
/// of the scene would cause platform views not to receive pointer events. The
/// tradeoff is that by placing the scene in front of the semantics placeholder
/// will cause platform views to block pointer events from reaching the
/// placeholder. This means that in order to enable accessibility, you must
/// double tap the app *outside of a platform view*. As a consequence, a
/// full-screen platform view will make it impossible to enable accessibility.
/// Make sure that your HTML views are sized no larger than necessary, or you
/// may cause difficulty for users trying to enable accessibility.
///
/// {@macro flutter.widgets.AndroidView.lifetime}
class HtmlElementView extends StatelessWidget {
/// Creates a platform view for Flutter Web.
///
/// `viewType` identifies the type of platform view to create.
const HtmlElementView({
super.key,
required this.viewType,
this.onPlatformViewCreated,
this.creationParams,
});
/// Creates a platform view that creates a DOM element specified by [tagName].
///
/// [isVisible] indicates whether the view is visible to the user or not.
/// Setting this to false allows the rendering pipeline to perform extra
/// optimizations knowing that the view will not result in any pixels painted
/// on the screen.
///
/// [onElementCreated] is called when the DOM element is created. It can be
/// used by the app to customize the element by adding attributes and styles.
factory HtmlElementView.fromTagName({
Key? key,
required String tagName,
bool isVisible = true,
ElementCreatedCallback? onElementCreated,
}) =>
HtmlElementViewImpl.createFromTagName(
key: key,
tagName: tagName,
isVisible: isVisible,
onElementCreated: onElementCreated,
);
/// The unique identifier for the HTML view type to be embedded by this widget.
///
/// A PlatformViewFactory for this type must have been registered.
final String viewType;
/// Callback to invoke after the platform view has been created.
///
/// May be null.
final PlatformViewCreatedCallback? onPlatformViewCreated;
/// Passed as the 2nd argument (i.e. `params`) of the registered view factory.
final Object? creationParams;
@override
Widget build(BuildContext context) => buildImpl(context);
}
class _AndroidViewState extends State<AndroidView> {
int? _id;
late AndroidViewController _controller;
TextDirection? _layoutDirection;
bool _initialized = false;
FocusNode? _focusNode;
static final Set<Factory<OneSequenceGestureRecognizer>> _emptyRecognizersSet =
<Factory<OneSequenceGestureRecognizer>>{};
@override
Widget build(BuildContext context) {
return Focus(
focusNode: _focusNode,
onFocusChange: _onFocusChange,
child: _AndroidPlatformView(
controller: _controller,
hitTestBehavior: widget.hitTestBehavior,
gestureRecognizers: widget.gestureRecognizers ?? _emptyRecognizersSet,
clipBehavior: widget.clipBehavior,
),
);
}
void _initializeOnce() {
if (_initialized) {
return;
}
_initialized = true;
_createNewAndroidView();
_focusNode = FocusNode(debugLabel: 'AndroidView(id: $_id)');
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final TextDirection newLayoutDirection = _findLayoutDirection();
final bool didChangeLayoutDirection = _layoutDirection != newLayoutDirection;
_layoutDirection = newLayoutDirection;
_initializeOnce();
if (didChangeLayoutDirection) {
// The native view will update asynchronously, in the meantime we don't want
// to block the framework. (so this is intentionally not awaiting).
_controller.setLayoutDirection(_layoutDirection!);
}
}
@override
void didUpdateWidget(AndroidView oldWidget) {
super.didUpdateWidget(oldWidget);
final TextDirection newLayoutDirection = _findLayoutDirection();
final bool didChangeLayoutDirection = _layoutDirection != newLayoutDirection;
_layoutDirection = newLayoutDirection;
if (widget.viewType != oldWidget.viewType) {
_controller.disposePostFrame();
_createNewAndroidView();
return;
}
if (didChangeLayoutDirection) {
_controller.setLayoutDirection(_layoutDirection!);
}
}
TextDirection _findLayoutDirection() {
assert(widget.layoutDirection != null || debugCheckHasDirectionality(context));
return widget.layoutDirection ?? Directionality.of(context);
}
@override
void dispose() {
_controller.dispose();
_focusNode?.dispose();
_focusNode = null;
super.dispose();
}
void _createNewAndroidView() {
_id = platformViewsRegistry.getNextPlatformViewId();
_controller = PlatformViewsService.initAndroidView(
id: _id!,
viewType: widget.viewType,
layoutDirection: _layoutDirection!,
creationParams: widget.creationParams,
creationParamsCodec: widget.creationParamsCodec,
onFocus: () {
_focusNode!.requestFocus();
},
);
if (widget.onPlatformViewCreated != null) {
_controller.addOnPlatformViewCreatedListener(widget.onPlatformViewCreated!);
}
}
void _onFocusChange(bool isFocused) {
if (!_controller.isCreated) {
return;
}
if (!isFocused) {
_controller.clearFocus().catchError((dynamic e) {
if (e is MissingPluginException) {
// We land the framework part of Android platform views keyboard
// support before the engine part. There will be a commit range where
// clearFocus isn't implemented in the engine. When that happens we
// just swallow the error here. Once the engine part is rolled to the
// framework I'll remove this.
// TODO(amirh): remove this once the engine's clearFocus is rolled.
return;
}
});
return;
}
SystemChannels.textInput.invokeMethod<void>(
'TextInput.setPlatformViewClient',
<String, dynamic>{'platformViewId': _id},
).catchError((dynamic e) {
if (e is MissingPluginException) {
// We land the framework part of Android platform views keyboard
// support before the engine part. There will be a commit range where
// setPlatformViewClient isn't implemented in the engine. When that
// happens we just swallow the error here. Once the engine part is
// rolled to the framework I'll remove this.
// TODO(amirh): remove this once the engine's clearFocus is rolled.
return;
}
});
}
}
abstract class _DarwinViewState<PlatformViewT extends _DarwinView, ControllerT extends DarwinPlatformViewController, RenderT extends RenderDarwinPlatformView<ControllerT>, ViewT extends _DarwinPlatformView<ControllerT, RenderT>> extends State<PlatformViewT> {
ControllerT? _controller;
TextDirection? _layoutDirection;
bool _initialized = false;
@visibleForTesting
FocusNode? focusNode;
static final Set<Factory<OneSequenceGestureRecognizer>> _emptyRecognizersSet =
<Factory<OneSequenceGestureRecognizer>>{};
@override
Widget build(BuildContext context) {
final ControllerT? controller = _controller;
if (controller == null) {
return const SizedBox.expand();
}
return Focus(
focusNode: focusNode,
onFocusChange: (bool isFocused) => _onFocusChange(isFocused, controller),
child: childPlatformView()
);
}
ViewT childPlatformView();
void _initializeOnce() {
if (_initialized) {
return;
}
_initialized = true;
_createNewUiKitView();
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final TextDirection newLayoutDirection = _findLayoutDirection();
final bool didChangeLayoutDirection = _layoutDirection != newLayoutDirection;
_layoutDirection = newLayoutDirection;
_initializeOnce();
if (didChangeLayoutDirection) {
// The native view will update asynchronously, in the meantime we don't want
// to block the framework. (so this is intentionally not awaiting).
_controller?.setLayoutDirection(_layoutDirection!);
}
}
@override
void didUpdateWidget(PlatformViewT oldWidget) {
super.didUpdateWidget(oldWidget);
final TextDirection newLayoutDirection = _findLayoutDirection();
final bool didChangeLayoutDirection = _layoutDirection != newLayoutDirection;
_layoutDirection = newLayoutDirection;
if (widget.viewType != oldWidget.viewType) {
_controller?.dispose();
_controller = null;
focusNode?.dispose();
focusNode = null;
_createNewUiKitView();
return;
}
if (didChangeLayoutDirection) {
_controller?.setLayoutDirection(_layoutDirection!);
}
}
TextDirection _findLayoutDirection() {
assert(widget.layoutDirection != null || debugCheckHasDirectionality(context));
return widget.layoutDirection ?? Directionality.of(context);
}
@override
void dispose() {
_controller?.dispose();
_controller = null;
focusNode?.dispose();
focusNode = null;
super.dispose();
}
Future<void> _createNewUiKitView() async {
final int id = platformViewsRegistry.getNextPlatformViewId();
final ControllerT controller = await createNewViewController(
id
);
if (!mounted) {
controller.dispose();
return;
}
widget.onPlatformViewCreated?.call(id);
setState(() {
_controller = controller;
focusNode = FocusNode(debugLabel: 'UiKitView(id: $id)');
});
}
Future<ControllerT> createNewViewController(int id);
void _onFocusChange(bool isFocused, ControllerT controller) {
if (!isFocused) {
// Unlike Android, we do not need to send "clearFocus" channel message
// to the engine, because focusing on another view will automatically
// cancel the focus on the previously focused platform view.
return;
}
SystemChannels.textInput.invokeMethod<void>(
'TextInput.setPlatformViewClient',
<String, dynamic>{'platformViewId': controller.id},
);
}
}
class _UiKitViewState extends _DarwinViewState<UiKitView, UiKitViewController, RenderUiKitView, _UiKitPlatformView> {
@override
Future<UiKitViewController> createNewViewController(int id) async {
return PlatformViewsService.initUiKitView(
id: id,
viewType: widget.viewType,
layoutDirection: _layoutDirection!,
creationParams: widget.creationParams,
creationParamsCodec: widget.creationParamsCodec,
onFocus: () {
focusNode?.requestFocus();
}
);
}
@override
_UiKitPlatformView childPlatformView() {
return _UiKitPlatformView(
controller: _controller!,
hitTestBehavior: widget.hitTestBehavior,
gestureRecognizers: widget.gestureRecognizers ?? _DarwinViewState._emptyRecognizersSet,
);
}
}
class _AppKitViewState extends _DarwinViewState<AppKitView, AppKitViewController, RenderAppKitView, _AppKitPlatformView> {
@override
Future<AppKitViewController> createNewViewController(int id) async {
return PlatformViewsService.initAppKitView(
id: id,
viewType: widget.viewType,
layoutDirection: _layoutDirection!,
creationParams: widget.creationParams,
creationParamsCodec: widget.creationParamsCodec,
onFocus: () {
focusNode?.requestFocus();
}
);
}
@override
_AppKitPlatformView childPlatformView() {
return _AppKitPlatformView(
controller: _controller!,
hitTestBehavior: widget.hitTestBehavior,
gestureRecognizers: widget.gestureRecognizers ?? _DarwinViewState._emptyRecognizersSet,
);
}
}
class _AndroidPlatformView extends LeafRenderObjectWidget {
const _AndroidPlatformView({
required this.controller,
required this.hitTestBehavior,
required this.gestureRecognizers,
this.clipBehavior = Clip.hardEdge,
});
final AndroidViewController controller;
final PlatformViewHitTestBehavior hitTestBehavior;
final Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers;
final Clip clipBehavior;
@override
RenderObject createRenderObject(BuildContext context) =>
RenderAndroidView(
viewController: controller,
hitTestBehavior: hitTestBehavior,
gestureRecognizers: gestureRecognizers,
clipBehavior: clipBehavior,
);
@override
void updateRenderObject(BuildContext context, RenderAndroidView renderObject) {
renderObject.controller = controller;
renderObject.hitTestBehavior = hitTestBehavior;
renderObject.updateGestureRecognizers(gestureRecognizers);
renderObject.clipBehavior = clipBehavior;
}
}
abstract class _DarwinPlatformView<TController extends DarwinPlatformViewController, TRender extends RenderDarwinPlatformView<TController>> extends LeafRenderObjectWidget {
const _DarwinPlatformView({
required this.controller,
required this.hitTestBehavior,
required this.gestureRecognizers,
});
final TController controller;
final PlatformViewHitTestBehavior hitTestBehavior;
final Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers;
@override
@mustCallSuper
void updateRenderObject(BuildContext context, TRender renderObject) {
renderObject
..viewController = controller
..hitTestBehavior = hitTestBehavior
..updateGestureRecognizers(gestureRecognizers);
}
}
class _UiKitPlatformView extends _DarwinPlatformView<UiKitViewController, RenderUiKitView> {
const _UiKitPlatformView({required super.controller, required super.hitTestBehavior, required super.gestureRecognizers});
@override
RenderObject createRenderObject(BuildContext context) {
return RenderUiKitView(
viewController: controller,
hitTestBehavior: hitTestBehavior,
gestureRecognizers: gestureRecognizers,
);
}
}
class _AppKitPlatformView extends _DarwinPlatformView<AppKitViewController, RenderAppKitView> {
const _AppKitPlatformView({required super.controller, required super.hitTestBehavior, required super.gestureRecognizers});
@override
RenderObject createRenderObject(BuildContext context) {
return RenderAppKitView(
viewController: controller,
hitTestBehavior: hitTestBehavior,
gestureRecognizers: gestureRecognizers,
);
}
}
/// The parameters used to create a [PlatformViewController].
///
/// See also:
///
/// * [CreatePlatformViewCallback] which uses this object to create a [PlatformViewController].
class PlatformViewCreationParams {
const PlatformViewCreationParams._({
required this.id,
required this.viewType,
required this.onPlatformViewCreated,
required this.onFocusChanged,
});
/// The unique identifier for the new platform view.
///
/// [PlatformViewController.viewId] should match this id.
final int id;
/// The unique identifier for the type of platform view to be embedded.
///
/// This viewType is used to tell the platform which type of view to
/// associate with the [id].
final String viewType;
/// Callback invoked after the platform view has been created.
final PlatformViewCreatedCallback onPlatformViewCreated;
/// Callback invoked when the platform view's focus is changed on the platform side.
///
/// The value is true when the platform view gains focus and false when it loses focus.
final ValueChanged<bool> onFocusChanged;
}
/// A factory for a surface presenting a platform view as part of the widget hierarchy.
///
/// The returned widget should present the platform view associated with `controller`.
///
/// See also:
///
/// * [PlatformViewSurface], a common widget for presenting platform views.
typedef PlatformViewSurfaceFactory = Widget Function(BuildContext context, PlatformViewController controller);
/// Constructs a [PlatformViewController].
///
/// The [PlatformViewController.viewId] field of the created controller must match the value of the
/// params [PlatformViewCreationParams.id] field.
///
/// See also:
///
/// * [PlatformViewLink], which links a platform view with the Flutter framework.
typedef CreatePlatformViewCallback = PlatformViewController Function(PlatformViewCreationParams params);
/// Links a platform view with the Flutter framework.
///
/// Provides common functionality for embedding a platform view (e.g an android.view.View on Android)
/// with the Flutter framework.
///
/// {@macro flutter.widgets.AndroidView.lifetime}
///
/// To implement a new platform view widget, return this widget in the `build` method.
/// For example:
///
/// ```dart
/// class FooPlatformView extends StatelessWidget {
/// const FooPlatformView({super.key});
/// @override
/// Widget build(BuildContext context) {
/// return PlatformViewLink(
/// viewType: 'webview',
/// onCreatePlatformView: createFooWebView,
/// surfaceFactory: (BuildContext context, PlatformViewController controller) {
/// return PlatformViewSurface(
/// gestureRecognizers: gestureRecognizers,
/// controller: controller,
/// hitTestBehavior: PlatformViewHitTestBehavior.opaque,
/// );
/// },
/// );
/// }
/// }
/// ```
///
/// The `surfaceFactory` and the `onCreatePlatformView` are only called when the
/// state of this widget is initialized, or when the `viewType` changes.
class PlatformViewLink extends StatefulWidget {
/// Construct a [PlatformViewLink] widget.
///
/// See also:
///
/// * [PlatformViewSurface] for details on the widget returned by `surfaceFactory`.
/// * [PlatformViewCreationParams] for how each parameter can be used when implementing `createPlatformView`.
const PlatformViewLink({
super.key,
required PlatformViewSurfaceFactory surfaceFactory,
required CreatePlatformViewCallback onCreatePlatformView,
required this.viewType,
}) : _surfaceFactory = surfaceFactory,
_onCreatePlatformView = onCreatePlatformView;
final PlatformViewSurfaceFactory _surfaceFactory;
final CreatePlatformViewCallback _onCreatePlatformView;
/// The unique identifier for the view type to be embedded.
///
/// Typically, this viewType has already been registered on the platform side.
final String viewType;
@override
State<StatefulWidget> createState() => _PlatformViewLinkState();
}
class _PlatformViewLinkState extends State<PlatformViewLink> {
int? _id;
PlatformViewController? _controller;
bool _platformViewCreated = false;
Widget? _surface;
FocusNode? _focusNode;
@override
Widget build(BuildContext context) {
final PlatformViewController? controller = _controller;
if (controller == null) {
return const SizedBox.expand();
}
if (!_platformViewCreated) {
// Depending on the implementation, the first non-empty size can be used
// to size the platform view.
return _PlatformViewPlaceHolder(onLayout: (Size size, Offset position) {
if (controller.awaitingCreation && !size.isEmpty) {
controller.create(size: size, position: position);
}
});
}
_surface ??= widget._surfaceFactory(context, controller);
return Focus(
focusNode: _focusNode,
onFocusChange: _handleFrameworkFocusChanged,
child: _surface!,
);
}
@override
void initState() {
_focusNode = FocusNode(debugLabel: 'PlatformView(id: $_id)');
_initialize();
super.initState();
}
@override
void didUpdateWidget(PlatformViewLink oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.viewType != oldWidget.viewType) {
_controller?.disposePostFrame();
// The _surface has to be recreated as its controller is disposed.
// Setting _surface to null will trigger its creation in build().
_surface = null;
_initialize();
}
}
void _initialize() {
_id = platformViewsRegistry.getNextPlatformViewId();
_controller = widget._onCreatePlatformView(
PlatformViewCreationParams._(
id: _id!,
viewType: widget.viewType,
onPlatformViewCreated: _onPlatformViewCreated,
onFocusChanged: _handlePlatformFocusChanged,
),
);
}
void _onPlatformViewCreated(int id) {
if (mounted) {
setState(() {
_platformViewCreated = true;
});
}
}
void _handleFrameworkFocusChanged(bool isFocused) {
if (!isFocused) {
_controller?.clearFocus();
}
SystemChannels.textInput.invokeMethod<void>(
'TextInput.setPlatformViewClient',
<String, dynamic>{'platformViewId': _id},
);
}
void _handlePlatformFocusChanged(bool isFocused) {
if (isFocused) {
_focusNode!.requestFocus();
}
}
@override
void dispose() {
_controller?.dispose();
_controller = null;
_focusNode?.dispose();
_focusNode = null;
super.dispose();
}
}
/// Integrates a platform view with Flutter's compositor, touch, and semantics subsystems.
///
/// The compositor integration is done by adding a [PlatformViewLayer] to the layer tree. [PlatformViewSurface]
/// isn't supported on all platforms (e.g on Android platform views can be composited by using a [TextureLayer] or
/// [AndroidViewSurface]).
/// Custom Flutter embedders can support [PlatformViewLayer]s by implementing a SystemCompositor.
///
/// The widget fills all available space, the parent of this object must provide bounded layout
/// constraints.
///
/// If the associated platform view is not created the [PlatformViewSurface] does not paint any contents.
///
/// See also:
///
/// * [AndroidView] which embeds an Android platform view in the widget hierarchy using a [TextureLayer].
/// * [UiKitView] which embeds an iOS platform view in the widget hierarchy.
// TODO(amirh): Link to the embedder's system compositor documentation once available.
class PlatformViewSurface extends LeafRenderObjectWidget {
/// Construct a [PlatformViewSurface].
const PlatformViewSurface({
super.key,
required this.controller,
required this.hitTestBehavior,
required this.gestureRecognizers,
});
/// The controller for the platform view integrated by this [PlatformViewSurface].
///
/// [PlatformViewController] is used for dispatching touch events to the platform view.
/// [PlatformViewController.viewId] identifies the platform view whose contents are painted by this widget.
final PlatformViewController controller;
/// Which gestures should be forwarded to the PlatformView.
///
/// {@macro flutter.widgets.AndroidView.gestureRecognizers.descHead}
///
/// For example, with the following setup vertical drags will not be dispatched to the platform view
/// as the vertical drag gesture is claimed by the parent [GestureDetector].
///
/// ```dart
/// GestureDetector(
/// onVerticalDragStart: (DragStartDetails details) { },
/// child: PlatformViewSurface(
/// gestureRecognizers: const <Factory<OneSequenceGestureRecognizer>>{},
/// controller: _controller,
/// hitTestBehavior: PlatformViewHitTestBehavior.opaque,
/// ),
/// )
/// ```
///
/// To get the [PlatformViewSurface] to claim the vertical drag gestures we can pass a vertical drag
/// gesture recognizer factory in [gestureRecognizers] e.g:
///
/// ```dart
/// GestureDetector(
/// onVerticalDragStart: (DragStartDetails details) { },
/// child: SizedBox(
/// width: 200.0,
/// height: 100.0,
/// child: PlatformViewSurface(
/// gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>{
/// Factory<OneSequenceGestureRecognizer>(
/// () => EagerGestureRecognizer(),
/// ),
/// },
/// controller: _controller,
/// hitTestBehavior: PlatformViewHitTestBehavior.opaque,
/// ),
/// ),
/// )
/// ```
///
/// {@macro flutter.widgets.AndroidView.gestureRecognizers.descFoot}
// We use OneSequenceGestureRecognizers as they support gesture arena teams.
// TODO(amirh): get a list of GestureRecognizers here.
// https://github.com/flutter/flutter/issues/20953
final Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers;
/// {@macro flutter.widgets.AndroidView.hitTestBehavior}
final PlatformViewHitTestBehavior hitTestBehavior;
@override
RenderObject createRenderObject(BuildContext context) {
return PlatformViewRenderBox(controller: controller, gestureRecognizers: gestureRecognizers, hitTestBehavior: hitTestBehavior);
}
@override
void updateRenderObject(BuildContext context, PlatformViewRenderBox renderObject) {
renderObject
..controller = controller
..hitTestBehavior = hitTestBehavior
..updateGestureRecognizers(gestureRecognizers);
}
}
/// Integrates an Android view with Flutter's compositor, touch, and semantics subsystems.
///
/// The compositor integration is done by adding a [TextureLayer] to the layer tree.
///
/// The parent of this object must provide bounded layout constraints.
///
/// If the associated platform view is not created, the [AndroidViewSurface] does not paint any contents.
///
/// When possible, you may want to use [AndroidView] directly, since it requires less boilerplate code
/// than [AndroidViewSurface], and there's no difference in performance, or other trade-off(s).
///
/// See also:
///
/// * [AndroidView] which embeds an Android platform view in the widget hierarchy.
/// * [UiKitView] which embeds an iOS platform view in the widget hierarchy.
class AndroidViewSurface extends StatefulWidget {
/// Construct an `AndroidPlatformViewSurface`.
const AndroidViewSurface({
super.key,
required this.controller,
required this.hitTestBehavior,
required this.gestureRecognizers,
});
/// The controller for the platform view integrated by this [AndroidViewSurface].
///
/// See [PlatformViewSurface.controller] for details.
final AndroidViewController controller;
/// Which gestures should be forwarded to the PlatformView.
///
/// See [PlatformViewSurface.gestureRecognizers] for details.
final Set<Factory<OneSequenceGestureRecognizer>> gestureRecognizers;
/// {@macro flutter.widgets.AndroidView.hitTestBehavior}
final PlatformViewHitTestBehavior hitTestBehavior;
@override
State<StatefulWidget> createState() {
return _AndroidViewSurfaceState();
}
}
class _AndroidViewSurfaceState extends State<AndroidViewSurface> {
@override
void initState() {
super.initState();
if (!widget.controller.isCreated) {
// Schedule a rebuild once creation is complete and the final display
// type is known.
widget.controller.addOnPlatformViewCreatedListener(_onPlatformViewCreated);
}
}
@override
void dispose() {
widget.controller.removeOnPlatformViewCreatedListener(_onPlatformViewCreated);
super.dispose();
}
@override
Widget build(BuildContext context) {
if (widget.controller.requiresViewComposition) {
return _PlatformLayerBasedAndroidViewSurface(
controller: widget.controller,
hitTestBehavior: widget.hitTestBehavior,
gestureRecognizers: widget.gestureRecognizers,
);
} else {
return _TextureBasedAndroidViewSurface(
controller: widget.controller,
hitTestBehavior: widget.hitTestBehavior,
gestureRecognizers: widget.gestureRecognizers,
);
}
}
void _onPlatformViewCreated(int _) {
// Trigger a re-build based on the current controller state.
setState(() {});
}
}
// Displays an Android platform view via GL texture.
class _TextureBasedAndroidViewSurface extends PlatformViewSurface {
const _TextureBasedAndroidViewSurface({
required AndroidViewController super.controller,
required super.hitTestBehavior,
required super.gestureRecognizers,
});
@override
RenderObject createRenderObject(BuildContext context) {
final AndroidViewController viewController = controller as AndroidViewController;
// Use GL texture based composition.
// App should use GL texture unless they require to embed a SurfaceView.
final RenderAndroidView renderBox = RenderAndroidView(
viewController: viewController,
gestureRecognizers: gestureRecognizers,
hitTestBehavior: hitTestBehavior,
);
viewController.pointTransformer =
(Offset position) => renderBox.globalToLocal(position);
return renderBox;
}
}
class _PlatformLayerBasedAndroidViewSurface extends PlatformViewSurface {
const _PlatformLayerBasedAndroidViewSurface({
required AndroidViewController super.controller,
required super.hitTestBehavior,
required super.gestureRecognizers,
});
@override
RenderObject createRenderObject(BuildContext context) {
final AndroidViewController viewController = controller as AndroidViewController;
final PlatformViewRenderBox renderBox =
super.createRenderObject(context) as PlatformViewRenderBox;
viewController.pointTransformer =
(Offset position) => renderBox.globalToLocal(position);
return renderBox;
}
}
/// A callback used to notify the size of the platform view placeholder.
/// This size is the initial size of the platform view.
typedef _OnLayoutCallback = void Function(Size size, Offset position);
/// A [RenderBox] that notifies its size to the owner after a layout.
class _PlatformViewPlaceholderBox extends RenderConstrainedBox {
_PlatformViewPlaceholderBox({
required this.onLayout,
}) : super(additionalConstraints: const BoxConstraints.tightFor(
width: double.infinity,
height: double.infinity,
));
_OnLayoutCallback onLayout;
@override
void performLayout() {
super.performLayout();
// A call to `localToGlobal` requires waiting for a frame to render first.
SchedulerBinding.instance.addPostFrameCallback((_) {
onLayout(size, localToGlobal(Offset.zero));
}, debugLabel: 'PlatformViewPlaceholderBox.onLayout');
}
}
/// When a platform view is in the widget hierarchy, this widget is used to capture
/// the size of the platform view after the first layout.
/// This placeholder is basically a [SizedBox.expand] with a [onLayout] callback to
/// notify the size of the render object to its parent.
class _PlatformViewPlaceHolder extends SingleChildRenderObjectWidget {
const _PlatformViewPlaceHolder({
required this.onLayout,
});
final _OnLayoutCallback onLayout;
@override
_PlatformViewPlaceholderBox createRenderObject(BuildContext context) {
return _PlatformViewPlaceholderBox(onLayout: onLayout);
}
@override
void updateRenderObject(BuildContext context, _PlatformViewPlaceholderBox renderObject) {
renderObject.onLayout = onLayout;
}
}
extension on PlatformViewController {
/// Disposes the controller in a post-frame callback, to allow other widgets to
/// remove their listeners before the controller is disposed.
void disposePostFrame() {
SchedulerBinding.instance.addPostFrameCallback((_) {
dispose();
}, debugLabel: 'PlatformViewController.dispose');
}
}
| flutter/packages/flutter/lib/src/widgets/platform_view.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/platform_view.dart",
"repo_id": "flutter",
"token_count": 14696
} | 646 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'automatic_keep_alive.dart';
import 'basic.dart';
import 'framework.dart';
import 'selection_container.dart';
import 'two_dimensional_viewport.dart';
export 'package:flutter/rendering.dart' show
SliverGridDelegate,
SliverGridDelegateWithFixedCrossAxisCount,
SliverGridDelegateWithMaxCrossAxisExtent;
// Examples can assume:
// late SliverGridDelegateWithMaxCrossAxisExtent _gridDelegate;
// abstract class SomeWidget extends StatefulWidget { const SomeWidget({super.key}); }
// typedef ChildWidget = Placeholder;
/// A callback which produces a semantic index given a widget and the local index.
///
/// Return a null value to prevent a widget from receiving an index.
///
/// A semantic index is used to tag child semantic nodes for accessibility
/// announcements in scroll view.
///
/// See also:
///
/// * [CustomScrollView], for an explanation of scroll semantics.
/// * [SliverChildBuilderDelegate], for an explanation of how this is used to
/// generate indexes.
typedef SemanticIndexCallback = int? Function(Widget widget, int localIndex);
int _kDefaultSemanticIndexCallback(Widget _, int localIndex) => localIndex;
/// A delegate that supplies children for slivers.
///
/// Many slivers lazily construct their box children to avoid creating more
/// children than are visible through the [Viewport]. Rather than receiving
/// their children as an explicit [List], they receive their children using a
/// [SliverChildDelegate].
///
/// It's uncommon to subclass [SliverChildDelegate]. Instead, consider using one
/// of the existing subclasses that provide adaptors to builder callbacks or
/// explicit child lists.
///
/// {@template flutter.widgets.SliverChildDelegate.lifecycle}
/// ## Child elements' lifecycle
///
/// ### Creation
///
/// While laying out the list, visible children's elements, states and render
/// objects will be created lazily based on existing widgets (such as in the
/// case of [SliverChildListDelegate]) or lazily provided ones (such as in the
/// case of [SliverChildBuilderDelegate]).
///
/// ### Destruction
///
/// When a child is scrolled out of view, the associated element subtree, states
/// and render objects are destroyed. A new child at the same position in the
/// sliver will be lazily recreated along with new elements, states and render
/// objects when it is scrolled back.
///
/// ### Destruction mitigation
///
/// In order to preserve state as child elements are scrolled in and out of
/// view, the following options are possible:
///
/// * Moving the ownership of non-trivial UI-state-driving business logic
/// out of the sliver child subtree. For instance, if a list contains posts
/// with their number of upvotes coming from a cached network response, store
/// the list of posts and upvote number in a data model outside the list. Let
/// the sliver child UI subtree be easily recreate-able from the
/// source-of-truth model object. Use [StatefulWidget]s in the child widget
/// subtree to store instantaneous UI state only.
///
/// * Letting [KeepAlive] be the root widget of the sliver child widget subtree
/// that needs to be preserved. The [KeepAlive] widget marks the child
/// subtree's top render object child for keepalive. When the associated top
/// render object is scrolled out of view, the sliver keeps the child's
/// render object (and by extension, its associated elements and states) in a
/// cache list instead of destroying them. When scrolled back into view, the
/// render object is repainted as-is (if it wasn't marked dirty in the
/// interim).
///
/// This only works if the [SliverChildDelegate] subclasses don't wrap the
/// child widget subtree with other widgets such as [AutomaticKeepAlive] and
/// [RepaintBoundary] via `addAutomaticKeepAlives` and
/// `addRepaintBoundaries`.
///
/// * Using [AutomaticKeepAlive] widgets (inserted by default in
/// [SliverChildListDelegate] or [SliverChildListDelegate]).
/// [AutomaticKeepAlive] allows descendant widgets to control whether the
/// subtree is actually kept alive or not. This behavior is in contrast with
/// [KeepAlive], which will unconditionally keep the subtree alive.
///
/// As an example, the [EditableText] widget signals its sliver child element
/// subtree to stay alive while its text field has input focus. If it doesn't
/// have focus and no other descendants signaled for keepalive via a
/// [KeepAliveNotification], the sliver child element subtree will be
/// destroyed when scrolled away.
///
/// [AutomaticKeepAlive] descendants typically signal it to be kept alive by
/// using the [AutomaticKeepAliveClientMixin], then implementing the
/// [AutomaticKeepAliveClientMixin.wantKeepAlive] getter and calling
/// [AutomaticKeepAliveClientMixin.updateKeepAlive].
///
/// ## Using more than one delegate in a [Viewport]
///
/// If multiple delegates are used in a single scroll view, the first child of
/// each delegate will always be laid out, even if it extends beyond the
/// currently viewable area. This is because at least one child is required in
/// order to [estimateMaxScrollOffset] for the whole scroll view, as it uses the
/// currently built children to estimate the remaining children's extent.
/// {@endtemplate}
///
/// See also:
///
/// * [SliverChildBuilderDelegate], which is a delegate that uses a builder
/// callback to construct the children.
/// * [SliverChildListDelegate], which is a delegate that has an explicit list
/// of children.
abstract class SliverChildDelegate {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const SliverChildDelegate();
/// Returns the child with the given index.
///
/// Should return null if asked to build a widget with a greater
/// index than exists. If this returns null, [estimatedChildCount]
/// must subsequently return a precise non-null value (which is then
/// used to implement [RenderSliverBoxChildManager.childCount]).
///
/// Subclasses typically override this function and wrap their children in
/// [AutomaticKeepAlive], [IndexedSemantics], and [RepaintBoundary] widgets.
///
/// The values returned by this method are cached. To indicate that the
/// widgets have changed, a new delegate must be provided, and the new
/// delegate's [shouldRebuild] method must return true.
Widget? build(BuildContext context, int index);
/// Returns an estimate of the number of children this delegate will build.
///
/// Used to estimate the maximum scroll offset if [estimateMaxScrollOffset]
/// returns null.
///
/// Return null if there are an unbounded number of children or if it would
/// be too difficult to estimate the number of children.
///
/// This must return a precise number once [build] has returned null, as it
/// used to implement [RenderSliverBoxChildManager.childCount].
int? get estimatedChildCount => null;
/// Returns an estimate of the max scroll extent for all the children.
///
/// Subclasses should override this function if they have additional
/// information about their max scroll extent.
///
/// The default implementation returns null, which causes the caller to
/// extrapolate the max scroll offset from the given parameters.
double? estimateMaxScrollOffset(
int firstIndex,
int lastIndex,
double leadingScrollOffset,
double trailingScrollOffset,
) => null;
/// Called at the end of layout to indicate that layout is now complete.
///
/// The `firstIndex` argument is the index of the first child that was
/// included in the current layout. The `lastIndex` argument is the index of
/// the last child that was included in the current layout.
///
/// Useful for subclasses that which to track which children are included in
/// the underlying render tree.
void didFinishLayout(int firstIndex, int lastIndex) { }
/// Called whenever a new instance of the child delegate class is
/// provided to the sliver.
///
/// If the new instance represents different information than the old
/// instance, then the method should return true, otherwise it should return
/// false.
///
/// If the method returns false, then the [build] call might be optimized
/// away.
bool shouldRebuild(covariant SliverChildDelegate oldDelegate);
/// Find index of child element with associated key.
///
/// This will be called during `performRebuild` in [SliverMultiBoxAdaptorElement]
/// to check if a child has moved to a different position. It should return the
/// index of the child element with associated key, null if not found.
///
/// If not provided, a child widget may not map to its existing [RenderObject]
/// when the order of children returned from the children builder changes.
/// This may result in state-loss.
int? findIndexByKey(Key key) => null;
@override
String toString() {
final List<String> description = <String>[];
debugFillDescription(description);
return '${describeIdentity(this)}(${description.join(", ")})';
}
/// Add additional information to the given description for use by [toString].
@protected
@mustCallSuper
void debugFillDescription(List<String> description) {
try {
final int? children = estimatedChildCount;
if (children != null) {
description.add('estimated child count: $children');
}
} catch (e) {
// The exception is forwarded to widget inspector.
description.add('estimated child count: EXCEPTION (${e.runtimeType})');
}
}
}
class _SaltedValueKey extends ValueKey<Key> {
const _SaltedValueKey(super.value);
}
/// Called to find the new index of a child based on its `key` in case of
/// reordering.
///
/// If the child with the `key` is no longer present, null is returned.
///
/// Used by [SliverChildBuilderDelegate.findChildIndexCallback].
typedef ChildIndexGetter = int? Function(Key key);
/// A delegate that supplies children for slivers using a builder callback.
///
/// Many slivers lazily construct their box children to avoid creating more
/// children than are visible through the [Viewport]. This delegate provides
/// children using a [NullableIndexedWidgetBuilder] callback, so that the children do
/// not even have to be built until they are displayed.
///
/// The widgets returned from the builder callback are automatically wrapped in
/// [AutomaticKeepAlive] widgets if [addAutomaticKeepAlives] is true (the
/// default) and in [RepaintBoundary] widgets if [addRepaintBoundaries] is true
/// (also the default).
///
/// ## Accessibility
///
/// The [CustomScrollView] requires that its semantic children are annotated
/// using [IndexedSemantics]. This is done by default in the delegate with
/// the `addSemanticIndexes` parameter set to true.
///
/// If multiple delegates are used in a single scroll view, then the indexes
/// will not be correct by default. The `semanticIndexOffset` can be used to
/// offset the semantic indexes of each delegate so that the indexes are
/// monotonically increasing. For example, if a scroll view contains two
/// delegates where the first has 10 children contributing semantics, then the
/// second delegate should offset its children by 10.
///
/// {@tool snippet}
///
/// This sample code shows how to use `semanticIndexOffset` to handle multiple
/// delegates in a single scroll view.
///
/// ```dart
/// CustomScrollView(
/// semanticChildCount: 4,
/// slivers: <Widget>[
/// SliverGrid(
/// gridDelegate: _gridDelegate,
/// delegate: SliverChildBuilderDelegate(
/// (BuildContext context, int index) {
/// return const Text('...');
/// },
/// childCount: 2,
/// ),
/// ),
/// SliverGrid(
/// gridDelegate: _gridDelegate,
/// delegate: SliverChildBuilderDelegate(
/// (BuildContext context, int index) {
/// return const Text('...');
/// },
/// childCount: 2,
/// semanticIndexOffset: 2,
/// ),
/// ),
/// ],
/// )
/// ```
/// {@end-tool}
///
/// In certain cases, only a subset of child widgets should be annotated
/// with a semantic index. For example, in [ListView.separated()] the
/// separators do not have an index associated with them. This is done by
/// providing a `semanticIndexCallback` which returns null for separators
/// indexes and rounds the non-separator indexes down by half.
///
/// {@tool snippet}
///
/// This sample code shows how to use `semanticIndexCallback` to handle
/// annotating a subset of child nodes with a semantic index. There is
/// a [Spacer] widget at odd indexes which should not have a semantic
/// index.
///
/// ```dart
/// CustomScrollView(
/// semanticChildCount: 5,
/// slivers: <Widget>[
/// SliverGrid(
/// gridDelegate: _gridDelegate,
/// delegate: SliverChildBuilderDelegate(
/// (BuildContext context, int index) {
/// if (index.isEven) {
/// return const Text('...');
/// }
/// return const Spacer();
/// },
/// semanticIndexCallback: (Widget widget, int localIndex) {
/// if (localIndex.isEven) {
/// return localIndex ~/ 2;
/// }
/// return null;
/// },
/// childCount: 10,
/// ),
/// ),
/// ],
/// )
/// ```
/// {@end-tool}
///
/// See also:
///
/// * [SliverChildListDelegate], which is a delegate that has an explicit list
/// of children.
/// * [IndexedSemantics], for an example of manually annotating child nodes
/// with semantic indexes.
class SliverChildBuilderDelegate extends SliverChildDelegate {
/// Creates a delegate that supplies children for slivers using the given
/// builder callback.
///
/// The [builder], [addAutomaticKeepAlives], [addRepaintBoundaries],
/// [addSemanticIndexes], and [semanticIndexCallback] arguments must not be
/// null.
///
/// If the order in which [builder] returns children ever changes, consider
/// providing a [findChildIndexCallback]. This allows the delegate to find the
/// new index for a child that was previously located at a different index to
/// attach the existing state to the [Widget] at its new location.
const SliverChildBuilderDelegate(
this.builder, {
this.findChildIndexCallback,
this.childCount,
this.addAutomaticKeepAlives = true,
this.addRepaintBoundaries = true,
this.addSemanticIndexes = true,
this.semanticIndexCallback = _kDefaultSemanticIndexCallback,
this.semanticIndexOffset = 0,
});
/// Called to build children for the sliver.
///
/// Will be called only for indices greater than or equal to zero and less
/// than [childCount] (if [childCount] is non-null).
///
/// Should return null if asked to build a widget with a greater index than
/// exists.
///
/// May result in an infinite loop or run out of memory if [childCount] is null
/// and the [builder] always provides a zero-size widget (such as `Container()`
/// or `SizedBox.shrink()`). If possible, provide children with non-zero size,
/// return null from [builder], or set a [childCount].
///
/// The delegate wraps the children returned by this builder in
/// [RepaintBoundary] widgets.
final NullableIndexedWidgetBuilder builder;
/// The total number of children this delegate can provide.
///
/// If null, the number of children is determined by the least index for which
/// [builder] returns null.
///
/// May result in an infinite loop or run out of memory if [childCount] is null
/// and the [builder] always provides a zero-size widget (such as `Container()`
/// or `SizedBox.shrink()`). If possible, provide children with non-zero size,
/// return null from [builder], or set a [childCount].
final int? childCount;
/// {@template flutter.widgets.SliverChildBuilderDelegate.addAutomaticKeepAlives}
/// Whether to wrap each child in an [AutomaticKeepAlive].
///
/// Typically, lazily laid out children are wrapped in [AutomaticKeepAlive]
/// widgets so that the children can use [KeepAliveNotification]s to preserve
/// their state when they would otherwise be garbage collected off-screen.
///
/// This feature (and [addRepaintBoundaries]) must be disabled if the children
/// are going to manually maintain their [KeepAlive] state. It may also be
/// more efficient to disable this feature if it is known ahead of time that
/// none of the children will ever try to keep themselves alive.
///
/// Defaults to true.
/// {@endtemplate}
final bool addAutomaticKeepAlives;
/// {@template flutter.widgets.SliverChildBuilderDelegate.addRepaintBoundaries}
/// Whether to wrap each child in a [RepaintBoundary].
///
/// Typically, children in a scrolling container are wrapped in repaint
/// boundaries so that they do not need to be repainted as the list scrolls.
/// If the children are easy to repaint (e.g., solid color blocks or a short
/// snippet of text), it might be more efficient to not add a repaint boundary
/// and instead always repaint the children during scrolling.
///
/// Defaults to true.
/// {@endtemplate}
final bool addRepaintBoundaries;
/// {@template flutter.widgets.SliverChildBuilderDelegate.addSemanticIndexes}
/// Whether to wrap each child in an [IndexedSemantics].
///
/// Typically, children in a scrolling container must be annotated with a
/// semantic index in order to generate the correct accessibility
/// announcements. This should only be set to false if the indexes have
/// already been provided by an [IndexedSemantics] widget.
///
/// Defaults to true.
///
/// See also:
///
/// * [IndexedSemantics], for an explanation of how to manually
/// provide semantic indexes.
/// {@endtemplate}
final bool addSemanticIndexes;
/// {@template flutter.widgets.SliverChildBuilderDelegate.semanticIndexOffset}
/// An initial offset to add to the semantic indexes generated by this widget.
///
/// Defaults to zero.
/// {@endtemplate}
final int semanticIndexOffset;
/// {@template flutter.widgets.SliverChildBuilderDelegate.semanticIndexCallback}
/// A [SemanticIndexCallback] which is used when [addSemanticIndexes] is true.
///
/// Defaults to providing an index for each widget.
/// {@endtemplate}
final SemanticIndexCallback semanticIndexCallback;
/// {@template flutter.widgets.SliverChildBuilderDelegate.findChildIndexCallback}
/// Called to find the new index of a child based on its key in case of reordering.
///
/// If not provided, a child widget may not map to its existing [RenderObject]
/// when the order of children returned from the children builder changes.
/// This may result in state-loss.
///
/// This callback should take an input [Key], and it should return the
/// index of the child element with that associated key, or null if not found.
/// {@endtemplate}
final ChildIndexGetter? findChildIndexCallback;
@override
int? findIndexByKey(Key key) {
if (findChildIndexCallback == null) {
return null;
}
final Key childKey;
if (key is _SaltedValueKey) {
final _SaltedValueKey saltedValueKey = key;
childKey = saltedValueKey.value;
} else {
childKey = key;
}
return findChildIndexCallback!(childKey);
}
@override
@pragma('vm:notify-debugger-on-exception')
Widget? build(BuildContext context, int index) {
if (index < 0 || (childCount != null && index >= childCount!)) {
return null;
}
Widget? child;
try {
child = builder(context, index);
} catch (exception, stackTrace) {
child = _createErrorWidget(exception, stackTrace);
}
if (child == null) {
return null;
}
final Key? key = child.key != null ? _SaltedValueKey(child.key!) : null;
if (addRepaintBoundaries) {
child = RepaintBoundary(child: child);
}
if (addSemanticIndexes) {
final int? semanticIndex = semanticIndexCallback(child, index);
if (semanticIndex != null) {
child = IndexedSemantics(index: semanticIndex + semanticIndexOffset, child: child);
}
}
if (addAutomaticKeepAlives) {
child = AutomaticKeepAlive(child: _SelectionKeepAlive(child: child));
}
return KeyedSubtree(key: key, child: child);
}
@override
int? get estimatedChildCount => childCount;
@override
bool shouldRebuild(covariant SliverChildBuilderDelegate oldDelegate) => true;
}
/// A delegate that supplies children for slivers using an explicit list.
///
/// Many slivers lazily construct their box children to avoid creating more
/// children than are visible through the [Viewport]. This delegate provides
/// children using an explicit list, which is convenient but reduces the benefit
/// of building children lazily.
///
/// In general building all the widgets in advance is not efficient. It is
/// better to create a delegate that builds them on demand using
/// [SliverChildBuilderDelegate] or by subclassing [SliverChildDelegate]
/// directly.
///
/// This class is provided for the cases where either the list of children is
/// known well in advance (ideally the children are themselves compile-time
/// constants, for example), and therefore will not be built each time the
/// delegate itself is created, or the list is small, such that it's likely
/// always visible (and thus there is nothing to be gained by building it on
/// demand). For example, the body of a dialog box might fit both of these
/// conditions.
///
/// The widgets in the given [children] list are automatically wrapped in
/// [AutomaticKeepAlive] widgets if [addAutomaticKeepAlives] is true (the
/// default) and in [RepaintBoundary] widgets if [addRepaintBoundaries] is true
/// (also the default).
///
/// ## Accessibility
///
/// The [CustomScrollView] requires that its semantic children are annotated
/// using [IndexedSemantics]. This is done by default in the delegate with
/// the `addSemanticIndexes` parameter set to true.
///
/// If multiple delegates are used in a single scroll view, then the indexes
/// will not be correct by default. The `semanticIndexOffset` can be used to
/// offset the semantic indexes of each delegate so that the indexes are
/// monotonically increasing. For example, if a scroll view contains two
/// delegates where the first has 10 children contributing semantics, then the
/// second delegate should offset its children by 10.
///
/// In certain cases, only a subset of child widgets should be annotated
/// with a semantic index. For example, in [ListView.separated()] the
/// separators do not have an index associated with them. This is done by
/// providing a `semanticIndexCallback` which returns null for separators
/// indexes and rounds the non-separator indexes down by half.
///
/// See [SliverChildBuilderDelegate] for sample code using
/// `semanticIndexOffset` and `semanticIndexCallback`.
///
/// See also:
///
/// * [SliverChildBuilderDelegate], which is a delegate that uses a builder
/// callback to construct the children.
class SliverChildListDelegate extends SliverChildDelegate {
/// Creates a delegate that supplies children for slivers using the given
/// list.
///
/// The [children], [addAutomaticKeepAlives], [addRepaintBoundaries],
/// [addSemanticIndexes], and [semanticIndexCallback] arguments must not be
/// null.
///
/// If the order of children never changes, consider using the constant
/// [SliverChildListDelegate.fixed] constructor.
SliverChildListDelegate(
this.children, {
this.addAutomaticKeepAlives = true,
this.addRepaintBoundaries = true,
this.addSemanticIndexes = true,
this.semanticIndexCallback = _kDefaultSemanticIndexCallback,
this.semanticIndexOffset = 0,
}) : _keyToIndex = <Key?, int>{null: 0};
/// Creates a constant version of the delegate that supplies children for
/// slivers using the given list.
///
/// If the order of the children will change, consider using the regular
/// [SliverChildListDelegate] constructor.
///
/// The [children], [addAutomaticKeepAlives], [addRepaintBoundaries],
/// [addSemanticIndexes], and [semanticIndexCallback] arguments must not be
/// null.
const SliverChildListDelegate.fixed(
this.children, {
this.addAutomaticKeepAlives = true,
this.addRepaintBoundaries = true,
this.addSemanticIndexes = true,
this.semanticIndexCallback = _kDefaultSemanticIndexCallback,
this.semanticIndexOffset = 0,
}) : _keyToIndex = null;
/// {@macro flutter.widgets.SliverChildBuilderDelegate.addAutomaticKeepAlives}
final bool addAutomaticKeepAlives;
/// {@macro flutter.widgets.SliverChildBuilderDelegate.addRepaintBoundaries}
final bool addRepaintBoundaries;
/// {@macro flutter.widgets.SliverChildBuilderDelegate.addSemanticIndexes}
final bool addSemanticIndexes;
/// {@macro flutter.widgets.SliverChildBuilderDelegate.semanticIndexOffset}
final int semanticIndexOffset;
/// {@macro flutter.widgets.SliverChildBuilderDelegate.semanticIndexCallback}
final SemanticIndexCallback semanticIndexCallback;
/// The widgets to display.
///
/// If this list is going to be mutated, it is usually wise to put a [Key] on
/// each of the child widgets, so that the framework can match old
/// configurations to new configurations and maintain the underlying render
/// objects.
///
/// Also, a [Widget] in Flutter is immutable, so directly modifying the
/// [children] such as `someWidget.children.add(...)` or
/// passing a reference of the original list value to the [children] parameter
/// will result in incorrect behaviors. Whenever the
/// children list is modified, a new list object must be provided.
///
/// The following code corrects the problem mentioned above.
///
/// ```dart
/// class SomeWidgetState extends State<SomeWidget> {
/// final List<Widget> _children = <Widget>[];
///
/// void someHandler() {
/// setState(() {
/// // The key here allows Flutter to reuse the underlying render
/// // objects even if the children list is recreated.
/// _children.add(ChildWidget(key: UniqueKey()));
/// });
/// }
///
/// @override
/// Widget build(BuildContext context) {
/// // Always create a new list of children as a Widget is immutable.
/// return PageView(children: List<Widget>.of(_children));
/// }
/// }
/// ```
final List<Widget> children;
/// A map to cache key to index lookup for children.
///
/// _keyToIndex[null] is used as current index during the lazy loading process
/// in [_findChildIndex]. _keyToIndex should never be used for looking up null key.
final Map<Key?, int>? _keyToIndex;
bool get _isConstantInstance => _keyToIndex == null;
int? _findChildIndex(Key key) {
if (_isConstantInstance) {
return null;
}
// Lazily fill the [_keyToIndex].
if (!_keyToIndex!.containsKey(key)) {
int index = _keyToIndex[null]!;
while (index < children.length) {
final Widget child = children[index];
if (child.key != null) {
_keyToIndex[child.key] = index;
}
if (child.key == key) {
// Record current index for next function call.
_keyToIndex[null] = index + 1;
return index;
}
index += 1;
}
_keyToIndex[null] = index;
} else {
return _keyToIndex[key];
}
return null;
}
@override
int? findIndexByKey(Key key) {
final Key childKey;
if (key is _SaltedValueKey) {
final _SaltedValueKey saltedValueKey = key;
childKey = saltedValueKey.value;
} else {
childKey = key;
}
return _findChildIndex(childKey);
}
@override
Widget? build(BuildContext context, int index) {
if (index < 0 || index >= children.length) {
return null;
}
Widget child = children[index];
final Key? key = child.key != null? _SaltedValueKey(child.key!) : null;
if (addRepaintBoundaries) {
child = RepaintBoundary(child: child);
}
if (addSemanticIndexes) {
final int? semanticIndex = semanticIndexCallback(child, index);
if (semanticIndex != null) {
child = IndexedSemantics(index: semanticIndex + semanticIndexOffset, child: child);
}
}
if (addAutomaticKeepAlives) {
child = AutomaticKeepAlive(child: _SelectionKeepAlive(child: child));
}
return KeyedSubtree(key: key, child: child);
}
@override
int? get estimatedChildCount => children.length;
@override
bool shouldRebuild(covariant SliverChildListDelegate oldDelegate) {
return children != oldDelegate.children;
}
}
class _SelectionKeepAlive extends StatefulWidget {
/// Creates a widget that listens to [KeepAliveNotification]s and maintains a
/// [KeepAlive] widget appropriately.
const _SelectionKeepAlive({
required this.child,
});
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
@override
State<_SelectionKeepAlive> createState() => _SelectionKeepAliveState();
}
class _SelectionKeepAliveState extends State<_SelectionKeepAlive> with AutomaticKeepAliveClientMixin implements SelectionRegistrar {
Set<Selectable>? _selectablesWithSelections;
Map<Selectable, VoidCallback>? _selectableAttachments;
SelectionRegistrar? _registrar;
@override
bool get wantKeepAlive => _wantKeepAlive;
bool _wantKeepAlive = false;
set wantKeepAlive(bool value) {
if (_wantKeepAlive != value) {
_wantKeepAlive = value;
updateKeepAlive();
}
}
VoidCallback listensTo(Selectable selectable) {
return () {
if (selectable.value.hasSelection) {
_updateSelectablesWithSelections(selectable, add: true);
} else {
_updateSelectablesWithSelections(selectable, add: false);
}
};
}
void _updateSelectablesWithSelections(Selectable selectable, {required bool add}) {
if (add) {
assert(selectable.value.hasSelection);
_selectablesWithSelections ??= <Selectable>{};
_selectablesWithSelections!.add(selectable);
} else {
_selectablesWithSelections?.remove(selectable);
}
wantKeepAlive = _selectablesWithSelections?.isNotEmpty ?? false;
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
final SelectionRegistrar? newRegistrar = SelectionContainer.maybeOf(context);
if (_registrar != newRegistrar) {
if (_registrar != null) {
_selectableAttachments?.keys.forEach(_registrar!.remove);
}
_registrar = newRegistrar;
if (_registrar != null) {
_selectableAttachments?.keys.forEach(_registrar!.add);
}
}
}
@override
void add(Selectable selectable) {
final VoidCallback attachment = listensTo(selectable);
selectable.addListener(attachment);
_selectableAttachments ??= <Selectable, VoidCallback>{};
_selectableAttachments![selectable] = attachment;
_registrar!.add(selectable);
if (selectable.value.hasSelection) {
_updateSelectablesWithSelections(selectable, add: true);
}
}
@override
void remove(Selectable selectable) {
if (_selectableAttachments == null) {
return;
}
assert(_selectableAttachments!.containsKey(selectable));
final VoidCallback attachment = _selectableAttachments!.remove(selectable)!;
selectable.removeListener(attachment);
_registrar!.remove(selectable);
_updateSelectablesWithSelections(selectable, add: false);
}
@override
void dispose() {
if (_selectableAttachments != null) {
for (final Selectable selectable in _selectableAttachments!.keys) {
_registrar!.remove(selectable);
selectable.removeListener(_selectableAttachments![selectable]!);
}
_selectableAttachments = null;
}
_selectablesWithSelections = null;
super.dispose();
}
@override
Widget build(BuildContext context) {
super.build(context);
if (_registrar == null) {
return widget.child;
}
return SelectionRegistrarScope(
registrar: this,
child: widget.child,
);
}
}
// Return a Widget for the given Exception
Widget _createErrorWidget(Object exception, StackTrace stackTrace) {
final FlutterErrorDetails details = FlutterErrorDetails(
exception: exception,
stack: stackTrace,
library: 'widgets library',
context: ErrorDescription('building'),
);
FlutterError.reportError(details);
return ErrorWidget.builder(details);
}
/// A delegate that supplies children for scrolling in two dimensions.
///
/// A [TwoDimensionalScrollView] lazily constructs its box children to avoid
/// creating more children than are visible through the
/// [TwoDimensionalViewport]. Rather than receiving children as an
/// explicit [List], it receives its children using a
/// [TwoDimensionalChildDelegate].
///
/// As a ChangeNotifier, this delegate allows subclasses to notify its listeners
/// (typically as a subclass of [RenderTwoDimensionalViewport]) to rebuild when
/// aspects of the delegate change. When values returned by getters or builders
/// on this delegate change, [notifyListeners] should be called. This signals to
/// the [RenderTwoDimensionalViewport] that the getters and builders need to be
/// re-queried to update the layout of children in the viewport.
///
/// See also:
///
/// * [TwoDimensionalChildBuilderDelegate], an concrete subclass of this that
/// lazily builds children on demand.
/// * [TwoDimensionalChildListDelegate], an concrete subclass of this that
/// uses a two dimensional array to layout children.
abstract class TwoDimensionalChildDelegate extends ChangeNotifier {
/// Returns the child with the given [ChildVicinity], which is described in
/// terms of x and y indices.
///
/// Subclasses must implement this function and will typically wrap their
/// children in [RepaintBoundary] widgets.
///
/// The values returned by this method are cached. To indicate that the
/// widgets have changed, a new delegate must be provided, and the new
/// delegate's [shouldRebuild] method must return true. Alternatively,
/// calling [notifyListeners] will allow the same delegate to be used.
Widget? build(BuildContext context, covariant ChildVicinity vicinity);
/// Called whenever a new instance of the child delegate class is
/// provided.
///
/// If the new instance represents different information than the old
/// instance, then the method should return true, otherwise it should return
/// false.
///
/// If the method returns false, then the [build] call might be optimized
/// away.
bool shouldRebuild(covariant TwoDimensionalChildDelegate oldDelegate);
}
/// A delegate that supplies children for a [TwoDimensionalScrollView] using a
/// builder callback.
///
/// The widgets returned from the builder callback are automatically wrapped in
/// [RepaintBoundary] widgets if [addRepaintBoundaries] is true
/// (also the default).
///
/// See also:
///
/// * [TwoDimensionalChildListDelegate], which is a similar delegate that has an
/// explicit two dimensional array of children.
/// * [SliverChildBuilderDelegate], which is a delegate that uses a builder
/// callback to construct the children in one dimension instead of two.
/// * [SliverChildListDelegate], which is a delegate that has an explicit list
/// of children in one dimension instead of two.
class TwoDimensionalChildBuilderDelegate extends TwoDimensionalChildDelegate {
/// Creates a delegate that supplies children for a [TwoDimensionalScrollView]
/// using the given builder callback.
TwoDimensionalChildBuilderDelegate({
required this.builder,
int? maxXIndex,
int? maxYIndex,
this.addRepaintBoundaries = true,
this.addAutomaticKeepAlives = true,
}) : assert(maxYIndex == null || maxYIndex >= -1),
assert(maxXIndex == null || maxXIndex >= -1),
_maxYIndex = maxYIndex,
_maxXIndex = maxXIndex;
/// Called to build children on demand.
///
/// Implementors of [RenderTwoDimensionalViewport.layoutChildSequence]
/// call this builder to create the children of the viewport. For
/// [ChildVicinity] indices greater than [maxXIndex] or [maxYIndex], null will
/// be returned by the default [build] implementation. This default behavior
/// can be changed by overriding the build method.
///
/// Must return null if asked to build a widget with a [ChildVicinity] that
/// does not exist.
///
/// The delegate wraps the children returned by this builder in
/// [RepaintBoundary] widgets if [addRepaintBoundaries] is true.
final TwoDimensionalIndexedWidgetBuilder builder;
/// The maximum [ChildVicinity.xIndex] for children in the x axis.
///
/// {@template flutter.widgets.twoDimensionalChildBuilderDelegate.maxIndex}
/// For each [ChildVicinity], the child's relative location is described in
/// terms of x and y indices to facilitate a consistent visitor pattern for
/// all children in the viewport.
///
/// This is fairly straightforward in the context of a table implementation,
/// where there is usually the same number of columns in every row and vice
/// versa, each aligned one after the other.
///
/// When plotting children more abstractly in two dimensional space, there may
/// be more x indices for a given y index than another y index. An example of
/// this would be a scatter plot where there are more children at the top of
/// the graph than at the bottom.
///
/// If null, subclasses of [RenderTwoDimensionalViewport] can continue call on
/// the [builder] until null has been returned for each known index of x and
/// y. In some cases, null may not be a terminating result, such as a table
/// with a merged cell spanning multiple indices. Refer to the
/// [TwoDimensionalViewport] subclass to learn how this value is applied in
/// the specific use case.
///
/// If not null, the value must be greater than or equal to -1, where -1
/// indicates there will be no children at all provided to the
/// [TwoDimensionalViewport].
///
/// If the value changes, the delegate will call [notifyListeners]. This
/// informs the [RenderTwoDimensionalViewport] that any cached information
/// from the delegate is invalid.
/// {@endtemplate}
///
/// This value represents the greatest x index of all [ChildVicinity]s for the
/// two dimensional scroll view.
///
/// See also:
///
/// * [RenderTwoDimensionalViewport.buildOrObtainChildFor], the method that
/// leads to calling on the delegate to build a child of the given
/// [ChildVicinity].
int? get maxXIndex => _maxXIndex;
int? _maxXIndex;
set maxXIndex(int? value) {
if (value == maxXIndex) {
return;
}
assert(value == null || value >= -1);
_maxXIndex = value;
notifyListeners();
}
/// The maximum [ChildVicinity.yIndex] for children in the y axis.
///
/// {@macro flutter.widgets.twoDimensionalChildBuilderDelegate.maxIndex}
///
/// This value represents the greatest y index of all [ChildVicinity]s for the
/// two dimensional scroll view.
///
/// See also:
///
/// * [RenderTwoDimensionalViewport.buildOrObtainChildFor], the method that
/// leads to calling on the delegate to build a child of the given
/// [ChildVicinity].
int? get maxYIndex => _maxYIndex;
int? _maxYIndex;
set maxYIndex(int? value) {
if (maxYIndex == value) {
return;
}
assert(value == null || value >= -1);
_maxYIndex = value;
notifyListeners();
}
/// {@macro flutter.widgets.SliverChildBuilderDelegate.addRepaintBoundaries}
final bool addRepaintBoundaries;
/// {@macro flutter.widgets.SliverChildBuilderDelegate.addAutomaticKeepAlives}
final bool addAutomaticKeepAlives;
@override
Widget? build(BuildContext context, ChildVicinity vicinity) {
// If we have exceeded explicit upper bounds, return null.
if (vicinity.xIndex < 0 || (maxXIndex != null && vicinity.xIndex > maxXIndex!)) {
return null;
}
if (vicinity.yIndex < 0 || (maxYIndex != null && vicinity.yIndex > maxYIndex!)) {
return null;
}
Widget? child;
try {
child = builder(context, vicinity);
} catch (exception, stackTrace) {
child = _createErrorWidget(exception, stackTrace);
}
if (child == null) {
return null;
}
if (addRepaintBoundaries) {
child = RepaintBoundary(child: child);
}
if (addAutomaticKeepAlives) {
child = AutomaticKeepAlive(child: _SelectionKeepAlive(child: child));
}
return child;
}
@override
bool shouldRebuild(covariant TwoDimensionalChildDelegate oldDelegate) => true;
}
/// A delegate that supplies children for a [TwoDimensionalViewport] using an
/// explicit two dimensional array.
///
/// In general, building all the widgets in advance is not efficient. It is
/// better to create a delegate that builds them on demand using
/// [TwoDimensionalChildBuilderDelegate] or by subclassing
/// [TwoDimensionalChildDelegate] directly.
///
/// This class is provided for the cases where either the list of children is
/// known well in advance (ideally the children are themselves compile-time
/// constants, for example), and therefore will not be built each time the
/// delegate itself is created, or the array is small, such that it's likely
/// always visible (and thus there is nothing to be gained by building it on
/// demand).
///
/// The widgets in the given [children] list are automatically wrapped in
/// [RepaintBoundary] widgets if [addRepaintBoundaries] is true
/// (also the default).
///
/// The [children] are accessed for each [ChildVicinity.yIndex] and
/// [ChildVicinity.xIndex] of the [TwoDimensionalViewport] as
/// `children[vicinity.yIndex][vicinity.xIndex]`.
///
/// See also:
///
/// * [TwoDimensionalChildBuilderDelegate], which is a delegate that uses a
/// builder callback to construct the children.
/// * [SliverChildBuilderDelegate], which is a delegate that uses a builder
/// callback to construct the children in one dimension instead of two.
/// * [SliverChildListDelegate], which is a delegate that has an explicit list
/// of children in one dimension instead of two.
class TwoDimensionalChildListDelegate extends TwoDimensionalChildDelegate {
/// Creates a delegate that supplies children for a [TwoDimensionalScrollView].
///
/// The [children] and [addRepaintBoundaries] must not be
/// null.
TwoDimensionalChildListDelegate({
this.addRepaintBoundaries = true,
this.addAutomaticKeepAlives = true,
required this.children,
});
/// The widgets to display.
///
/// Also, a [Widget] in Flutter is immutable, so directly modifying the
/// [children] such as `someWidget.children.add(...)` or
/// passing a reference of the original list value to the [children] parameter
/// will result in incorrect behaviors. Whenever the
/// children list is modified, a new list object must be provided.
///
/// The [children] are accessed for each [ChildVicinity.yIndex] and
/// [ChildVicinity.xIndex] of the [TwoDimensionalViewport] as
/// `children[vicinity.yIndex][vicinity.xIndex]`.
final List<List<Widget>> children;
/// {@macro flutter.widgets.SliverChildBuilderDelegate.addRepaintBoundaries}
final bool addRepaintBoundaries;
/// {@macro flutter.widgets.SliverChildBuilderDelegate.addAutomaticKeepAlives}
final bool addAutomaticKeepAlives;
@override
Widget? build(BuildContext context, ChildVicinity vicinity) {
// If we have exceeded explicit upper bounds, return null.
if (vicinity.yIndex < 0 || vicinity.yIndex >= children.length) {
return null;
}
if (vicinity.xIndex < 0 || vicinity.xIndex >= children[vicinity.yIndex].length) {
return null;
}
Widget child = children[vicinity.yIndex][vicinity.xIndex];
if (addRepaintBoundaries) {
child = RepaintBoundary(child: child);
}
if (addAutomaticKeepAlives) {
child = AutomaticKeepAlive(child: _SelectionKeepAlive(child: child));
}
return child;
}
@override
bool shouldRebuild(covariant TwoDimensionalChildListDelegate oldDelegate) {
return children != oldDelegate.children;
}
}
| flutter/packages/flutter/lib/src/widgets/scroll_delegate.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/scroll_delegate.dart",
"repo_id": "flutter",
"token_count": 13283
} | 647 |
// 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 'framework.dart';
import 'inherited_model.dart';
/// The type of the [SharedAppData.getValue] `init` parameter.
///
/// This callback is used to lazily create the initial value for
/// a [SharedAppData] keyword.
typedef SharedAppDataInitCallback<T> = T Function();
/// Enables sharing key/value data with its `child` and all of the
/// child's descendants.
///
/// - `SharedAppData.getValue(context, key, initCallback)` creates a dependency
/// on the key and returns the value for the key from the shared data table.
/// If no value exists for key then the initCallback is used to create
/// the initial value.
///
/// - `SharedAppData.setValue(context, key, value)` changes the value of an entry
/// in the shared data table and forces widgets that depend on that entry
/// to be rebuilt.
///
/// A widget whose build method uses SharedAppData.getValue(context,
/// keyword, initCallback) creates a dependency on the SharedAppData. When
/// the value of keyword changes with SharedAppData.setValue(), the widget
/// will be rebuilt. The values managed by the SharedAppData are expected
/// to be immutable: intrinsic changes to values will not cause
/// dependent widgets to be rebuilt.
///
/// An instance of this widget is created automatically by [WidgetsApp].
///
/// There are many ways to share data with a widget subtree. This
/// class is based on [InheritedModel], which is an [InheritedWidget].
/// It's intended to be used by packages that need to share a modest
/// number of values among their own components.
///
/// SharedAppData is not intended to be a substitute for Provider or any of
/// the other general purpose application state systems. SharedAppData is
/// for situations where a package's custom widgets need to share one
/// or a handful of immutable data objects that can be lazily
/// initialized. It exists so that packages like that can deliver
/// custom widgets without requiring the developer to add a
/// package-specific umbrella widget to their application.
///
/// A good way to create an SharedAppData key that avoids potential
/// collisions with other packages is to use a static `Object()` value.
/// The `SharedObject` example below does this.
///
/// {@tool dartpad}
/// The following sample demonstrates using the automatically created
/// [SharedAppData]. Button presses cause changes to the values for keys
/// 'foo', and 'bar', and those changes only cause the widgets that
/// depend on those keys to be rebuilt.
///
/// ** See code in examples/api/lib/widgets/shared_app_data/shared_app_data.0.dart **
/// {@end-tool}
///
/// {@tool dartpad}
/// The following sample demonstrates how a single lazily computed
/// value could be shared within an app. A Flutter package that
/// provided custom widgets might use this approach to share a (possibly
/// private) value with instances of those widgets.
///
/// ** See code in examples/api/lib/widgets/shared_app_data/shared_app_data.1.dart **
/// {@end-tool}
class SharedAppData extends StatefulWidget {
/// Creates a widget based on [InheritedModel] that supports build
/// dependencies qualified by keywords. Descendant widgets create
/// such dependencies with [SharedAppData.getValue] and they trigger
/// rebuilds with [SharedAppData.setValue].
///
/// This widget is automatically created by the [WidgetsApp].
const SharedAppData({ super.key, required this.child });
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
@override
State<StatefulWidget> createState() => _SharedAppDataState();
/// Returns the app model's value for `key` and ensures that each
/// time the value of `key` is changed with [SharedAppData.setValue], the
/// specified context will be rebuilt.
///
/// If no value for `key` exists then the `init` callback is used to
/// generate an initial value. The callback is expected to return
/// an immutable value because intrinsic changes to the value will
/// not cause dependent widgets to be rebuilt.
///
/// A widget that depends on the app model's value for `key` should use
/// this method in their `build` methods to ensure that they are rebuilt
/// if the value changes.
///
/// The type parameter `K` is the type of the keyword and `V`
/// is the type of the value.
static V getValue<K extends Object, V>(BuildContext context, K key, SharedAppDataInitCallback<V> init) {
final _SharedAppModel? model = InheritedModel.inheritFrom<_SharedAppModel>(context, aspect: key);
assert(_debugHasSharedAppData(model, context, 'getValue'));
return model!.sharedAppDataState.getValue<K, V>(key, init);
}
/// Changes the app model's `value` for `key` and rebuilds any widgets
/// that have created a dependency on `key` with [SharedAppData.getValue].
///
/// If `value` is `==` to the current value of `key` then nothing
/// is rebuilt.
///
/// The `value` is expected to be immutable because intrinsic
/// changes to the value will not cause dependent widgets to be
/// rebuilt.
///
/// Unlike [SharedAppData.getValue], this method does _not_ create a dependency
/// between `context` and `key`.
///
/// The type parameter `K` is the type of the value's keyword and `V`
/// is the type of the value.
static void setValue<K extends Object, V>(BuildContext context, K key, V value) {
final _SharedAppModel? model = context.getInheritedWidgetOfExactType<_SharedAppModel>();
assert(_debugHasSharedAppData(model, context, 'setValue'));
model!.sharedAppDataState.setValue<K, V>(key, value);
}
static bool _debugHasSharedAppData(_SharedAppModel? model, BuildContext context, String methodName) {
assert(() {
if (model == null) {
throw FlutterError.fromParts(
<DiagnosticsNode>[
ErrorSummary('No SharedAppData widget found.'),
ErrorDescription('SharedAppData.$methodName requires an SharedAppData widget ancestor.\n'),
context.describeWidget('The specific widget that could not find an SharedAppData ancestor was'),
context.describeOwnershipChain('The ownership chain for the affected widget is'),
ErrorHint(
'Typically, the SharedAppData widget is introduced by the MaterialApp '
'or WidgetsApp widget at the top of your application widget tree. It '
'provides a key/value map of data that is shared with the entire '
'application.',
),
],
);
}
return true;
}());
return true;
}
}
class _SharedAppDataState extends State<SharedAppData> {
late Map<Object, Object?> data = <Object, Object?>{};
@override
Widget build(BuildContext context) {
return _SharedAppModel(sharedAppDataState: this, child: widget.child);
}
V getValue<K extends Object, V>(K key, SharedAppDataInitCallback<V> init) {
data[key] ??= init();
return data[key] as V;
}
void setValue<K extends Object, V>(K key, V value) {
if (data[key] != value) {
setState(() {
data = Map<Object, Object?>.of(data);
data[key] = value;
});
}
}
}
class _SharedAppModel extends InheritedModel<Object> {
_SharedAppModel({
required this.sharedAppDataState,
required super.child
}) : data = sharedAppDataState.data;
final _SharedAppDataState sharedAppDataState;
final Map<Object, Object?> data;
@override
bool updateShouldNotify(_SharedAppModel old) {
return data != old.data;
}
@override
bool updateShouldNotifyDependent(_SharedAppModel old, Set<Object> keys) {
for (final Object key in keys) {
if (data[key] != old.data[key]) {
return true;
}
}
return false;
}
}
| flutter/packages/flutter/lib/src/widgets/shared_app_data.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/shared_app_data.dart",
"repo_id": "flutter",
"token_count": 2341
} | 648 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'editable_text.dart';
import 'framework.dart';
// Enable if you want verbose logging about tap region changes.
const bool _kDebugTapRegion = false;
bool _tapRegionDebug(String message, [Iterable<String>? details]) {
if (_kDebugTapRegion) {
debugPrint('TAP REGION: $message');
if (details != null && details.isNotEmpty) {
for (final String detail in details) {
debugPrint(' $detail');
}
}
}
// Return true so that it can be easily used inside of an assert.
return true;
}
/// The type of callback that [TapRegion.onTapOutside] and
/// [TapRegion.onTapInside] take.
///
/// The event is the pointer event that caused the callback to be called.
typedef TapRegionCallback = void Function(PointerDownEvent event);
/// An interface for registering and unregistering a [RenderTapRegion]
/// (typically created with a [TapRegion] widget) with a
/// [RenderTapRegionSurface] (typically created with a [TapRegionSurface]
/// widget).
abstract class TapRegionRegistry {
/// Register the given [RenderTapRegion] with the registry.
void registerTapRegion(RenderTapRegion region);
/// Unregister the given [RenderTapRegion] with the registry.
void unregisterTapRegion(RenderTapRegion region);
/// Allows finding of the nearest [TapRegionRegistry], such as a
/// [RenderTapRegionSurface].
///
/// Will throw if a [TapRegionRegistry] isn't found.
static TapRegionRegistry of(BuildContext context) {
final TapRegionRegistry? registry = maybeOf(context);
assert(() {
if (registry == null) {
throw FlutterError(
'TapRegionRegistry.of() was called with a context that does not contain a TapRegionSurface widget.\n'
'No TapRegionSurface widget ancestor could be found starting from the context that was passed to '
'TapRegionRegistry.of().\n'
'The context used was:\n'
' $context',
);
}
return true;
}());
return registry!;
}
/// Allows finding of the nearest [TapRegionRegistry], such as a
/// [RenderTapRegionSurface].
static TapRegionRegistry? maybeOf(BuildContext context) {
return context.findAncestorRenderObjectOfType<RenderTapRegionSurface>();
}
}
/// A widget that provides notification of a tap inside or outside of a set of
/// registered regions, without participating in the [gesture
/// disambiguation](https://flutter.dev/gestures/#gesture-disambiguation)
/// system.
///
/// The regions are defined by adding [TapRegion] widgets to the widget tree
/// around the regions of interest, and they will register with this
/// [TapRegionSurface]. Each of the tap regions can optionally belong to a group
/// by assigning a [TapRegion.groupId], where all the regions with the same
/// groupId act as if they were all one region.
///
/// When a tap outside of a registered region or region group is detected, its
/// [TapRegion.onTapOutside] callback is called. If the tap is outside one
/// member of a group, but inside another, no notification is made.
///
/// When a tap inside of a registered region or region group is detected, its
/// [TapRegion.onTapInside] callback is called. If the tap is inside one member
/// of a group, all members are notified.
///
/// The [TapRegionSurface] should be defined at the highest level needed to
/// encompass the entire area where taps should be monitored. This is typically
/// around the entire app. If the entire app isn't covered, then taps outside of
/// the [TapRegionSurface] will be ignored and no [TapRegion.onTapOutside] calls
/// will be made for those events. The [WidgetsApp], [MaterialApp] and
/// [CupertinoApp] automatically include a [TapRegionSurface] around their
/// entire app.
///
/// [TapRegionSurface] does not participate in the [gesture
/// disambiguation](https://flutter.dev/gestures/#gesture-disambiguation)
/// system, so if multiple [TapRegionSurface]s are active at the same time, they
/// will all fire, and so will any other gestures recognized by a
/// [GestureDetector] or other pointer event handlers.
///
/// [TapRegion]s register only with the nearest ancestor [TapRegionSurface].
///
/// See also:
///
/// * [RenderTapRegionSurface], the render object that is inserted into the
/// render tree by this widget.
/// * <https://flutter.dev/gestures/#gesture-disambiguation> for more
/// information about the gesture system and how it disambiguates inputs.
class TapRegionSurface extends SingleChildRenderObjectWidget {
/// Creates a const [RenderTapRegionSurface].
///
/// The [child] attribute is required.
const TapRegionSurface({
super.key,
required Widget super.child,
});
@override
RenderObject createRenderObject(BuildContext context) {
return RenderTapRegionSurface();
}
@override
void updateRenderObject(
BuildContext context,
RenderProxyBoxWithHitTestBehavior renderObject,
) {}
}
/// A render object that provides notification of a tap inside or outside of a
/// set of registered regions, without participating in the [gesture
/// disambiguation](https://flutter.dev/gestures/#gesture-disambiguation) system
/// (other than to consume tap down events if [TapRegion.consumeOutsideTaps] is
/// true).
///
/// The regions are defined by adding [RenderTapRegion] render objects in the
/// render tree around the regions of interest, and they will register with this
/// [RenderTapRegionSurface]. Each of the tap regions can optionally belong to a
/// group by assigning a [RenderTapRegion.groupId], where all the regions with
/// the same groupId act as if they were all one region.
///
/// When a tap outside of a registered region or region group is detected, its
/// [TapRegion.onTapOutside] callback is called. If the tap is outside one
/// member of a group, but inside another, no notification is made.
///
/// When a tap inside of a registered region or region group is detected, its
/// [TapRegion.onTapInside] callback is called. If the tap is inside one member
/// of a group, all members are notified.
///
/// The [RenderTapRegionSurface] should be defined at the highest level needed
/// to encompass the entire area where taps should be monitored. This is
/// typically around the entire app. If the entire app isn't covered, then taps
/// outside of the [RenderTapRegionSurface] will be ignored and no
/// [RenderTapRegion.onTapOutside] calls will be made for those events. The
/// [WidgetsApp], [MaterialApp] and [CupertinoApp] automatically include a
/// [RenderTapRegionSurface] around the entire app.
///
/// [RenderTapRegionSurface] does not participate in the [gesture
/// disambiguation](https://flutter.dev/gestures/#gesture-disambiguation)
/// system, so if multiple [RenderTapRegionSurface]s are active at the same
/// time, they will all fire, and so will any other gestures recognized by a
/// [GestureDetector] or other pointer event handlers.
///
/// [RenderTapRegion]s register only with the nearest ancestor
/// [RenderTapRegionSurface].
///
/// See also:
///
/// * [TapRegionSurface], a widget that inserts a [RenderTapRegionSurface] into
/// the render tree.
/// * [TapRegionRegistry.of], which can find the nearest ancestor
/// [RenderTapRegionSurface], which is a [TapRegionRegistry].
class RenderTapRegionSurface extends RenderProxyBoxWithHitTestBehavior implements TapRegionRegistry {
final Expando<BoxHitTestResult> _cachedResults = Expando<BoxHitTestResult>();
final Set<RenderTapRegion> _registeredRegions = <RenderTapRegion>{};
final Map<Object?, Set<RenderTapRegion>> _groupIdToRegions = <Object?, Set<RenderTapRegion>>{};
@override
void registerTapRegion(RenderTapRegion region) {
assert(_tapRegionDebug('Region $region registered.'));
assert(!_registeredRegions.contains(region));
_registeredRegions.add(region);
if (region.groupId != null) {
_groupIdToRegions[region.groupId] ??= <RenderTapRegion>{};
_groupIdToRegions[region.groupId]!.add(region);
}
}
@override
void unregisterTapRegion(RenderTapRegion region) {
assert(_tapRegionDebug('Region $region unregistered.'));
assert(_registeredRegions.contains(region));
_registeredRegions.remove(region);
if (region.groupId != null) {
assert(_groupIdToRegions.containsKey(region.groupId));
_groupIdToRegions[region.groupId]!.remove(region);
if (_groupIdToRegions[region.groupId]!.isEmpty) {
_groupIdToRegions.remove(region.groupId);
}
}
}
@override
bool hitTest(BoxHitTestResult result, {required Offset position}) {
if (!size.contains(position)) {
return false;
}
final bool hitTarget = hitTestChildren(result, position: position) || hitTestSelf(position);
if (hitTarget) {
final BoxHitTestEntry entry = BoxHitTestEntry(this, position);
_cachedResults[entry] = result;
result.add(entry);
}
return hitTarget;
}
@override
void handleEvent(PointerEvent event, HitTestEntry entry) {
assert(debugHandleEvent(event, entry));
assert(() {
for (final RenderTapRegion region in _registeredRegions) {
if (!region.enabled) {
return false;
}
}
return true;
}(), 'A RenderTapRegion was registered when it was disabled.');
if (event is! PointerDownEvent) {
return;
}
if (_registeredRegions.isEmpty) {
assert(_tapRegionDebug('Ignored tap event because no regions are registered.'));
return;
}
final BoxHitTestResult? result = _cachedResults[entry];
if (result == null) {
assert(_tapRegionDebug('Ignored tap event because no surface descendants were hit.'));
return;
}
// A child was hit, so we need to call onTapOutside for those regions or
// groups of regions that were not hit.
final Set<RenderTapRegion> hitRegions =
_getRegionsHit(_registeredRegions, result.path).cast<RenderTapRegion>().toSet();
final Set<RenderTapRegion> insideRegions = <RenderTapRegion>{};
assert(_tapRegionDebug('Tap event hit ${hitRegions.length} descendants.'));
for (final RenderTapRegion region in hitRegions) {
if (region.groupId == null) {
insideRegions.add(region);
continue;
}
// Add all grouped regions to the insideRegions so that groups act as a
// single region.
insideRegions.addAll(_groupIdToRegions[region.groupId]!);
}
// If they're not inside, then they're outside.
final Set<RenderTapRegion> outsideRegions = _registeredRegions.difference(insideRegions);
bool consumeOutsideTaps = false;
for (final RenderTapRegion region in outsideRegions) {
assert(_tapRegionDebug('Calling onTapOutside for $region'));
if (region.consumeOutsideTaps) {
assert(_tapRegionDebug('Stopping tap propagation for $region (and all of ${region.groupId})'));
consumeOutsideTaps = true;
}
region.onTapOutside?.call(event);
}
for (final RenderTapRegion region in insideRegions) {
assert(_tapRegionDebug('Calling onTapInside for $region'));
region.onTapInside?.call(event);
}
// If any of the "outside" regions have consumeOutsideTaps set, then stop
// the propagation of the event through the gesture recognizer by adding it
// to the recognizer and immediately resolving it.
if (consumeOutsideTaps) {
GestureBinding.instance.gestureArena.add(event.pointer, _DummyTapRecognizer()).resolve(GestureDisposition.accepted);
}
}
// Returns the registered regions that are in the hit path.
Iterable<HitTestTarget> _getRegionsHit(Set<RenderTapRegion> detectors, Iterable<HitTestEntry> hitTestPath) {
final Set<HitTestTarget> hitRegions = <HitTestTarget>{};
for (final HitTestEntry<HitTestTarget> entry in hitTestPath) {
final HitTestTarget target = entry.target;
if (_registeredRegions.contains(target)) {
hitRegions.add(target);
}
}
return hitRegions;
}
}
// A dummy tap recognizer so that we don't have to deal with the lifecycle of
// TapGestureRecognizer, since we're just going to immediately resolve it
// anyhow.
class _DummyTapRecognizer extends GestureArenaMember {
@override
void acceptGesture(int pointer) { }
@override
void rejectGesture(int pointer) { }
}
/// A widget that defines a region that can detect taps inside or outside of
/// itself and any group of regions it belongs to, without participating in the
/// [gesture
/// disambiguation](https://flutter.dev/gestures/#gesture-disambiguation) system
/// (other than to consume tap down events if [consumeOutsideTaps] is true).
///
/// This widget indicates to the nearest ancestor [TapRegionSurface] that the
/// region occupied by its child will participate in the tap detection for that
/// surface.
///
/// If this region belongs to a group (by virtue of its [groupId]), all the
/// regions in the group will act as one.
///
/// If there is no [TapRegionSurface] ancestor, [TapRegion] will do nothing.
class TapRegion extends SingleChildRenderObjectWidget {
/// Creates a const [TapRegion].
///
/// The [child] argument is required.
const TapRegion({
super.key,
required super.child,
this.enabled = true,
this.behavior = HitTestBehavior.deferToChild,
this.onTapOutside,
this.onTapInside,
this.groupId,
this.consumeOutsideTaps = false,
String? debugLabel,
}) : debugLabel = kReleaseMode ? null : debugLabel;
/// Whether or not this [TapRegion] is enabled as part of the composite region.
final bool enabled;
/// How to behave during hit testing when deciding how the hit test propagates
/// to children and whether to consider targets behind this [TapRegion].
///
/// Defaults to [HitTestBehavior.deferToChild].
///
/// See [HitTestBehavior] for the allowed values and their meanings.
final HitTestBehavior behavior;
/// A callback to be invoked when a tap is detected outside of this
/// [TapRegion] and any other region with the same [groupId], if any.
///
/// The [PointerDownEvent] passed to the function is the event that caused the
/// notification. If this region is part of a group (i.e. [groupId] is set),
/// then it's possible that the event may be outside of this immediate region,
/// although it will be within the region of one of the group members.
final TapRegionCallback? onTapOutside;
/// A callback to be invoked when a tap is detected inside of this
/// [TapRegion], or any other tap region with the same [groupId], if any.
///
/// The [PointerDownEvent] passed to the function is the event that caused the
/// notification. If this region is part of a group (i.e. [groupId] is set),
/// then it's possible that the event may be outside of this immediate region,
/// although it will be within the region of one of the group members.
final TapRegionCallback? onTapInside;
/// An optional group ID that groups [TapRegion]s together so that they
/// operate as one region. If any member of a group is hit by a particular
/// tap, then the [onTapOutside] will not be called for any members of the
/// group. If any member of the group is hit, then all members will have their
/// [onTapInside] called.
///
/// If the group id is null, then only this region is hit tested.
final Object? groupId;
/// If true, then the group that this region belongs to will stop the
/// propagation of the tap down event in the gesture arena.
///
/// This is useful if you want to block the tap down from being given to a
/// [GestureDetector] when [onTapOutside] is called.
///
/// If other [TapRegion]s with the same [groupId] have [consumeOutsideTaps]
/// set to false, but this one is true, then this one will take precedence,
/// and the event will be consumed.
///
/// Defaults to false.
final bool consumeOutsideTaps;
/// An optional debug label to help with debugging in debug mode.
///
/// Will be null in release mode.
final String? debugLabel;
@override
RenderObject createRenderObject(BuildContext context) {
return RenderTapRegion(
registry: TapRegionRegistry.maybeOf(context),
enabled: enabled,
consumeOutsideTaps: consumeOutsideTaps,
behavior: behavior,
onTapOutside: onTapOutside,
onTapInside: onTapInside,
groupId: groupId,
debugLabel: debugLabel,
);
}
@override
void updateRenderObject(BuildContext context, covariant RenderTapRegion renderObject) {
renderObject
..registry = TapRegionRegistry.maybeOf(context)
..enabled = enabled
..behavior = behavior
..groupId = groupId
..onTapOutside = onTapOutside
..onTapInside = onTapInside;
if (!kReleaseMode) {
renderObject.debugLabel = debugLabel;
}
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(FlagProperty('enabled', value: enabled, ifFalse: 'DISABLED', defaultValue: true));
properties.add(DiagnosticsProperty<HitTestBehavior>('behavior', behavior, defaultValue: HitTestBehavior.deferToChild));
properties.add(DiagnosticsProperty<Object?>('debugLabel', debugLabel, defaultValue: null));
properties.add(DiagnosticsProperty<Object?>('groupId', groupId, defaultValue: null));
}
}
/// A render object that defines a region that can detect taps inside or outside
/// of itself and any group of regions it belongs to, without participating in
/// the [gesture
/// disambiguation](https://flutter.dev/gestures/#gesture-disambiguation)
/// system.
///
/// This render object indicates to the nearest ancestor [TapRegionSurface] that
/// the region occupied by its child (or itself if [behavior] is
/// [HitTestBehavior.opaque]) will participate in the tap detection for that
/// surface.
///
/// If this region belongs to a group (by virtue of its [groupId]), all the
/// regions in the group will act as one.
///
/// If there is no [RenderTapRegionSurface] ancestor in the render tree,
/// [RenderTapRegion] will do nothing.
///
/// The [behavior] attribute describes how to behave during hit testing when
/// deciding how the hit test propagates to children and whether to consider
/// targets behind the tap region. Defaults to [HitTestBehavior.deferToChild].
/// See [HitTestBehavior] for the allowed values and their meanings.
///
/// See also:
///
/// * [TapRegion], a widget that inserts a [RenderTapRegion] into the render
/// tree.
class RenderTapRegion extends RenderProxyBoxWithHitTestBehavior {
/// Creates a [RenderTapRegion].
RenderTapRegion({
TapRegionRegistry? registry,
bool enabled = true,
bool consumeOutsideTaps = false,
this.onTapOutside,
this.onTapInside,
super.behavior = HitTestBehavior.deferToChild,
Object? groupId,
String? debugLabel,
}) : _registry = registry,
_enabled = enabled,
_consumeOutsideTaps = consumeOutsideTaps,
_groupId = groupId,
debugLabel = kReleaseMode ? null : debugLabel;
bool _isRegistered = false;
/// A callback to be invoked when a tap is detected outside of this
/// [RenderTapRegion] and any other region with the same [groupId], if any.
///
/// The [PointerDownEvent] passed to the function is the event that caused the
/// notification. If this region is part of a group (i.e. [groupId] is set),
/// then it's possible that the event may be outside of this immediate region,
/// although it will be within the region of one of the group members.
TapRegionCallback? onTapOutside;
/// A callback to be invoked when a tap is detected inside of this
/// [RenderTapRegion], or any other tap region with the same [groupId], if any.
///
/// The [PointerDownEvent] passed to the function is the event that caused the
/// notification. If this region is part of a group (i.e. [groupId] is set),
/// then it's possible that the event may be outside of this immediate region,
/// although it will be within the region of one of the group members.
TapRegionCallback? onTapInside;
/// A label used in debug builds. Will be null in release builds.
String? debugLabel;
/// Whether or not this region should participate in the composite region.
bool get enabled => _enabled;
bool _enabled;
set enabled(bool value) {
if (_enabled != value) {
_enabled = value;
markNeedsLayout();
}
}
/// Whether or not the tap down even that triggers a call to [onTapOutside]
/// will continue on to participate in the gesture arena.
///
/// If any [RenderTapRegion] in the same group has [consumeOutsideTaps] set to
/// true, then the tap down event will be consumed before other gesture
/// recognizers can process them.
bool get consumeOutsideTaps => _consumeOutsideTaps;
bool _consumeOutsideTaps;
set consumeOutsideTaps(bool value) {
if (_consumeOutsideTaps != value) {
_consumeOutsideTaps = value;
markNeedsLayout();
}
}
/// An optional group ID that groups [RenderTapRegion]s together so that they
/// operate as one region. If any member of a group is hit by a particular
/// tap, then the [onTapOutside] will not be called for any members of the
/// group. If any member of the group is hit, then all members will have their
/// [onTapInside] called.
///
/// If the group id is null, then only this region is hit tested.
Object? get groupId => _groupId;
Object? _groupId;
set groupId(Object? value) {
if (_groupId != value) {
// If the group changes, we need to unregister and re-register under the
// new group. The re-registration happens automatically in layout().
if (_isRegistered) {
_registry!.unregisterTapRegion(this);
_isRegistered = false;
}
_groupId = value;
markNeedsLayout();
}
}
/// The registry that this [RenderTapRegion] should register with.
///
/// If the [registry] is null, then this region will not be registered
/// anywhere, and will not do any tap detection.
///
/// A [RenderTapRegionSurface] is a [TapRegionRegistry].
TapRegionRegistry? get registry => _registry;
TapRegionRegistry? _registry;
set registry(TapRegionRegistry? value) {
if (_registry != value) {
if (_isRegistered) {
_registry!.unregisterTapRegion(this);
_isRegistered = false;
}
_registry = value;
markNeedsLayout();
}
}
@override
void layout(Constraints constraints, {bool parentUsesSize = false}) {
super.layout(constraints, parentUsesSize: parentUsesSize);
if (_registry == null) {
return;
}
if (_isRegistered) {
_registry!.unregisterTapRegion(this);
}
final bool shouldBeRegistered = _enabled && _registry != null;
if (shouldBeRegistered) {
_registry!.registerTapRegion(this);
}
_isRegistered = shouldBeRegistered;
}
@override
void dispose() {
if (_isRegistered) {
_registry!.unregisterTapRegion(this);
}
super.dispose();
}
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
super.debugFillProperties(properties);
properties.add(DiagnosticsProperty<String?>('debugLabel', debugLabel, defaultValue: null));
properties.add(DiagnosticsProperty<Object?>('groupId', groupId, defaultValue: null));
properties.add(FlagProperty('enabled', value: enabled, ifFalse: 'DISABLED', defaultValue: true));
}
}
/// A [TapRegion] that adds its children to the tap region group for widgets
/// based on the [EditableText] text editing widget, such as [TextField] and
/// [CupertinoTextField].
///
/// Widgets that are wrapped with a [TextFieldTapRegion] are considered to be
/// part of a text field for purposes of unfocus behavior. So, when the user
/// taps on them, the currently focused text field won't be unfocused by
/// default. This allows controls like spinners, copy buttons, and formatting
/// buttons to be associated with a text field without causing the text field to
/// lose focus when they are interacted with.
///
/// {@tool dartpad}
/// This example shows how to use a [TextFieldTapRegion] to wrap a set of
/// "spinner" buttons that increment and decrement a value in the text field
/// without causing the text field to lose keyboard focus.
///
/// This example includes a generic `SpinnerField<T>` class that you can copy/paste
/// into your own project and customize.
///
/// ** See code in examples/api/lib/widgets/tap_region/text_field_tap_region.0.dart **
/// {@end-tool}
///
/// See also:
///
/// * [TapRegion], the widget that this widget uses to add widgets to the group
/// of text fields.
class TextFieldTapRegion extends TapRegion {
/// Creates a const [TextFieldTapRegion].
///
/// The [child] field is required.
const TextFieldTapRegion({
super.key,
required super.child,
super.enabled,
super.onTapOutside,
super.onTapInside,
super.consumeOutsideTaps,
super.debugLabel,
}) : super(groupId: EditableText);
}
| flutter/packages/flutter/lib/src/widgets/tap_region.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/tap_region.dart",
"repo_id": "flutter",
"token_count": 7643
} | 649 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:collection';
import 'dart:ui' show FlutterView, SemanticsUpdate;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'framework.dart';
import 'lookup_boundary.dart';
import 'media_query.dart';
/// Bootstraps a render tree that is rendered into the provided [FlutterView].
///
/// The content rendered into that view is determined by the provided [child].
/// Descendants within the same [LookupBoundary] can look up the view they are
/// rendered into via [View.of] and [View.maybeOf].
///
/// The provided [child] is wrapped in a [MediaQuery] constructed from the given
/// [view].
///
/// For most use cases, using [MediaQuery.of], or its associated "...Of" methods
/// are a more appropriate way of obtaining the information that a [FlutterView]
/// exposes. For example, using [MediaQuery.sizeOf] will expose the _logical_
/// device size ([MediaQueryData.size]) rather than the physical size
/// ([FlutterView.physicalSize]). Similarly, while [FlutterView.padding] conveys
/// the information from the operating system, the [MediaQueryData.padding]
/// attribute (obtained from [MediaQuery.paddingOf]) further adjusts this
/// information to be aware of the context of the widget; e.g. the [Scaffold]
/// widget adjusts the values for its various children.
///
/// Each [FlutterView] can be associated with at most one [View] widget in the
/// widget tree. Two or more [View] widgets configured with the same
/// [FlutterView] must never exist within the same widget tree at the same time.
/// This limitation is enforced by a [GlobalObjectKey] that derives its identity
/// from the [view] provided to this widget.
///
/// Since the [View] widget bootstraps its own independent render tree, neither
/// it nor any of its descendants will insert a [RenderObject] into an existing
/// render tree. Therefore, the [View] widget can only be used in those parts of
/// the widget tree where it is not required to participate in the construction
/// of the surrounding render tree. In other words, the widget may only be used
/// in a non-rendering zone of the widget tree (see [WidgetsBinding] for a
/// definition of rendering and non-rendering zones).
///
/// In practical terms, the widget is typically used at the root of the widget
/// tree outside of any other [View] widget, as a child of a [ViewCollection]
/// widget, or in the [ViewAnchor.view] slot of a [ViewAnchor] widget. It is not
/// required to be a direct child, though, since other non-[RenderObjectWidget]s
/// (e.g. [InheritedWidget]s, [Builder]s, or [StatefulWidget]s/[StatelessWidget]
/// that only produce non-[RenderObjectWidget]s) are allowed to be present
/// between those widgets and the [View] widget.
///
/// See also:
///
/// * [Element.debugExpectsRenderObjectForSlot], which defines whether a [View]
/// widget is allowed in a given child slot.
class View extends StatelessWidget {
/// Create a [View] widget to bootstrap a render tree that is rendered into
/// the provided [FlutterView].
///
/// The content rendered into that [view] is determined by the given [child]
/// widget.
View({
super.key,
required this.view,
@Deprecated(
'Do not use. '
'This parameter only exists to implement the deprecated RendererBinding.pipelineOwner property until it is removed. '
'This feature was deprecated after v3.10.0-12.0.pre.'
)
PipelineOwner? deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner,
@Deprecated(
'Do not use. '
'This parameter only exists to implement the deprecated RendererBinding.renderView property until it is removed. '
'This feature was deprecated after v3.10.0-12.0.pre.'
)
RenderView? deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView,
required this.child,
}) : _deprecatedPipelineOwner = deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner,
_deprecatedRenderView = deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView,
assert((deprecatedDoNotUseWillBeRemovedWithoutNoticePipelineOwner == null) == (deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView == null)),
assert(deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView == null || deprecatedDoNotUseWillBeRemovedWithoutNoticeRenderView.flutterView == view);
/// The [FlutterView] into which [child] is drawn.
final FlutterView view;
/// The widget below this widget in the tree, which will be drawn into the
/// [view].
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget child;
final PipelineOwner? _deprecatedPipelineOwner;
final RenderView? _deprecatedRenderView;
/// Returns the [FlutterView] that the provided `context` will render into.
///
/// Returns null if the `context` is not associated with a [FlutterView].
///
/// The method creates a dependency on the `context`, which will be informed
/// when the identity of the [FlutterView] changes (i.e. the `context` is
/// moved to render into a different [FlutterView] then before). The context
/// will not be informed when the _properties_ on the [FlutterView] itself
/// change their values. To access the property values of a [FlutterView] it
/// is best practise to use [MediaQuery.maybeOf] instead, which will ensure
/// that the `context` is informed when the view properties change.
///
/// See also:
///
/// * [View.of], which throws instead of returning null if no [FlutterView]
/// is found.
static FlutterView? maybeOf(BuildContext context) {
return LookupBoundary.dependOnInheritedWidgetOfExactType<_ViewScope>(context)?.view;
}
/// Returns the [FlutterView] that the provided `context` will render into.
///
/// Throws if the `context` is not associated with a [FlutterView].
///
/// The method creates a dependency on the `context`, which will be informed
/// when the identity of the [FlutterView] changes (i.e. the `context` is
/// moved to render into a different [FlutterView] then before). The context
/// will not be informed when the _properties_ on the [FlutterView] itself
/// change their values. To access the property values of a [FlutterView]
/// prefer using the access methods on [MediaQuery], such as
/// [MediaQuery.sizeOf], which will ensure that the `context` is informed when
/// the view properties change.
///
/// See also:
///
/// * [View.maybeOf], which throws instead of returning null if no
/// [FlutterView] is found.
static FlutterView of(BuildContext context) {
final FlutterView? result = maybeOf(context);
assert(() {
if (result == null) {
final bool hiddenByBoundary = LookupBoundary.debugIsHidingAncestorWidgetOfExactType<_ViewScope>(context);
final List<DiagnosticsNode> information = <DiagnosticsNode>[
if (hiddenByBoundary) ...<DiagnosticsNode>[
ErrorSummary('View.of() was called with a context that does not have access to a View widget.'),
ErrorDescription('The context provided to View.of() does have a View widget ancestor, but it is hidden by a LookupBoundary.'),
] else ...<DiagnosticsNode>[
ErrorSummary('View.of() was called with a context that does not contain a View widget.'),
ErrorDescription('No View widget ancestor could be found starting from the context that was passed to View.of().'),
],
ErrorDescription(
'The context used was:\n'
' $context',
),
ErrorHint('This usually means that the provided context is not associated with a View.'),
];
throw FlutterError.fromParts(information);
}
return true;
}());
return result!;
}
/// Returns the [PipelineOwner] parent to which a child [View] should attach
/// its [PipelineOwner] to.
///
/// If `context` has a [View] ancestor, it returns the [PipelineOwner]
/// responsible for managing the render tree of that view. If there is no
/// [View] ancestor, [RendererBinding.rootPipelineOwner] is returned instead.
static PipelineOwner pipelineOwnerOf(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<_PipelineOwnerScope>()?.pipelineOwner
?? RendererBinding.instance.rootPipelineOwner;
}
@override
Widget build(BuildContext context) {
return _RawView(
view: view,
deprecatedPipelineOwner: _deprecatedPipelineOwner,
deprecatedRenderView: _deprecatedRenderView,
builder: (BuildContext context, PipelineOwner owner) {
return _ViewScope(
view: view,
child: _PipelineOwnerScope(
pipelineOwner: owner,
child: MediaQuery.fromView(
view: view,
child: child,
),
),
);
}
);
}
}
/// A builder for the content [Widget] of a [_RawView].
///
/// The widget returned by the builder defines the content that is drawn into
/// the [FlutterView] configured on the [_RawView].
///
/// The builder is given the [PipelineOwner] that the [_RawView] uses to manage
/// its render tree. Typical builder implementations make that pipeline owner
/// available as an attachment point for potential child views.
///
/// Used by [_RawView.builder].
typedef _RawViewContentBuilder = Widget Function(BuildContext context, PipelineOwner owner);
/// The workhorse behind the [View] widget that actually bootstraps a render
/// tree.
///
/// It instantiates the [RenderView] as the root of that render tree and adds it
/// to the [RendererBinding] via [RendererBinding.addRenderView]. It also owns
/// the [PipelineOwner] that manages this render tree and adds it as a child to
/// the surrounding parent [PipelineOwner] obtained with [View.pipelineOwnerOf].
/// This ensures that the render tree bootstrapped by this widget participates
/// properly in frame production and hit testing.
class _RawView extends RenderObjectWidget {
/// Create a [RawView] widget to bootstrap a render tree that is rendered into
/// the provided [FlutterView].
///
/// The content rendered into that [view] is determined by the [Widget]
/// returned by [builder].
_RawView({
required this.view,
required PipelineOwner? deprecatedPipelineOwner,
required RenderView? deprecatedRenderView,
required this.builder,
}) : _deprecatedPipelineOwner = deprecatedPipelineOwner,
_deprecatedRenderView = deprecatedRenderView,
assert(deprecatedRenderView == null || deprecatedRenderView.flutterView == view),
// TODO(goderbauer): Replace this with GlobalObjectKey(view) when the deprecated properties are removed.
super(key: _DeprecatedRawViewKey(view, deprecatedPipelineOwner, deprecatedRenderView));
/// The [FlutterView] into which the [Widget] returned by [builder] is drawn.
final FlutterView view;
/// Determines the content [Widget] that is drawn into the [view].
///
/// The [builder] is given the [PipelineOwner] responsible for the render tree
/// bootstrapped by this widget and typically makes it available as an
/// attachment point for potential child views.
final _RawViewContentBuilder builder;
final PipelineOwner? _deprecatedPipelineOwner;
final RenderView? _deprecatedRenderView;
@override
RenderObjectElement createElement() => _RawViewElement(this);
@override
RenderObject createRenderObject(BuildContext context) {
return _deprecatedRenderView ?? RenderView(
view: view,
);
}
// No need to implement updateRenderObject: RawView uses the view as a
// GlobalKey, so we never need to update the RenderObject with a new view.
}
class _RawViewElement extends RenderTreeRootElement {
_RawViewElement(super.widget);
late final PipelineOwner _pipelineOwner = PipelineOwner(
onSemanticsOwnerCreated: _handleSemanticsOwnerCreated,
onSemanticsUpdate: _handleSemanticsUpdate,
onSemanticsOwnerDisposed: _handleSemanticsOwnerDisposed,
);
PipelineOwner get _effectivePipelineOwner => (widget as _RawView)._deprecatedPipelineOwner ?? _pipelineOwner;
void _handleSemanticsOwnerCreated() {
(_effectivePipelineOwner.rootNode as RenderView?)?.scheduleInitialSemantics();
}
void _handleSemanticsOwnerDisposed() {
(_effectivePipelineOwner.rootNode as RenderView?)?.clearSemantics();
}
void _handleSemanticsUpdate(SemanticsUpdate update) {
(widget as _RawView).view.updateSemantics(update);
}
@override
RenderView get renderObject => super.renderObject as RenderView;
Element? _child;
void _updateChild() {
try {
final Widget child = (widget as _RawView).builder(this, _effectivePipelineOwner);
_child = updateChild(_child, child, null);
} catch (e, stack) {
final FlutterErrorDetails details = FlutterErrorDetails(
exception: e,
stack: stack,
library: 'widgets library',
context: ErrorDescription('building $this'),
informationCollector: !kDebugMode ? null : () => <DiagnosticsNode>[
DiagnosticsDebugCreator(DebugCreator(this)),
],
);
FlutterError.reportError(details);
final Widget error = ErrorWidget.builder(details);
_child = updateChild(null, error, slot);
}
}
@override
void mount(Element? parent, Object? newSlot) {
super.mount(parent, newSlot);
assert(_effectivePipelineOwner.rootNode == null);
_effectivePipelineOwner.rootNode = renderObject;
_attachView();
_updateChild();
renderObject.prepareInitialFrame();
if (_effectivePipelineOwner.semanticsOwner != null) {
renderObject.scheduleInitialSemantics();
}
}
PipelineOwner? _parentPipelineOwner; // Is null if view is currently not attached.
void _attachView([PipelineOwner? parentPipelineOwner]) {
assert(_parentPipelineOwner == null);
parentPipelineOwner ??= View.pipelineOwnerOf(this);
parentPipelineOwner.adoptChild(_effectivePipelineOwner);
RendererBinding.instance.addRenderView(renderObject);
_parentPipelineOwner = parentPipelineOwner;
}
void _detachView() {
final PipelineOwner? parentPipelineOwner = _parentPipelineOwner;
if (parentPipelineOwner != null) {
RendererBinding.instance.removeRenderView(renderObject);
parentPipelineOwner.dropChild(_effectivePipelineOwner);
_parentPipelineOwner = null;
}
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
if (_parentPipelineOwner == null) {
return;
}
final PipelineOwner newParentPipelineOwner = View.pipelineOwnerOf(this);
if (newParentPipelineOwner != _parentPipelineOwner) {
_detachView();
_attachView(newParentPipelineOwner);
}
}
@override
void performRebuild() {
super.performRebuild();
_updateChild();
}
@override
void activate() {
super.activate();
assert(_effectivePipelineOwner.rootNode == null);
_effectivePipelineOwner.rootNode = renderObject;
_attachView();
}
@override
void deactivate() {
_detachView();
assert(_effectivePipelineOwner.rootNode == renderObject);
_effectivePipelineOwner.rootNode = null; // To satisfy the assert in the super class.
super.deactivate();
}
@override
void update(_RawView newWidget) {
super.update(newWidget);
_updateChild();
}
@override
void visitChildren(ElementVisitor visitor) {
if (_child != null) {
visitor(_child!);
}
}
@override
void forgetChild(Element child) {
assert(child == _child);
_child = null;
super.forgetChild(child);
}
@override
void insertRenderObjectChild(RenderBox child, Object? slot) {
assert(slot == null);
assert(renderObject.debugValidateChild(child));
renderObject.child = child;
}
@override
void moveRenderObjectChild(RenderObject child, Object? oldSlot, Object? newSlot) {
assert(false);
}
@override
void removeRenderObjectChild(RenderObject child, Object? slot) {
assert(slot == null);
assert(renderObject.child == child);
renderObject.child = null;
}
@override
void unmount() {
if (_effectivePipelineOwner != (widget as _RawView)._deprecatedPipelineOwner) {
_effectivePipelineOwner.dispose();
}
super.unmount();
}
}
class _ViewScope extends InheritedWidget {
const _ViewScope({required this.view, required super.child});
final FlutterView? view;
@override
bool updateShouldNotify(_ViewScope oldWidget) => view != oldWidget.view;
}
class _PipelineOwnerScope extends InheritedWidget {
const _PipelineOwnerScope({
required this.pipelineOwner,
required super.child,
});
final PipelineOwner pipelineOwner;
@override
bool updateShouldNotify(_PipelineOwnerScope oldWidget) => pipelineOwner != oldWidget.pipelineOwner;
}
class _MultiChildComponentWidget extends Widget {
const _MultiChildComponentWidget({
super.key,
List<Widget> views = const <Widget>[],
Widget? child,
}) : _views = views, _child = child;
// It is up to the subclasses to make the relevant properties public.
final List<Widget> _views;
final Widget? _child;
@override
Element createElement() => _MultiChildComponentElement(this);
}
/// A collection of sibling [View]s.
///
/// This widget can only be used in places were a [View] widget is allowed, i.e.
/// in a non-rendering zone of the widget tree. In practical terms, it can be
/// used at the root of the widget tree outside of any [View] widget, as a child
/// to a another [ViewCollection], or in the [ViewAnchor.view] slot of a
/// [ViewAnchor] widget. It is not required to be a direct child of those
/// widgets; other non-[RenderObjectWidget]s may appear in between the two (such
/// as an [InheritedWidget]).
///
/// Similarly, the [views] children of this widget must be [View]s, but they
/// may be wrapped in additional non-[RenderObjectWidget]s (e.g.
/// [InheritedWidget]s).
///
/// See also:
///
/// * [WidgetsBinding] for an explanation of rendering and non-rendering zones.
class ViewCollection extends _MultiChildComponentWidget {
/// Creates a [ViewCollection] widget.
const ViewCollection({super.key, required super.views});
/// The [View] descendants of this widget.
///
/// The [View]s may be wrapped in other non-[RenderObjectWidget]s (e.g.
/// [InheritedWidget]s). However, no [RenderObjectWidget] is allowed to appear
/// between the [ViewCollection] and the next [View] widget.
List<Widget> get views => _views;
}
/// Decorates a [child] widget with a side [View].
///
/// This widget must have a [View] ancestor, into which the [child] widget
/// is rendered.
///
/// Typically, a [View] or [ViewCollection] widget is used in the [view] slot to
/// define the content of the side view(s). Those widgets may be wrapped in
/// other non-[RenderObjectWidget]s (e.g. [InheritedWidget]s). However, no
/// [RenderObjectWidget] is allowed to appear between the [ViewAnchor] and the
/// next [View] widget in the [view] slot. The widgets in the [view] slot have
/// access to all [InheritedWidget]s above the [ViewAnchor] in the tree.
///
/// In technical terms, the [ViewAnchor] can only be used in a rendering zone of
/// the widget tree and the [view] slot marks the start of a new non-rendering
/// zone (see [WidgetsBinding] for a definition of these zones). Typically,
/// it is occupied by a [View] widget, which will start a new rendering zone.
///
/// {@template flutter.widgets.ViewAnchor}
/// An example use case for this widget is a tooltip for a button. The tooltip
/// should be able to extend beyond the bounds of the main view. For this, the
/// tooltip can be implemented as a separate [View], which is anchored to the
/// button in the main view by wrapping that button with a [ViewAnchor]. In this
/// example, the [view] slot is configured with the tooltip [View] and the
/// [child] is the button widget rendered into the surrounding view.
/// {@endtemplate}
class ViewAnchor extends StatelessWidget {
/// Creates a [ViewAnchor] widget.
const ViewAnchor({
super.key,
this.view,
required this.child,
});
/// The widget that defines the view anchored to this widget.
///
/// Typically, a [View] or [ViewCollection] widget is used, which may be
/// wrapped in other non-[RenderObjectWidget]s (e.g. [InheritedWidget]s).
///
/// {@macro flutter.widgets.ViewAnchor}
final Widget? view;
/// The widget below this widget in the tree.
///
/// It is rendered into the surrounding view, not in the view defined by
/// [view].
///
/// {@macro flutter.widgets.ViewAnchor}
final Widget child;
@override
Widget build(BuildContext context) {
return _MultiChildComponentWidget(
views: <Widget>[
if (view != null)
_ViewScope(
view: null,
child: view!,
),
],
child: child,
);
}
}
class _MultiChildComponentElement extends Element {
_MultiChildComponentElement(super.widget);
List<Element> _viewElements = <Element>[];
final Set<Element> _forgottenViewElements = HashSet<Element>();
Element? _childElement;
bool _debugAssertChildren() {
final _MultiChildComponentWidget typedWidget = widget as _MultiChildComponentWidget;
// Each view widget must have a corresponding element.
assert(_viewElements.length == typedWidget._views.length);
// Iff there is a child widget, it must have a corresponding element.
assert((_childElement == null) == (typedWidget._child == null));
// The child element is not also a view element.
assert(!_viewElements.contains(_childElement));
return true;
}
@override
void attachRenderObject(Object? newSlot) {
super.attachRenderObject(newSlot);
assert(_debugCheckMustAttachRenderObject(newSlot));
}
@override
void mount(Element? parent, Object? newSlot) {
super.mount(parent, newSlot);
assert(_debugCheckMustAttachRenderObject(newSlot));
assert(_viewElements.isEmpty);
assert(_childElement == null);
rebuild();
assert(_debugAssertChildren());
}
@override
void updateSlot(Object? newSlot) {
super.updateSlot(newSlot);
assert(_debugCheckMustAttachRenderObject(newSlot));
}
bool _debugCheckMustAttachRenderObject(Object? slot) {
// Check only applies in the ViewCollection configuration.
if (!kDebugMode || (widget as _MultiChildComponentWidget)._child != null) {
return true;
}
bool hasAncestorRenderObjectElement = false;
bool ancestorWantsRenderObject = true;
visitAncestorElements((Element ancestor) {
if (!ancestor.debugExpectsRenderObjectForSlot(slot)) {
ancestorWantsRenderObject = false;
return false;
}
if (ancestor is RenderObjectElement) {
hasAncestorRenderObjectElement = true;
return false;
}
return true;
});
if (hasAncestorRenderObjectElement && ancestorWantsRenderObject) {
FlutterError.reportError(
FlutterErrorDetails(exception: FlutterError.fromParts(
<DiagnosticsNode>[
ErrorSummary(
'The Element for ${toStringShort()} cannot be inserted into slot "$slot" of its ancestor. ',
),
ErrorDescription(
'The ownership chain for the Element in question was:\n ${debugGetCreatorChain(10)}',
),
ErrorDescription(
'This Element allows the creation of multiple independent render trees, which cannot '
'be attached to an ancestor in an existing render tree. However, an ancestor RenderObject '
'is expecting that a child will be attached.'
),
ErrorHint(
'Try moving the subtree that contains the ${toStringShort()} widget into the '
'view property of a ViewAnchor widget or to the root of the widget tree, where '
'it is not expected to attach its RenderObject to its ancestor.',
),
],
)),
);
}
return true;
}
@override
void update(_MultiChildComponentWidget newWidget) {
// Cannot switch from ViewAnchor config to ViewCollection config.
assert((newWidget._child == null) == ((widget as _MultiChildComponentWidget)._child == null));
super.update(newWidget);
rebuild(force: true);
assert(_debugAssertChildren());
}
static const Object _viewSlot = Object();
@override
bool debugExpectsRenderObjectForSlot(Object? slot) => slot != _viewSlot;
@override
void performRebuild() {
final _MultiChildComponentWidget typedWidget = widget as _MultiChildComponentWidget;
_childElement = updateChild(_childElement, typedWidget._child, slot);
final List<Widget> views = typedWidget._views;
_viewElements = updateChildren(
_viewElements,
views,
forgottenChildren: _forgottenViewElements,
slots: List<Object>.generate(views.length, (_) => _viewSlot),
);
_forgottenViewElements.clear();
super.performRebuild(); // clears the dirty flag
assert(_debugAssertChildren());
}
@override
void forgetChild(Element child) {
if (child == _childElement) {
_childElement = null;
} else {
assert(_viewElements.contains(child));
assert(!_forgottenViewElements.contains(child));
_forgottenViewElements.add(child);
}
super.forgetChild(child);
}
@override
void visitChildren(ElementVisitor visitor) {
if (_childElement != null) {
visitor(_childElement!);
}
for (final Element child in _viewElements) {
if (!_forgottenViewElements.contains(child)) {
visitor(child);
}
}
}
@override
bool get debugDoingBuild => false; // This element does not have a concept of "building".
@override
Element? get renderObjectAttachingChild => _childElement;
@override
List<DiagnosticsNode> debugDescribeChildren() {
final List<DiagnosticsNode> children = <DiagnosticsNode>[];
if (_childElement != null) {
children.add(_childElement!.toDiagnosticsNode());
}
for (int i = 0; i < _viewElements.length; i++) {
children.add(_viewElements[i].toDiagnosticsNode(
name: 'view ${i + 1}',
style: DiagnosticsTreeStyle.offstage,
));
}
return children;
}
}
// A special [GlobalKey] to support passing the deprecated
// [RendererBinding.renderView] and [RendererBinding.pipelineOwner] to the
// [_RawView]. Will be removed when those deprecated properties are removed.
@optionalTypeArgs
class _DeprecatedRawViewKey<T extends State<StatefulWidget>> extends GlobalKey<T> {
const _DeprecatedRawViewKey(this.view, this.owner, this.renderView) : super.constructor();
final FlutterView view;
final PipelineOwner? owner;
final RenderView? renderView;
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType) {
return false;
}
return other is _DeprecatedRawViewKey<T>
&& identical(other.view, view)
&& identical(other.owner, owner)
&& identical(other.renderView, renderView);
}
@override
int get hashCode => Object.hash(view, owner, renderView);
@override
String toString() => '[_DeprecatedRawViewKey ${describeIdentity(view)}]';
}
| flutter/packages/flutter/lib/src/widgets/view.dart/0 | {
"file_path": "flutter/packages/flutter/lib/src/widgets/view.dart",
"repo_id": "flutter",
"token_count": 8743
} | 650 |
// 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();
}
}
| flutter/packages/flutter/test/animation/animation_sheet_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/animation/animation_sheet_test.dart",
"repo_id": "flutter",
"token_count": 1998
} | 651 |
// 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)),
),
);
});
}
| flutter/packages/flutter/test/cupertino/checkbox_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/cupertino/checkbox_test.dart",
"repo_id": "flutter",
"token_count": 5160
} | 652 |
# Tests for the Cupertino+Material mixed usages
In this package, we test for interactions between Material and Cupertino
widgets.
| flutter/packages/flutter/test/cupertino/material/README.md/0 | {
"file_path": "flutter/packages/flutter/test/cupertino/material/README.md",
"repo_id": "flutter",
"token_count": 33
} | 653 |
// 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';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
testWidgets('more than three suggestions throws an error', (WidgetTester tester) async {
Future<void> pumpToolbar(List<String> suggestions) async {
await tester.pumpWidget(
CupertinoApp(
home: Center(
child: CupertinoSpellCheckSuggestionsToolbar(
anchors: const TextSelectionToolbarAnchors(
primaryAnchor: Offset.zero,
),
buttonItems: suggestions.map((String string) {
return ContextMenuButtonItem(
onPressed: () {},
label: string,
);
}).toList(),
),
),
),
);
}
await pumpToolbar(<String>['hello', 'yellow', 'yell']);
expect(() async {
await pumpToolbar(<String>['hello', 'yellow', 'yell', 'yeller']);
}, throwsAssertionError);
},
skip: kIsWeb, // [intended]
);
test('buildSuggestionButtons only considers the first three suggestions', () {
final _FakeEditableTextState editableTextState = _FakeEditableTextState(
suggestions: <String>[
'hello',
'yellow',
'yell',
'yeller',
],
);
final List<ContextMenuButtonItem>? buttonItems =
CupertinoSpellCheckSuggestionsToolbar.buildButtonItems(editableTextState);
expect(buttonItems, isNotNull);
final Iterable<String?> labels = buttonItems!.map((ContextMenuButtonItem buttonItem) {
return buttonItem.label;
});
expect(labels, hasLength(3));
expect(labels, contains('hello'));
expect(labels, contains('yellow'));
expect(labels, contains('yell'));
expect(labels, isNot(contains('yeller')));
});
testWidgets('buildButtonItems builds a disabled "No Replacements Found" button when no suggestions', (WidgetTester tester) async {
final TextEditingController controller = TextEditingController();
addTearDown(controller.dispose);
final FocusNode focusNode = FocusNode();
addTearDown(focusNode.dispose);
await tester.pumpWidget(
CupertinoApp(
home: _FakeEditableText(focusNode, controller),
),
);
final _FakeEditableTextState editableTextState =
tester.state(find.byType(_FakeEditableText));
final List<ContextMenuButtonItem>? buttonItems =
CupertinoSpellCheckSuggestionsToolbar.buildButtonItems(editableTextState);
expect(buttonItems, isNotNull);
expect(buttonItems, hasLength(1));
expect(buttonItems!.first.label, 'No Replacements Found');
expect(buttonItems.first.onPressed, isNull);
});
}
class _FakeEditableText extends EditableText {
/// The parameters focusNode and controller are needed here so the can be
/// safely disposed after the test is completed.
_FakeEditableText(FocusNode focusNode, TextEditingController controller) : super(
controller: controller,
focusNode: focusNode,
backgroundCursorColor: CupertinoColors.white,
cursorColor: CupertinoColors.white,
style: const TextStyle(),
);
@override
_FakeEditableTextState createState() => _FakeEditableTextState();
}
class _FakeEditableTextState extends EditableTextState {
_FakeEditableTextState({
this.suggestions,
});
final List<String>? suggestions;
@override
TextEditingValue get currentTextEditingValue => TextEditingValue.empty;
@override
SuggestionSpan? findSuggestionSpanAtCursorIndex(int cursorIndex) {
return SuggestionSpan(
const TextRange(
start: 0,
end: 0,
),
suggestions ?? <String>[],
);
}
}
| flutter/packages/flutter/test/cupertino/spell_check_suggestions_toolbar_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/cupertino/spell_check_suggestions_toolbar_test.dart",
"repo_id": "flutter",
"token_count": 1476
} | 654 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// A test script that invokes compute() to start an isolate.
import 'package:flutter/src/foundation/_isolates_io.dart';
int getLength(String s) {
return s.length;
}
Future<void> main() async {
const String s = 'hello world';
final int result = await compute(getLength, s);
if (result != s.length) {
throw Exception('compute returned bad result');
}
}
| flutter/packages/flutter/test/foundation/_compute_caller.dart/0 | {
"file_path": "flutter/packages/flutter/test/foundation/_compute_caller.dart",
"repo_id": "flutter",
"token_count": 160
} | 655 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter_test/flutter_test.dart';
class X { }
class Y extends X { }
class A<U extends X> {
U? u;
}
void main() {
test('Assignment through a covariant template throws exception', () {
final A<Y> ay = A<Y>();
final A<X> ayAsAx = ay;
expect(() {
ayAsAx.u = X();
}, throwsA(isA<TypeError>()));
});
}
| flutter/packages/flutter/test/foundation/covariant_templates_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/foundation/covariant_templates_test.dart",
"repo_id": "flutter",
"token_count": 188
} | 656 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter_test/flutter_test.dart';
typedef HandleEventCallback = void Function(PointerEvent event);
class TestGestureFlutterBinding extends BindingBase with GestureBinding {
HandleEventCallback? callback;
@override
void handleEvent(PointerEvent event, HitTestEntry entry) {
if (callback != null) {
callback?.call(event);
}
super.handleEvent(event, entry);
}
static const ui.PointerDataPacket packet = ui.PointerDataPacket(
data: <ui.PointerData>[
ui.PointerData(change: ui.PointerChange.down),
ui.PointerData(change: ui.PointerChange.up),
],
);
Future<void> test(VoidCallback callback) {
return _binding.lockEvents(() async {
GestureBinding.instance.platformDispatcher.onPointerDataPacket?.call(packet);
callback();
});
}
}
late TestGestureFlutterBinding _binding;
void main() {
_binding = TestGestureFlutterBinding();
test('Pointer events are locked during reassemble', () async {
final List<PointerEvent> events = <PointerEvent>[];
_binding.callback = events.add;
bool tested = false;
await _binding.test(() {
expect(events.length, 0);
tested = true;
});
expect(tested, isTrue);
expect(events.length, 2);
expect(events[0], isA<PointerDownEvent>());
expect(events[1], isA<PointerUpEvent>());
});
}
| flutter/packages/flutter/test/gestures/locking_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/gestures/locking_test.dart",
"repo_id": "flutter",
"token_count": 580
} | 657 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('gets local coordinates', (WidgetTester tester) async {
int longPressCount = 0;
int longPressUpCount = 0;
final List<LongPressEndDetails> endDetails = <LongPressEndDetails>[];
final List<LongPressMoveUpdateDetails> moveDetails = <LongPressMoveUpdateDetails>[];
final List<LongPressStartDetails> startDetails = <LongPressStartDetails>[];
final Key redContainer = UniqueKey();
await tester.pumpWidget(
Center(
child: GestureDetector(
onLongPress: () {
longPressCount++;
},
onLongPressEnd: (LongPressEndDetails details) {
endDetails.add(details);
},
onLongPressMoveUpdate: (LongPressMoveUpdateDetails details) {
moveDetails.add(details);
},
onLongPressStart: (LongPressStartDetails details) {
startDetails.add(details);
},
onLongPressUp: () {
longPressUpCount++;
},
child: Container(
key: redContainer,
width: 100,
height: 150,
color: Colors.red,
),
),
),
);
await tester.longPressAt(tester.getCenter(find.byKey(redContainer)));
expect(longPressCount, 1);
expect(longPressUpCount, 1);
expect(moveDetails, isEmpty);
expect(startDetails.single.localPosition, const Offset(50, 75));
expect(startDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails.single.localPosition, const Offset(50, 75));
expect(endDetails.single.globalPosition, const Offset(400, 300));
});
testWidgets('scaled up', (WidgetTester tester) async {
int longPressCount = 0;
int longPressUpCount = 0;
final List<LongPressEndDetails> endDetails = <LongPressEndDetails>[];
final List<LongPressMoveUpdateDetails> moveDetails = <LongPressMoveUpdateDetails>[];
final List<LongPressStartDetails> startDetails = <LongPressStartDetails>[];
final Key redContainer = UniqueKey();
await tester.pumpWidget(
Center(
child: Transform.scale(
scale: 2.0,
child: GestureDetector(
onLongPress: () {
longPressCount++;
},
onLongPressEnd: (LongPressEndDetails details) {
endDetails.add(details);
},
onLongPressMoveUpdate: (LongPressMoveUpdateDetails details) {
moveDetails.add(details);
},
onLongPressStart: (LongPressStartDetails details) {
startDetails.add(details);
},
onLongPressUp: () {
longPressUpCount++;
},
child: Container(
key: redContainer,
width: 100,
height: 150,
color: Colors.red,
),
),
),
),
);
TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(redContainer)));
await gesture.moveBy(const Offset(0, 10.0));
await tester.pump(kLongPressTimeout);
await gesture.up();
expect(longPressCount, 1);
expect(longPressUpCount, 1);
expect(startDetails.single.localPosition, const Offset(50, 75));
expect(startDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails.single.localPosition, const Offset(50, 75 + 10.0 / 2.0));
expect(endDetails.single.globalPosition, const Offset(400, 300.0 + 10.0));
expect(moveDetails, isEmpty); // moved before long press was detected.
startDetails.clear();
endDetails.clear();
longPressCount = 0;
longPressUpCount = 0;
// Move after recognized.
gesture = await tester.startGesture(tester.getCenter(find.byKey(redContainer)));
await tester.pump(kLongPressTimeout);
await gesture.moveBy(const Offset(0, 100));
await gesture.up();
expect(longPressCount, 1);
expect(longPressUpCount, 1);
expect(startDetails.single.localPosition, const Offset(50, 75));
expect(startDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails.single.localPosition, const Offset(50, 75 + 100.0 / 2.0));
expect(endDetails.single.globalPosition, const Offset(400, 300.0 + 100.0));
expect(moveDetails.single.localPosition, const Offset(50, 75 + 100.0 / 2.0));
expect(moveDetails.single.globalPosition, const Offset(400, 300.0 + 100.0));
expect(moveDetails.single.offsetFromOrigin, const Offset(0, 100.0));
expect(moveDetails.single.localOffsetFromOrigin, const Offset(0, 100.0 / 2.0));
});
testWidgets('scaled down', (WidgetTester tester) async {
int longPressCount = 0;
int longPressUpCount = 0;
final List<LongPressEndDetails> endDetails = <LongPressEndDetails>[];
final List<LongPressMoveUpdateDetails> moveDetails = <LongPressMoveUpdateDetails>[];
final List<LongPressStartDetails> startDetails = <LongPressStartDetails>[];
final Key redContainer = UniqueKey();
await tester.pumpWidget(
Center(
child: Transform.scale(
scale: 0.5,
child: GestureDetector(
onLongPress: () {
longPressCount++;
},
onLongPressEnd: (LongPressEndDetails details) {
endDetails.add(details);
},
onLongPressMoveUpdate: (LongPressMoveUpdateDetails details) {
moveDetails.add(details);
},
onLongPressStart: (LongPressStartDetails details) {
startDetails.add(details);
},
onLongPressUp: () {
longPressUpCount++;
},
child: Container(
key: redContainer,
width: 100,
height: 150,
color: Colors.red,
),
),
),
),
);
TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(redContainer)));
await gesture.moveBy(const Offset(0, 10.0));
await tester.pump(kLongPressTimeout);
await gesture.up();
expect(longPressCount, 1);
expect(longPressUpCount, 1);
expect(startDetails.single.localPosition, const Offset(50, 75));
expect(startDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails.single.localPosition, const Offset(50, 75 + 10.0 * 2.0));
expect(endDetails.single.globalPosition, const Offset(400, 300.0 + 10.0));
expect(moveDetails, isEmpty); // moved before long press was detected.
startDetails.clear();
endDetails.clear();
longPressCount = 0;
longPressUpCount = 0;
// Move after recognized.
gesture = await tester.startGesture(tester.getCenter(find.byKey(redContainer)));
await tester.pump(kLongPressTimeout);
await gesture.moveBy(const Offset(0, 100));
await gesture.up();
expect(longPressCount, 1);
expect(longPressUpCount, 1);
expect(startDetails.single.localPosition, const Offset(50, 75));
expect(startDetails.single.globalPosition, const Offset(400, 300));
expect(endDetails.single.localPosition, const Offset(50, 75 + 100.0 * 2.0));
expect(endDetails.single.globalPosition, const Offset(400, 300.0 + 100.0));
expect(moveDetails.single.localPosition, const Offset(50, 75 + 100.0 * 2.0));
expect(moveDetails.single.globalPosition, const Offset(400, 300.0 + 100.0));
expect(moveDetails.single.offsetFromOrigin, const Offset(0, 100.0));
expect(moveDetails.single.localOffsetFromOrigin, const Offset(0, 100.0 * 2.0));
});
}
| flutter/packages/flutter/test/gestures/transformed_long_press_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/gestures/transformed_long_press_test.dart",
"repo_id": "flutter",
"token_count": 3448
} | 658 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
const AppBarTheme appBarTheme = AppBarTheme(
backgroundColor: Color(0xff00ff00),
foregroundColor: Color(0xff00ffff),
elevation: 4.0,
scrolledUnderElevation: 6.0,
shadowColor: Color(0xff1212ff),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(14.0)),
),
iconTheme: IconThemeData(color: Color(0xffff0000)),
actionsIconTheme: IconThemeData(color: Color(0xff0000ff)),
centerTitle: false,
titleSpacing: 10.0,
titleTextStyle: TextStyle(
fontSize: 22.0,
fontStyle: FontStyle.italic,
),
);
ScrollController primaryScrollController(WidgetTester tester) {
return PrimaryScrollController.of(tester.element(find.byType(CustomScrollView)));
}
test('AppBarTheme copyWith, ==, hashCode basics', () {
expect(const AppBarTheme(), const AppBarTheme().copyWith());
expect(const AppBarTheme().hashCode, const AppBarTheme().copyWith().hashCode);
});
test('AppBarTheme lerp special cases', () {
const AppBarTheme data = AppBarTheme();
expect(identical(AppBarTheme.lerp(data, data, 0.5), data), true);
});
testWidgets('Material2 - Passing no AppBarTheme returns defaults', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: false);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(icon: const Icon(Icons.share), onPressed: () { }),
],
),
),
),
);
final Material widget = _getAppBarMaterial(tester);
final IconTheme iconTheme = _getAppBarIconTheme(tester);
final IconTheme actionsIconTheme = _getAppBarActionsIconTheme(tester);
final RichText actionIconText = _getAppBarIconRichText(tester);
final DefaultTextStyle text = _getAppBarText(tester);
expect(SystemChrome.latestStyle!.statusBarBrightness, SystemUiOverlayStyle.light.statusBarBrightness);
expect(widget.color, Colors.blue);
expect(widget.elevation, 4.0);
expect(widget.shadowColor, Colors.black);
expect(widget.surfaceTintColor, null);
expect(widget.shape, null);
expect(iconTheme.data, const IconThemeData(color: Colors.white));
expect(actionsIconTheme.data, const IconThemeData(color: Colors.white));
expect(actionIconText.text.style!.color, Colors.white);
expect(text.style, Typography.material2014().englishLike.bodyMedium!.merge(Typography.material2014().white.bodyMedium));
expect(tester.getSize(find.byType(AppBar)).height, kToolbarHeight);
expect(tester.getSize(find.byType(AppBar)).width, 800);
});
testWidgets('Material3 - Passing no AppBarTheme returns defaults', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: true);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(icon: const Icon(Icons.share), onPressed: () { }),
],
),
),
),
);
final Material widget = _getAppBarMaterial(tester);
final IconTheme iconTheme = _getAppBarIconTheme(tester);
final IconTheme actionsIconTheme = _getAppBarActionsIconTheme(tester);
final RichText actionIconText = _getAppBarIconRichText(tester);
final DefaultTextStyle text = _getAppBarText(tester);
expect(SystemChrome.latestStyle!.statusBarBrightness, Brightness.light);
expect(widget.color, theme.colorScheme.surface);
expect(widget.elevation, 0);
expect(widget.shadowColor, Colors.transparent);
expect(widget.surfaceTintColor, theme.colorScheme.surfaceTint);
expect(widget.shape, null);
expect(iconTheme.data, IconThemeData(color: theme.colorScheme.onSurface, size: 24));
expect(actionsIconTheme.data, IconThemeData(color: theme.colorScheme.onSurfaceVariant, size: 24));
expect(actionIconText.text.style!.color, theme.colorScheme.onSurfaceVariant);
expect(
text.style,
Typography.material2021().englishLike.bodyMedium!
.merge(Typography.material2021().black.bodyMedium)
.copyWith(color: theme.colorScheme.onSurface, decorationColor: theme.colorScheme.onSurface),
);
expect(tester.getSize(find.byType(AppBar)).height, kToolbarHeight);
expect(tester.getSize(find.byType(AppBar)).width, 800);
});
testWidgets('AppBar uses values from AppBarTheme', (WidgetTester tester) async {
final AppBarTheme appBarTheme = _appBarTheme();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(appBarTheme: appBarTheme),
home: Scaffold(
appBar: AppBar(
title: const Text('App Bar Title'),
actions: <Widget>[
IconButton(icon: const Icon(Icons.share), onPressed: () { }),
],
),
),
),
);
final Material widget = _getAppBarMaterial(tester);
final IconTheme iconTheme = _getAppBarIconTheme(tester);
final IconTheme actionsIconTheme = _getAppBarActionsIconTheme(tester);
final RichText actionIconText = _getAppBarIconRichText(tester);
final DefaultTextStyle text = _getAppBarText(tester);
expect(SystemChrome.latestStyle!.statusBarBrightness, Brightness.light);
expect(widget.color, appBarTheme.backgroundColor);
expect(widget.elevation, appBarTheme.elevation);
expect(widget.shadowColor, appBarTheme.shadowColor);
expect(widget.surfaceTintColor, appBarTheme.surfaceTintColor);
expect(widget.shape, const StadiumBorder());
expect(iconTheme.data, appBarTheme.iconTheme);
expect(actionsIconTheme.data, appBarTheme.actionsIconTheme);
expect(actionIconText.text.style!.color, appBarTheme.actionsIconTheme!.color);
expect(text.style, appBarTheme.toolbarTextStyle);
expect(tester.getSize(find.byType(AppBar)).height, appBarTheme.toolbarHeight);
expect(tester.getSize(find.byType(AppBar)).width, 800);
});
testWidgets('AppBar widget properties take priority over theme', (WidgetTester tester) async {
const Brightness brightness = Brightness.dark;
const SystemUiOverlayStyle systemOverlayStyle = SystemUiOverlayStyle.light;
const Color color = Colors.orange;
const double elevation = 3.0;
const Color shadowColor = Colors.purple;
const Color surfaceTintColor = Colors.brown;
const ShapeBorder shape = RoundedRectangleBorder();
const IconThemeData iconThemeData = IconThemeData(color: Colors.green);
const IconThemeData actionsIconThemeData = IconThemeData(color: Colors.lightBlue);
const TextStyle toolbarTextStyle = TextStyle(color: Colors.pink);
const TextStyle titleTextStyle = TextStyle(color: Colors.orange);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light()).copyWith(
appBarTheme: _appBarTheme(),
),
home: Scaffold(
appBar: AppBar(
backgroundColor: color,
systemOverlayStyle: systemOverlayStyle,
elevation: elevation,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
shape: shape,
iconTheme: iconThemeData,
actionsIconTheme: actionsIconThemeData,
toolbarTextStyle: toolbarTextStyle,
titleTextStyle: titleTextStyle,
actions: <Widget>[
IconButton(icon: const Icon(Icons.share), onPressed: () { }),
],
),
),
),
);
final Material widget = _getAppBarMaterial(tester);
final IconTheme iconTheme = _getAppBarIconTheme(tester);
final IconTheme actionsIconTheme = _getAppBarActionsIconTheme(tester);
final RichText actionIconText = _getAppBarIconRichText(tester);
final DefaultTextStyle text = _getAppBarText(tester);
expect(SystemChrome.latestStyle!.statusBarBrightness, brightness);
expect(widget.color, color);
expect(widget.elevation, elevation);
expect(widget.shadowColor, shadowColor);
expect(widget.surfaceTintColor, surfaceTintColor);
expect(widget.shape, shape);
expect(iconTheme.data, iconThemeData);
expect(actionsIconTheme.data, actionsIconThemeData);
expect(actionIconText.text.style!.color, actionsIconThemeData.color);
expect(text.style, toolbarTextStyle);
});
testWidgets('AppBar icon color takes priority over everything', (WidgetTester tester) async {
const Color color = Colors.lime;
const IconThemeData iconThemeData = IconThemeData(color: Colors.green);
const IconThemeData actionsIconThemeData = IconThemeData(color: Colors.lightBlue);
await tester.pumpWidget(MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light()),
home: Scaffold(appBar: AppBar(
iconTheme: iconThemeData,
actionsIconTheme: actionsIconThemeData,
actions: <Widget>[
IconButton(icon: const Icon(Icons.share), color: color, onPressed: () { }),
],
)),
));
final RichText actionIconText = _getAppBarIconRichText(tester);
expect(actionIconText.text.style!.color, color);
});
testWidgets('AppBarTheme properties take priority over ThemeData properties', (WidgetTester tester) async {
final AppBarTheme appBarTheme = _appBarTheme();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light())
.copyWith(appBarTheme: _appBarTheme()),
home: Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(icon: const Icon(Icons.share), onPressed: () { }),
],
),
),
),
);
final Material widget = _getAppBarMaterial(tester);
final IconTheme iconTheme = _getAppBarIconTheme(tester);
final IconTheme actionsIconTheme = _getAppBarActionsIconTheme(tester);
final RichText actionIconText = _getAppBarIconRichText(tester);
final DefaultTextStyle text = _getAppBarText(tester);
expect(SystemChrome.latestStyle!.statusBarBrightness, Brightness.light);
expect(widget.color, appBarTheme.backgroundColor);
expect(widget.elevation, appBarTheme.elevation);
expect(widget.shadowColor, appBarTheme.shadowColor);
expect(widget.surfaceTintColor, appBarTheme.surfaceTintColor);
expect(iconTheme.data, appBarTheme.iconTheme);
expect(actionsIconTheme.data, appBarTheme.actionsIconTheme);
expect(actionIconText.text.style!.color, appBarTheme.actionsIconTheme!.color);
expect(text.style, appBarTheme.toolbarTextStyle);
});
testWidgets('Material2 - ThemeData colorScheme is used when no AppBarTheme is set', (WidgetTester tester) async {
final ThemeData lightTheme = ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: false);
final ThemeData darkTheme = ThemeData.from(colorScheme: const ColorScheme.dark(), useMaterial3: false);
Widget buildFrame(ThemeData appTheme) {
return MaterialApp(
theme: appTheme,
home: Builder(
builder: (BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(icon: const Icon(Icons.share), onPressed: () { }),
],
),
);
},
),
);
}
// AppBar M2 defaults for light themes:
// - elevation: 4
// - shadow color: black
// - surface tint color: null
// - background color: ColorScheme.primary
// - foreground color: ColorScheme.onPrimary
// - actions text: style bodyMedium, foreground color
// - status bar brightness: light (based on color scheme brightness)
await tester.pumpWidget(buildFrame(lightTheme));
Material widget = _getAppBarMaterial(tester);
IconTheme iconTheme = _getAppBarIconTheme(tester);
IconTheme actionsIconTheme = _getAppBarActionsIconTheme(tester);
RichText actionIconText = _getAppBarIconRichText(tester);
DefaultTextStyle text = _getAppBarText(tester);
expect(SystemChrome.latestStyle!.statusBarBrightness, SystemUiOverlayStyle.light.statusBarBrightness);
expect(widget.color, lightTheme.colorScheme.primary);
expect(widget.elevation, 4.0);
expect(widget.shadowColor, Colors.black);
expect(widget.surfaceTintColor, null);
expect(iconTheme.data.color, lightTheme.colorScheme.onPrimary);
expect(actionsIconTheme.data.color, lightTheme.colorScheme.onPrimary);
expect(actionIconText.text.style!.color, lightTheme.colorScheme.onPrimary);
expect(text.style, Typography.material2014().englishLike.bodyMedium!.merge(Typography.material2014().black.bodyMedium).copyWith(color: lightTheme.colorScheme.onPrimary));
// AppBar M2 defaults for dark themes:
// - elevation: 4
// - shadow color: black
// - surface tint color: null
// - background color: ColorScheme.surface
// - foreground color: ColorScheme.onSurface
// - actions text: style bodyMedium, foreground color
// - status bar brightness: dark (based on background color)
await tester.pumpWidget(buildFrame(darkTheme));
await tester.pumpAndSettle(); // Theme change animation
widget = _getAppBarMaterial(tester);
iconTheme = _getAppBarIconTheme(tester);
actionsIconTheme = _getAppBarActionsIconTheme(tester);
actionIconText = _getAppBarIconRichText(tester);
text = _getAppBarText(tester);
expect(SystemChrome.latestStyle!.statusBarBrightness, SystemUiOverlayStyle.light.statusBarBrightness);
expect(widget.color, darkTheme.colorScheme.surface);
expect(widget.elevation, 4.0);
expect(widget.shadowColor, Colors.black);
expect(widget.surfaceTintColor, null);
expect(iconTheme.data.color, darkTheme.colorScheme.onSurface);
expect(actionsIconTheme.data.color, darkTheme.colorScheme.onSurface);
expect(actionIconText.text.style!.color, darkTheme.colorScheme.onSurface);
expect(text.style, Typography.material2014().englishLike.bodyMedium!.merge(Typography.material2014().black.bodyMedium).copyWith(color: darkTheme.colorScheme.onSurface));
});
testWidgets('Material3 - ThemeData colorScheme is used when no AppBarTheme is set', (WidgetTester tester) async {
final ThemeData lightTheme = ThemeData.from(colorScheme: const ColorScheme.light(), useMaterial3: true);
final ThemeData darkTheme = ThemeData.from(colorScheme: const ColorScheme.dark(), useMaterial3: true);
Widget buildFrame(ThemeData appTheme) {
return MaterialApp(
theme: appTheme,
home: Builder(
builder: (BuildContext context) {
return Scaffold(
appBar: AppBar(
actions: <Widget>[
IconButton(icon: const Icon(Icons.share), onPressed: () { }),
],
),
);
},
),
);
}
// M3 AppBar defaults for light themes:
// - elevation: 0
// - shadow color: Colors.transparent
// - surface tint color: ColorScheme.surfaceTint
// - background color: ColorScheme.surface
// - foreground color: ColorScheme.onSurface
// - actions text: style bodyMedium, foreground color
// - status bar brightness: light (based on color scheme brightness)
await tester.pumpWidget(buildFrame(lightTheme));
Material widget = _getAppBarMaterial(tester);
IconTheme iconTheme = _getAppBarIconTheme(tester);
IconTheme actionsIconTheme = _getAppBarActionsIconTheme(tester);
RichText actionIconText = _getAppBarIconRichText(tester);
DefaultTextStyle text = _getAppBarText(tester);
expect(SystemChrome.latestStyle!.statusBarBrightness, Brightness.light);
expect(widget.color, lightTheme.colorScheme.surface);
expect(widget.elevation, 0);
expect(widget.shadowColor, Colors.transparent);
expect(widget.surfaceTintColor, lightTheme.colorScheme.surfaceTint);
expect(iconTheme.data.color, lightTheme.colorScheme.onSurface);
expect(actionsIconTheme.data.color, lightTheme.colorScheme.onSurface);
expect(actionIconText.text.style!.color, lightTheme.colorScheme.onSurface);
expect(text.style, Typography.material2021().englishLike.bodyMedium!.merge(Typography.material2021().black.bodyMedium).copyWith(color: lightTheme.colorScheme.onSurface));
// M3 AppBar defaults for dark themes:
// - elevation: 0
// - shadow color: Colors.transparent
// - surface tint color: ColorScheme.surfaceTint
// - background color: ColorScheme.surface
// - foreground color: ColorScheme.onSurface
// - actions text: style bodyMedium, foreground color
// - status bar brightness: dark (based on background color)
await tester.pumpWidget(buildFrame(darkTheme));
await tester.pumpAndSettle(); // Theme change animation
widget = _getAppBarMaterial(tester);
iconTheme = _getAppBarIconTheme(tester);
actionsIconTheme = _getAppBarActionsIconTheme(tester);
actionIconText = _getAppBarIconRichText(tester);
text = _getAppBarText(tester);
expect(SystemChrome.latestStyle!.statusBarBrightness, Brightness.dark);
expect(widget.color, darkTheme.colorScheme.surface);
expect(widget.elevation, 0);
expect(widget.shadowColor, Colors.transparent);
expect(widget.surfaceTintColor, darkTheme.colorScheme.surfaceTint);
expect(iconTheme.data.color, darkTheme.colorScheme.onSurface);
expect(actionsIconTheme.data.color, darkTheme.colorScheme.onSurface);
expect(actionIconText.text.style!.color, darkTheme.colorScheme.onSurface);
expect(text.style, Typography.material2021().englishLike.bodyMedium!.merge(Typography.material2021().black.bodyMedium).copyWith(color: darkTheme.colorScheme.onSurface, decorationColor: darkTheme.colorScheme.onSurface));
});
testWidgets('AppBar iconTheme with color=null defers to outer IconTheme', (WidgetTester tester) async {
// Verify claim made in https://github.com/flutter/flutter/pull/71184#issuecomment-737419215
Widget buildFrame({ Color? appIconColor, Color? appBarIconColor }) {
return MaterialApp(
theme: ThemeData.from(colorScheme: const ColorScheme.light()),
home: IconTheme(
data: IconThemeData(color: appIconColor),
child: Builder(
builder: (BuildContext context) {
return Scaffold(
appBar: AppBar(
iconTheme: IconThemeData(color: appBarIconColor),
actions: <Widget>[
IconButton(icon: const Icon(Icons.share), onPressed: () { }),
],
),
);
},
),
),
);
}
RichText getIconText() {
return tester.widget<RichText>(
find.descendant(
of: find.byType(Icon),
matching: find.byType(RichText),
),
);
}
await tester.pumpWidget(buildFrame(appIconColor: Colors.lime));
expect(getIconText().text.style!.color, Colors.lime);
await tester.pumpWidget(buildFrame(appIconColor: Colors.lime, appBarIconColor: Colors.purple));
expect(getIconText().text.style!.color, Colors.purple);
});
testWidgets('AppBar uses AppBarTheme.centerTitle when centerTitle is null', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
theme: ThemeData(appBarTheme: const AppBarTheme(centerTitle: true)),
home: Scaffold(appBar: AppBar(
title: const Text('Title'),
)),
));
final NavigationToolbar navToolBar = tester.widget(find.byType(NavigationToolbar));
expect(navToolBar.centerMiddle, true);
});
testWidgets('AppBar.centerTitle takes priority over AppBarTheme.centerTitle', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
theme: ThemeData(appBarTheme: const AppBarTheme(centerTitle: true)),
home: Scaffold(
appBar: AppBar(
title: const Text('Title'),
centerTitle: false,
),
),
));
final NavigationToolbar navToolBar = tester.widget(find.byType(NavigationToolbar));
// The AppBar.centerTitle should be used instead of AppBarTheme.centerTitle.
expect(navToolBar.centerMiddle, false);
});
testWidgets('AppBar.centerTitle adapts to TargetPlatform when AppBarTheme.centerTitle is null', (WidgetTester tester) async{
await tester.pumpWidget(MaterialApp(
theme: ThemeData(platform: TargetPlatform.iOS),
home: Scaffold(appBar: AppBar(
title: const Text('Title'),
)),
));
final NavigationToolbar navToolBar = tester.widget(find.byType(NavigationToolbar));
// When ThemeData.platform is TargetPlatform.iOS, and AppBarTheme is null,
// the value of NavigationToolBar.centerMiddle should be true.
expect(navToolBar.centerMiddle, true);
});
testWidgets('AppBar.shadowColor takes priority over AppBarTheme.shadowColor', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
theme: ThemeData(appBarTheme: const AppBarTheme(shadowColor: Colors.red)),
home: Scaffold(
appBar: AppBar(
title: const Text('Title'),
shadowColor: Colors.yellow,
),
),
));
final AppBar appBar = tester.widget(find.byType(AppBar));
// The AppBar.shadowColor should be used instead of AppBarTheme.shadowColor.
expect(appBar.shadowColor, Colors.yellow);
});
testWidgets('AppBar.surfaceTintColor takes priority over AppBarTheme.surfaceTintColor', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
theme: ThemeData(appBarTheme: const AppBarTheme(surfaceTintColor: Colors.red)),
home: Scaffold(
appBar: AppBar(
title: const Text('Title'),
surfaceTintColor: Colors.yellow,
),
),
));
final AppBar appBar = tester.widget(find.byType(AppBar));
// The AppBar.surfaceTintColor should be used instead of AppBarTheme.surfaceTintColor.
expect(appBar.surfaceTintColor, Colors.yellow);
});
testWidgets('Material3 - AppBarTheme.iconTheme.color takes priority over IconButtonTheme.foregroundColor', (WidgetTester tester) async {
const IconThemeData overallIconTheme = IconThemeData(color: Colors.yellow);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(
iconButtonTheme: IconButtonThemeData(
style: IconButton.styleFrom(foregroundColor: Colors.red),
),
appBarTheme: const AppBarTheme(iconTheme: overallIconTheme),
useMaterial3: true,
),
home: Scaffold(
appBar: AppBar(
leading: IconButton(icon: const Icon(Icons.menu), onPressed: () {},),
actions: <Widget>[ IconButton(icon: const Icon(Icons.add), onPressed: () {},) ],
title: const Text('Title'),
),
),
));
final Color? leadingIconButtonColor = _iconStyle(tester, Icons.menu)?.color;
final Color? actionIconButtonColor = _iconStyle(tester, Icons.add)?.color;
expect(leadingIconButtonColor, overallIconTheme.color);
expect(actionIconButtonColor, overallIconTheme.color);
});
testWidgets('Material3 - AppBarTheme.iconTheme.size takes priority over IconButtonTheme.iconSize', (WidgetTester tester) async {
const IconThemeData overallIconTheme = IconThemeData(size: 30.0);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(
iconButtonTheme: IconButtonThemeData(
style: IconButton.styleFrom(iconSize: 32.0),
),
appBarTheme: const AppBarTheme(iconTheme: overallIconTheme),
useMaterial3: true,
),
home: Scaffold(
appBar: AppBar(
leading: IconButton(icon: const Icon(Icons.menu), onPressed: () {},),
actions: <Widget>[ IconButton(icon: const Icon(Icons.add), onPressed: () {},) ],
title: const Text('Title'),
),
),
));
final double? leadingIconButtonSize = _iconStyle(tester, Icons.menu)?.fontSize;
final double? actionIconButtonSize = _iconStyle(tester, Icons.add)?.fontSize;
expect(leadingIconButtonSize, overallIconTheme.size);
expect(actionIconButtonSize, overallIconTheme.size);
});
testWidgets('Material3 - AppBarTheme.actionsIconTheme.color takes priority over IconButtonTheme.foregroundColor', (WidgetTester tester) async {
const IconThemeData actionsIconTheme = IconThemeData(color: Colors.yellow);
final IconButtonThemeData iconButtonTheme = IconButtonThemeData(
style: IconButton.styleFrom(foregroundColor: Colors.red),
);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(
iconButtonTheme: iconButtonTheme,
appBarTheme: const AppBarTheme(actionsIconTheme: actionsIconTheme),
useMaterial3: true,
),
home: Scaffold(
appBar: AppBar(
leading: IconButton(icon: const Icon(Icons.menu), onPressed: () {},),
actions: <Widget>[ IconButton(icon: const Icon(Icons.add), onPressed: () {},) ],
title: const Text('Title'),
),
),
));
final Color? leadingIconButtonColor = _iconStyle(tester, Icons.menu)?.color;
final Color? actionIconButtonColor = _iconStyle(tester, Icons.add)?.color;
expect(leadingIconButtonColor, Colors.red); // leading color should come from iconButtonTheme
expect(actionIconButtonColor, actionsIconTheme.color);
});
testWidgets('Material3 - AppBarTheme.actionsIconTheme.size takes priority over IconButtonTheme.iconSize', (WidgetTester tester) async {
const IconThemeData actionsIconTheme = IconThemeData(size: 30.0);
final IconButtonThemeData iconButtonTheme = IconButtonThemeData(
style: IconButton.styleFrom(iconSize: 32.0),
);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(
iconButtonTheme: iconButtonTheme,
appBarTheme: const AppBarTheme(actionsIconTheme: actionsIconTheme),
useMaterial3: true,
),
home: Scaffold(
appBar: AppBar(
leading: IconButton(icon: const Icon(Icons.menu), onPressed: () {},),
actions: <Widget>[ IconButton(icon: const Icon(Icons.add), onPressed: () {},) ],
title: const Text('Title'),
),
),
));
final double? leadingIconButtonSize = _iconStyle(tester, Icons.menu)?.fontSize;
final double? actionIconButtonSize = _iconStyle(tester, Icons.add)?.fontSize;
expect(leadingIconButtonSize, 32.0); // The size of leading icon button should come from iconButtonTheme
expect(actionIconButtonSize, actionsIconTheme.size);
});
testWidgets('Material3 - AppBarTheme.foregroundColor takes priority over IconButtonTheme.foregroundColor', (WidgetTester tester) async {
final IconButtonThemeData iconButtonTheme = IconButtonThemeData(
style: IconButton.styleFrom(foregroundColor: Colors.red),
);
const AppBarTheme appBarTheme = AppBarTheme(
foregroundColor: Colors.green,
);
final ThemeData themeData = ThemeData(
iconButtonTheme: iconButtonTheme,
appBarTheme: appBarTheme,
useMaterial3: true,
);
await tester.pumpWidget(
MaterialApp(
theme: themeData,
home: Scaffold(
appBar: AppBar(
title: const Text('title'),
leading: IconButton(icon: const Icon(Icons.menu), onPressed: () {}),
actions: <Widget>[
IconButton(icon: const Icon(Icons.add), onPressed: () {}),
],
),
),
),
);
final Color? leadingIconButtonColor = _iconStyle(tester, Icons.menu)?.color;
final Color? actionIconButtonColor = _iconStyle(tester, Icons.add)?.color;
expect(leadingIconButtonColor, appBarTheme.foregroundColor);
expect(actionIconButtonColor, appBarTheme.foregroundColor);
});
testWidgets('AppBar uses AppBarTheme.titleSpacing', (WidgetTester tester) async {
const double kTitleSpacing = 10;
await tester.pumpWidget(MaterialApp(
theme: ThemeData(appBarTheme: const AppBarTheme(titleSpacing: kTitleSpacing)),
home: Scaffold(
appBar: AppBar(
title: const Text('Title'),
),
),
));
final NavigationToolbar navToolBar = tester.widget(find.byType(NavigationToolbar));
expect(navToolBar.middleSpacing, kTitleSpacing);
});
testWidgets('AppBar.titleSpacing takes priority over AppBarTheme.titleSpacing', (WidgetTester tester) async {
const double kTitleSpacing = 10;
await tester.pumpWidget(MaterialApp(
theme: ThemeData(appBarTheme: const AppBarTheme(titleSpacing: kTitleSpacing)),
home: Scaffold(
appBar: AppBar(
title: const Text('Title'),
titleSpacing: 40,
),
),
));
final NavigationToolbar navToolBar = tester.widget(find.byType(NavigationToolbar));
expect(navToolBar.middleSpacing, 40);
});
testWidgets('SliverAppBar uses AppBarTheme.titleSpacing', (WidgetTester tester) async {
const double kTitleSpacing = 10;
await tester.pumpWidget(MaterialApp(
theme: ThemeData(appBarTheme: const AppBarTheme(titleSpacing: kTitleSpacing)),
home: const CustomScrollView(
slivers: <Widget>[
SliverAppBar(
title: Text('Title'),
),
],
),
));
final NavigationToolbar navToolBar = tester.widget(find.byType(NavigationToolbar));
expect(navToolBar.middleSpacing, kTitleSpacing);
});
testWidgets('SliverAppBar.titleSpacing takes priority over AppBarTheme.titleSpacing ', (WidgetTester tester) async {
const double kTitleSpacing = 10;
await tester.pumpWidget(MaterialApp(
theme: ThemeData(appBarTheme: const AppBarTheme(titleSpacing: kTitleSpacing)),
home: const CustomScrollView(
slivers: <Widget>[
SliverAppBar(
title: Text('Title'),
titleSpacing: 40,
),
],
),
));
final NavigationToolbar navToolbar = tester.widget(find.byType(NavigationToolbar));
expect(navToolbar.middleSpacing, 40);
});
testWidgets('SliverAppBar.medium uses AppBarTheme properties', (WidgetTester tester) async {
const String title = 'Medium App Bar';
await tester.pumpWidget(MaterialApp(
theme: ThemeData(appBarTheme: appBarTheme),
home: CustomScrollView(
primary: true,
slivers: <Widget>[
SliverAppBar.medium(
leading: IconButton(
onPressed: () {},
icon: const Icon(Icons.menu),
),
title: const Text(title),
actions: <Widget>[
IconButton(
onPressed: () {},
icon: const Icon(Icons.search),
),
],
),
],
),
));
// Test title.
final RichText titleText = tester.firstWidget(find.byType(RichText));
expect(titleText.text.style!.fontSize, appBarTheme.titleTextStyle!.fontSize);
expect(titleText.text.style!.fontStyle, appBarTheme.titleTextStyle!.fontStyle);
// Test background color, shadow color, and shape.
final Material material = tester.widget<Material>(
find.descendant(
of: find.byType(SliverAppBar),
matching: find.byType(Material).first,
),
);
expect(material.color, appBarTheme.backgroundColor);
expect(material.shadowColor, appBarTheme.shadowColor);
expect(material.shape, appBarTheme.shape);
final RichText actionIcon = tester.widget(find.byType(RichText).last);
expect(actionIcon.text.style!.color, appBarTheme.actionsIconTheme!.color);
// Scroll to collapse the SliverAppBar.
final ScrollController controller = primaryScrollController(tester);
controller.jumpTo(120);
await tester.pumpAndSettle();
// Test title spacing.
final Finder collapsedTitle = find.text(title).last;
final Offset titleOffset = tester.getTopLeft(collapsedTitle);
final Offset iconOffset = tester.getTopRight(find.ancestor(of: find.widgetWithIcon(IconButton, Icons.menu), matching: find.byType(ConstrainedBox)));
expect(titleOffset.dx, iconOffset.dx + appBarTheme.titleSpacing!);
});
testWidgets('SliverAppBar.medium properties take priority over AppBarTheme properties', (WidgetTester tester) async {
const String title = 'Medium App Bar';
const Color backgroundColor = Color(0xff000099);
const Color foregroundColor = Color(0xff00ff98);
const Color shadowColor = Color(0xff00ff97);
const ShapeBorder shape = RoundedRectangleBorder(
borderRadius: BorderRadiusDirectional.only(bottomStart: Radius.circular(12.0)),
);
const IconThemeData iconTheme = IconThemeData(color: Color(0xff00ff96));
const IconThemeData actionsIconTheme = IconThemeData(color: Color(0xff00ff95));
const double titleSpacing = 18.0;
const TextStyle titleTextStyle = TextStyle(
fontSize: 22.9,
fontStyle: FontStyle.italic,
);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(appBarTheme: appBarTheme),
home: CustomScrollView(
primary: true,
slivers: <Widget>[
SliverAppBar.medium(
centerTitle: false,
backgroundColor: backgroundColor,
foregroundColor: foregroundColor,
shadowColor: shadowColor,
shape: shape,
iconTheme: iconTheme,
actionsIconTheme: actionsIconTheme,
titleSpacing: titleSpacing,
titleTextStyle: titleTextStyle,
leading: IconButton(
onPressed: () {},
icon: const Icon(Icons.menu),
),
title: const Text(title),
actions: <Widget>[
IconButton(
onPressed: () {},
icon: const Icon(Icons.search),
),
],
),
],
),
));
// Test title.
final RichText titleText = tester.firstWidget(find.byType(RichText));
expect(titleText.text.style, titleTextStyle);
// Test background color, shadow color, and shape.
final Material material = tester.widget<Material>(
find.descendant(
of: find.byType(SliverAppBar),
matching: find.byType(Material).first,
),
);
expect(material.color, backgroundColor);
expect(material.shadowColor, shadowColor);
expect(material.shape, shape);
final RichText actionIcon = tester.widget(find.byType(RichText).last);
expect(actionIcon.text.style!.color, actionsIconTheme.color);
// Scroll to collapse the SliverAppBar.
final ScrollController controller = primaryScrollController(tester);
controller.jumpTo(120);
await tester.pumpAndSettle();
// Test title spacing.
final Finder collapsedTitle = find.text(title).last;
final Offset titleOffset = tester.getTopLeft(collapsedTitle);
final Offset iconOffset = tester.getTopRight(find.ancestor(of: find.widgetWithIcon(IconButton, Icons.menu), matching: find.byType(ConstrainedBox)));
expect(titleOffset.dx, iconOffset.dx + titleSpacing);
});
testWidgets('SliverAppBar.large uses AppBarTheme properties', (WidgetTester tester) async {
const String title = 'Large App Bar';
await tester.pumpWidget(MaterialApp(
theme: ThemeData(appBarTheme: appBarTheme),
home: CustomScrollView(
primary: true,
slivers: <Widget>[
SliverAppBar.large(
leading: IconButton(
onPressed: () {},
icon: const Icon(Icons.menu),
),
title: const Text(title),
actions: <Widget>[
IconButton(
onPressed: () {},
icon: const Icon(Icons.search),
),
],
),
],
),
));
// Test title.
final RichText titleText = tester.firstWidget(find.byType(RichText));
expect(titleText.text.style!.fontSize, appBarTheme.titleTextStyle!.fontSize);
expect(titleText.text.style!.fontStyle, appBarTheme.titleTextStyle!.fontStyle);
// Test background color, shadow color, and shape.
final Material material = tester.widget<Material>(
find.descendant(
of: find.byType(SliverAppBar),
matching: find.byType(Material).first,
),
);
expect(material.color, appBarTheme.backgroundColor);
expect(material.shadowColor, appBarTheme.shadowColor);
expect(material.shape, appBarTheme.shape);
final RichText actionIcon = tester.widget(find.byType(RichText).last);
expect(actionIcon.text.style!.color, appBarTheme.actionsIconTheme!.color);
// Scroll to collapse the SliverAppBar.
final ScrollController controller = primaryScrollController(tester);
controller.jumpTo(120);
await tester.pumpAndSettle();
// Test title spacing.
final Finder collapsedTitle = find.text(title).last;
final Offset titleOffset = tester.getTopLeft(collapsedTitle);
final Offset iconOffset = tester.getTopRight(find.ancestor(of: find.widgetWithIcon(IconButton, Icons.menu), matching: find.byType(ConstrainedBox)));
expect(titleOffset.dx, iconOffset.dx + appBarTheme.titleSpacing!);
});
testWidgets('SliverAppBar.large properties take priority over AppBarTheme properties', (WidgetTester tester) async {
const String title = 'Large App Bar';
const Color backgroundColor = Color(0xff000099);
const Color foregroundColor = Color(0xff00ff98);
const Color shadowColor = Color(0xff00ff97);
const ShapeBorder shape = RoundedRectangleBorder(
borderRadius: BorderRadiusDirectional.only(bottomStart: Radius.circular(12.0)),
);
const IconThemeData iconTheme = IconThemeData(color: Color(0xff00ff96));
const IconThemeData actionsIconTheme = IconThemeData(color: Color(0xff00ff95));
const double titleSpacing = 18.0;
const TextStyle titleTextStyle = TextStyle(
fontSize: 22.9,
fontStyle: FontStyle.italic,
);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(appBarTheme: appBarTheme),
home: CustomScrollView(
primary: true,
slivers: <Widget>[
SliverAppBar.large(
centerTitle: false,
backgroundColor: backgroundColor,
foregroundColor: foregroundColor,
shadowColor: shadowColor,
shape: shape,
iconTheme: iconTheme,
actionsIconTheme: actionsIconTheme,
titleSpacing: titleSpacing,
titleTextStyle: titleTextStyle,
leading: IconButton(
onPressed: () {},
icon: const Icon(Icons.menu),
),
title: const Text(title),
actions: <Widget>[
IconButton(
onPressed: () {},
icon: const Icon(Icons.search),
),
],
),
],
),
));
// Test title.
final RichText titleText = tester.firstWidget(find.byType(RichText));
expect(titleText.text.style, titleTextStyle);
// Test background color, shadow color, and shape.
final Material material = tester.widget<Material>(
find.descendant(
of: find.byType(SliverAppBar),
matching: find.byType(Material).first,
),
);
expect(material.color, backgroundColor);
expect(material.shadowColor, shadowColor);
expect(material.shape, shape);
final RichText actionIcon = tester.widget(find.byType(RichText).last);
expect(actionIcon.text.style!.color, actionsIconTheme.color);
// Scroll to collapse the SliverAppBar.
final ScrollController controller = primaryScrollController(tester);
controller.jumpTo(120);
await tester.pumpAndSettle();
// Test title spacing.
final Finder collapsedTitle = find.text(title).last;
final Offset titleOffset = tester.getTopLeft(collapsedTitle);
final Offset iconOffset = tester.getTopRight(find.ancestor(of: find.widgetWithIcon(IconButton, Icons.menu), matching: find.byType(ConstrainedBox)));
expect(titleOffset.dx, iconOffset.dx + titleSpacing);
});
testWidgets(
'SliverAppBar medium & large supports foregroundColor', (WidgetTester tester) async {
const String title = 'AppBar title';
const AppBarTheme appBarTheme = AppBarTheme(foregroundColor: Color(0xff00ff20));
const Color foregroundColor = Color(0xff001298);
Widget buildWidget({ Color? color, AppBarTheme? appBarTheme }) {
return MaterialApp(
theme: ThemeData(appBarTheme: appBarTheme),
home: CustomScrollView(
primary: true,
slivers: <Widget>[
SliverAppBar.medium(
foregroundColor: color,
title: const Text(title),
),
SliverAppBar.large(
foregroundColor: color,
title: const Text(title),
),
],
),
);
}
await tester.pumpWidget(buildWidget(appBarTheme: appBarTheme));
// Test AppBarTheme.foregroundColor parameter.
RichText mediumTitle = tester.widget(find.byType(RichText).first);
expect(mediumTitle.text.style!.color, appBarTheme.foregroundColor);
RichText largeTitle = tester.widget(find.byType(RichText).first);
expect(largeTitle.text.style!.color, appBarTheme.foregroundColor);
await tester.pumpWidget(buildWidget(
color: foregroundColor, appBarTheme: appBarTheme),
);
// Test foregroundColor parameter.
mediumTitle = tester.widget(find.byType(RichText).first);
expect(mediumTitle.text.style!.color, foregroundColor);
largeTitle = tester.widget(find.byType(RichText).first);
expect(largeTitle.text.style!.color, foregroundColor);
});
testWidgets('Default AppBarTheme debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const AppBarTheme().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('AppBarTheme implements debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const AppBarTheme(
backgroundColor: Color(0xff000000),
foregroundColor: Color(0xff000001),
elevation: 8.0,
scrolledUnderElevation: 3,
shadowColor: Color(0xff000002),
surfaceTintColor: Color(0xff000003),
shape: StadiumBorder(),
iconTheme: IconThemeData(color: Color(0xff000004)),
centerTitle: true,
titleSpacing: 40.0,
toolbarHeight: 96,
toolbarTextStyle: TextStyle(color: Color(0xff000005)),
titleTextStyle: TextStyle(color: Color(0xff000006)),
systemOverlayStyle: SystemUiOverlayStyle(
systemNavigationBarColor: Color(0xff000007),
),
).debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(
description,
equalsIgnoringHashCodes(
<String>[
'backgroundColor: Color(0xff000000)',
'foregroundColor: Color(0xff000001)',
'elevation: 8.0',
'scrolledUnderElevation: 3.0',
'shadowColor: Color(0xff000002)',
'surfaceTintColor: Color(0xff000003)',
'shape: StadiumBorder(BorderSide(width: 0.0, style: none))',
'iconTheme: IconThemeData#00000(color: Color(0xff000004))',
'centerTitle: true',
'titleSpacing: 40.0',
'toolbarHeight: 96.0',
'toolbarTextStyle: TextStyle(inherit: true, color: Color(0xff000005))',
'titleTextStyle: TextStyle(inherit: true, color: Color(0xff000006))'
],
),
);
// On the web, Dart doubles and ints are backed by the same kind of object because
// JavaScript does not support integers. So, the Dart double "4.0" is identical
// to "4", which results in the web evaluating to the value "4" regardless of which
// one is used. This results in a difference for doubles in debugFillProperties between
// the web and the rest of Flutter's target platforms.
}, skip: kIsWeb); // https://github.com/flutter/flutter/issues/87364
// This is a regression test for https://github.com/flutter/flutter/issues/130485.
testWidgets('Material3 - AppBarTheme.iconTheme correctly applies custom white color in dark mode', (WidgetTester tester) async {
final ThemeData themeData = ThemeData(
useMaterial3: true,
brightness: Brightness.dark,
appBarTheme: const AppBarTheme(iconTheme: IconThemeData(color: Colors.white)),
);
await tester.pumpWidget(
MaterialApp(
theme: themeData,
home: Scaffold(
appBar: AppBar(
leading: IconButton(icon: const Icon(Icons.menu), onPressed: () {}),
actions: <Widget>[
IconButton(icon: const Icon(Icons.add), onPressed: () {}),
],
),
),
),
);
Color? leadingIconButtonColor() => _iconStyle(tester, Icons.menu)?.color;
Color? actionIconButtonColor() => _iconStyle(tester, Icons.add)?.color;
expect(leadingIconButtonColor(), Colors.white);
expect(actionIconButtonColor(), Colors.white);
});
}
AppBarTheme _appBarTheme() {
const SystemUiOverlayStyle systemOverlayStyle = SystemUiOverlayStyle.dark;
const Color backgroundColor = Colors.lightBlue;
const double elevation = 6.0;
const Color shadowColor = Colors.red;
const Color surfaceTintColor = Colors.green;
const IconThemeData iconThemeData = IconThemeData(color: Colors.black);
const IconThemeData actionsIconThemeData = IconThemeData(color: Colors.pink);
return const AppBarTheme(
actionsIconTheme: actionsIconThemeData,
systemOverlayStyle: systemOverlayStyle,
backgroundColor: backgroundColor,
elevation: elevation,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
shape: StadiumBorder(),
iconTheme: iconThemeData,
toolbarHeight: 96,
toolbarTextStyle: TextStyle(color: Colors.yellow),
titleTextStyle: TextStyle(color: Colors.pink),
);
}
Material _getAppBarMaterial(WidgetTester tester) {
return tester.widget<Material>(
find.descendant(
of: find.byType(AppBar),
matching: find.byType(Material),
).first,
);
}
IconTheme _getAppBarIconTheme(WidgetTester tester) {
return tester.widget<IconTheme>(
find.descendant(
of: find.byType(AppBar),
matching: find.byType(IconTheme),
).first,
);
}
IconTheme _getAppBarActionsIconTheme(WidgetTester tester) {
return tester.widget<IconTheme>(
find.descendant(
of: find.byType(NavigationToolbar),
matching: find.byType(IconTheme),
).first,
);
}
RichText _getAppBarIconRichText(WidgetTester tester) {
return tester.widget<RichText>(
find.descendant(
of: find.byType(Icon),
matching: find.byType(RichText),
).first,
);
}
DefaultTextStyle _getAppBarText(WidgetTester tester) {
return tester.widget<DefaultTextStyle>(
find.descendant(
of: find.byType(CustomSingleChildLayout),
matching: find.byType(DefaultTextStyle),
).first,
);
}
TextStyle? _iconStyle(WidgetTester tester, IconData icon) {
final RichText iconRichText = tester.widget<RichText>(
find.descendant(of: find.byIcon(icon).first, matching: find.byType(RichText)),
);
return iconRichText.text.style;
}
| flutter/packages/flutter/test/material/app_bar_theme_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/app_bar_theme_test.dart",
"repo_id": "flutter",
"token_count": 18059
} | 659 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('BottomSheetThemeData copyWith, ==, hashCode basics', () {
expect(const BottomSheetThemeData(), const BottomSheetThemeData().copyWith());
expect(const BottomSheetThemeData().hashCode, const BottomSheetThemeData().copyWith().hashCode);
});
test('BottomSheetThemeData lerp special cases', () {
expect(BottomSheetThemeData.lerp(null, null, 0), null);
const BottomSheetThemeData data = BottomSheetThemeData();
expect(identical(BottomSheetThemeData.lerp(data, data, 0.5), data), true);
});
test('BottomSheetThemeData lerp special cases', () {
expect(BottomSheetThemeData.lerp(null, null, 0), null);
const BottomSheetThemeData data = BottomSheetThemeData();
expect(identical(BottomSheetThemeData.lerp(data, data, 0.5), data), true);
});
test('BottomSheetThemeData null fields by default', () {
const BottomSheetThemeData bottomSheetTheme = BottomSheetThemeData();
expect(bottomSheetTheme.backgroundColor, null);
expect(bottomSheetTheme.shadowColor, null);
expect(bottomSheetTheme.elevation, null);
expect(bottomSheetTheme.shape, null);
expect(bottomSheetTheme.clipBehavior, null);
expect(bottomSheetTheme.constraints, null);
expect(bottomSheetTheme.dragHandleColor, null);
expect(bottomSheetTheme.dragHandleSize, null);
});
testWidgets('Default BottomSheetThemeData debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const BottomSheetThemeData().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('BottomSheetThemeData implements debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const BottomSheetThemeData(
backgroundColor: Color(0xFFFFFFFF),
elevation: 2.0,
shadowColor: Color(0xFF00FFFF),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2.0))),
clipBehavior: Clip.antiAlias,
constraints: BoxConstraints(minWidth: 200, maxWidth: 640),
dragHandleColor: Color(0xFFFFFFFF),
dragHandleSize: Size(20, 20)
).debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(description, <String>[
'backgroundColor: Color(0xffffffff)',
'elevation: 2.0',
'shadowColor: Color(0xff00ffff)',
'shape: RoundedRectangleBorder(BorderSide(width: 0.0, style: none), BorderRadius.circular(2.0))',
'dragHandleColor: Color(0xffffffff)',
'dragHandleSize: Size(20.0, 20.0)',
'clipBehavior: Clip.antiAlias',
'constraints: BoxConstraints(200.0<=w<=640.0, 0.0<=h<=Infinity)',
]);
});
testWidgets('Material3 - Passing no BottomSheetThemeData returns defaults', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(
body: BottomSheet(
onClosing: () {},
builder: (BuildContext context) {
return Container();
},
),
),
));
final Material material = tester.widget<Material>(
find.descendant(
of: find.byType(BottomSheet),
matching: find.byType(Material),
),
);
final ThemeData theme = Theme.of(tester.element(find.byType(Scaffold)));
expect(material.color, theme.colorScheme.surfaceContainerLow);
expect(material.elevation, 1.0);
expect(material.shape, const RoundedRectangleBorder(borderRadius: BorderRadius.vertical(top: Radius.circular(28.0))));
expect(material.clipBehavior, Clip.none);
});
testWidgets('Material2 - Passing no BottomSheetThemeData returns defaults', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
body: BottomSheet(
onClosing: () {},
builder: (BuildContext context) {
return Container();
},
),
),
));
final Material material = tester.widget<Material>(
find.descendant(
of: find.byType(BottomSheet),
matching: find.byType(Material),
),
);
expect(material.color, null);
expect(material.elevation, 0.0);
expect(material.shape, null);
expect(material.clipBehavior, Clip.none);
});
testWidgets('BottomSheet uses values from BottomSheetThemeData', (WidgetTester tester) async {
final BottomSheetThemeData bottomSheetTheme = _bottomSheetTheme();
await tester.pumpWidget(MaterialApp(
theme: ThemeData(bottomSheetTheme: bottomSheetTheme),
home: Scaffold(
body: BottomSheet(
onClosing: () {},
builder: (BuildContext context) {
return Container();
},
),
),
));
final Material material = tester.widget<Material>(
find.descendant(
of: find.byType(BottomSheet),
matching: find.byType(Material),
),
);
expect(material.color, bottomSheetTheme.backgroundColor);
expect(material.elevation, bottomSheetTheme.elevation);
expect(material.shape, bottomSheetTheme.shape);
expect(material.clipBehavior, bottomSheetTheme.clipBehavior);
});
testWidgets('BottomSheet widget properties take priority over theme', (WidgetTester tester) async {
const Color backgroundColor = Colors.purple;
const Color shadowColor = Colors.blue;
const double elevation = 7.0;
const ShapeBorder shape = RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(9.0)),
);
const Clip clipBehavior = Clip.hardEdge;
await tester.pumpWidget(MaterialApp(
theme: ThemeData(bottomSheetTheme: _bottomSheetTheme()),
home: Scaffold(
body: BottomSheet(
backgroundColor: backgroundColor,
shadowColor: shadowColor,
elevation: elevation,
shape: shape,
clipBehavior: Clip.hardEdge,
onClosing: () {},
builder: (BuildContext context) {
return Container();
},
),
),
));
final Material material = tester.widget<Material>(
find.descendant(
of: find.byType(BottomSheet),
matching: find.byType(Material),
),
);
expect(material.color, backgroundColor);
expect(material.shadowColor, shadowColor);
expect(material.elevation, elevation);
expect(material.shape, shape);
expect(material.clipBehavior, clipBehavior);
});
testWidgets('Modal bottom sheet-specific parameters are used for modal bottom sheets', (WidgetTester tester) async {
const double modalElevation = 5.0;
const double persistentElevation = 7.0;
const Color modalBackgroundColor = Colors.yellow;
const Color modalBarrierColor = Colors.blue;
const Color persistentBackgroundColor = Colors.red;
const BottomSheetThemeData bottomSheetTheme = BottomSheetThemeData(
elevation: persistentElevation,
modalElevation: modalElevation,
backgroundColor: persistentBackgroundColor,
modalBackgroundColor: modalBackgroundColor,
modalBarrierColor:modalBarrierColor,
);
await tester.pumpWidget(bottomSheetWithElevations(bottomSheetTheme));
await tester.tap(find.text('Show Modal'));
await tester.pumpAndSettle();
final Material material = tester.widget<Material>(
find.descendant(
of: find.byType(BottomSheet),
matching: find.byType(Material),
),
);
expect(material.elevation, modalElevation);
expect(material.color, modalBackgroundColor);
final ModalBarrier modalBarrier = tester.widget(find.byType(ModalBarrier).last);
expect(modalBarrier.color, modalBarrierColor);
});
testWidgets('General bottom sheet parameters take priority over modal bottom sheet-specific parameters for persistent bottom sheets', (WidgetTester tester) async {
const double modalElevation = 5.0;
const double persistentElevation = 7.0;
const Color modalBackgroundColor = Colors.yellow;
const Color persistentBackgroundColor = Colors.red;
const BottomSheetThemeData bottomSheetTheme = BottomSheetThemeData(
elevation: persistentElevation,
modalElevation: modalElevation,
backgroundColor: persistentBackgroundColor,
modalBackgroundColor: modalBackgroundColor,
);
await tester.pumpWidget(bottomSheetWithElevations(bottomSheetTheme));
await tester.tap(find.text('Show Persistent'));
await tester.pumpAndSettle();
final Material material = tester.widget<Material>(
find.descendant(
of: find.byType(BottomSheet),
matching: find.byType(Material),
),
);
expect(material.elevation, persistentElevation);
expect(material.color, persistentBackgroundColor);
});
testWidgets("Material3 - Modal bottom sheet-specific parameters don't apply to persistent bottom sheets", (WidgetTester tester) async {
const double modalElevation = 5.0;
const Color modalBackgroundColor = Colors.yellow;
const BottomSheetThemeData bottomSheetTheme = BottomSheetThemeData(
modalElevation: modalElevation,
modalBackgroundColor: modalBackgroundColor,
);
await tester.pumpWidget(bottomSheetWithElevations(bottomSheetTheme));
await tester.tap(find.text('Show Persistent'));
await tester.pumpAndSettle();
final Material material = tester.widget<Material>(
find.descendant(
of: find.byType(BottomSheet),
matching: find.byType(Material),
),
);
expect(material.elevation, 1.0);
final ThemeData theme = Theme.of(tester.element(find.byType(Scaffold)));
expect(material.color, theme.colorScheme.surfaceContainerLow);
});
testWidgets("Material2 - Modal bottom sheet-specific parameters don't apply to persistent bottom sheets", (WidgetTester tester) async {
const double modalElevation = 5.0;
const Color modalBackgroundColor = Colors.yellow;
const BottomSheetThemeData bottomSheetTheme = BottomSheetThemeData(
modalElevation: modalElevation,
modalBackgroundColor: modalBackgroundColor,
);
await tester.pumpWidget(bottomSheetWithElevations(bottomSheetTheme, useMaterial3: false));
await tester.tap(find.text('Show Persistent'));
await tester.pumpAndSettle();
final Material material = tester.widget<Material>(
find.descendant(
of: find.byType(BottomSheet),
matching: find.byType(Material),
),
);
expect(material.elevation, 0);
expect(material.color, null);
});
testWidgets('Modal bottom sheets respond to theme changes', (WidgetTester tester) async {
const double lightElevation = 5.0;
const double darkElevation = 3.0;
const Color lightBackgroundColor = Colors.green;
const Color darkBackgroundColor = Colors.grey;
const Color lightShadowColor = Colors.blue;
const Color darkShadowColor = Colors.purple;
await tester.pumpWidget(MaterialApp(
theme: ThemeData.light().copyWith(
bottomSheetTheme: const BottomSheetThemeData(
elevation: lightElevation,
backgroundColor: lightBackgroundColor,
shadowColor: lightShadowColor,
),
),
darkTheme: ThemeData.dark().copyWith(
bottomSheetTheme: const BottomSheetThemeData(
elevation: darkElevation,
backgroundColor: darkBackgroundColor,
shadowColor: darkShadowColor,
),
),
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return Column(
children: <Widget>[
RawMaterialButton(
child: const Text('Show Modal'),
onPressed: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return const Text('This is a modal bottom sheet.');
},
);
},
),
],
);
},
),
),
));
await tester.tap(find.text('Show Modal'));
await tester.pumpAndSettle();
final Material lightMaterial = tester.widget<Material>(
find.descendant(
of: find.byType(BottomSheet),
matching: find.byType(Material),
),
);
expect(lightMaterial.elevation, lightElevation);
expect(lightMaterial.color, lightBackgroundColor);
expect(lightMaterial.shadowColor, lightShadowColor);
// Simulate the user changing to dark theme
tester.binding.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
await tester.pumpAndSettle();
final Material darkMaterial = tester.widget<Material>(
find.descendant(
of: find.byType(BottomSheet),
matching: find.byType(Material),
),
);
expect(darkMaterial.elevation, darkElevation);
expect(darkMaterial.color, darkBackgroundColor);
expect(darkMaterial.shadowColor, darkShadowColor);
});
}
Widget bottomSheetWithElevations(BottomSheetThemeData bottomSheetTheme, {bool useMaterial3 = true}) {
return MaterialApp(
theme: ThemeData(bottomSheetTheme: bottomSheetTheme, useMaterial3: useMaterial3),
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return Column(
children: <Widget>[
RawMaterialButton(
child: const Text('Show Modal'),
onPressed: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext _) {
return const Text(
'This is a modal bottom sheet.',
);
},
);
},
),
RawMaterialButton(
child: const Text('Show Persistent'),
onPressed: () {
showBottomSheet(
context: context,
builder: (BuildContext _) {
return const Text(
'This is a persistent bottom sheet.',
);
},
);
},
),
],
);
},
),
),
);
}
BottomSheetThemeData _bottomSheetTheme() {
return const BottomSheetThemeData(
backgroundColor: Colors.orange,
elevation: 12.0,
shape: BeveledRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(12))),
clipBehavior: Clip.antiAlias,
);
}
| flutter/packages/flutter/test/material/bottom_sheet_theme_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/bottom_sheet_theme_test.dart",
"repo_id": "flutter",
"token_count": 6098
} | 660 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
const List<int> primaryKeys = <int>[50, 100, 200, 300, 400, 500, 600, 700, 800, 900];
const List<int> accentKeys = <int>[100, 200, 400, 700];
void main() {
test('MaterialColor basic functionality', () {
const MaterialColor color = MaterialColor(
500,
<int, Color>{
50: Color(0x00000050),
100: Color(0x00000100),
200: Color(0x00000200),
300: Color(0x00000300),
400: Color(0x00000400),
500: Color(0x00000500),
600: Color(0x00000600),
700: Color(0x00000700),
800: Color(0x00000800),
900: Color(0x00000900),
},
);
expect(color.value, 500);
expect(color[50]!.value, 0x00000050);
expect(color[100]!.value, 0x00000100);
expect(color[200]!.value, 0x00000200);
expect(color[300]!.value, 0x00000300);
expect(color[400]!.value, 0x00000400);
expect(color[500]!.value, 0x00000500);
expect(color[600]!.value, 0x00000600);
expect(color[700]!.value, 0x00000700);
expect(color[800]!.value, 0x00000800);
expect(color[900]!.value, 0x00000900);
expect(color.shade50.value, 0x00000050);
expect(color.shade100.value, 0x00000100);
expect(color.shade200.value, 0x00000200);
expect(color.shade300.value, 0x00000300);
expect(color.shade400.value, 0x00000400);
expect(color.shade500.value, 0x00000500);
expect(color.shade600.value, 0x00000600);
expect(color.shade700.value, 0x00000700);
expect(color.shade800.value, 0x00000800);
expect(color.shade900.value, 0x00000900);
});
test('Colors swatches do not contain duplicates', () {
for (final MaterialColor color in Colors.primaries) {
expect(primaryKeys.map<Color>((int key) => color[key]!).toSet().length, primaryKeys.length);
}
expect(primaryKeys.map<Color>((int key) => Colors.grey[key]!).toSet().length, primaryKeys.length);
for (final MaterialAccentColor color in Colors.accents) {
expect(accentKeys.map<Color>((int key) => color[key]!).toSet().length, accentKeys.length);
}
});
test('All color swatch colors are opaque and equal their primary color', () {
for (final MaterialColor color in Colors.primaries) {
expect(color.value, color.shade500.value);
for (final int key in primaryKeys) {
expect(color[key]!.alpha, 0xFF);
}
}
expect(Colors.grey.value, Colors.grey.shade500.value);
for (final int key in primaryKeys) {
expect(Colors.grey[key]!.alpha, 0xFF);
}
for (final MaterialAccentColor color in Colors.accents) {
expect(color.value, color.shade200.value);
for (final int key in accentKeys) {
expect(color[key]!.alpha, 0xFF);
}
}
});
}
| flutter/packages/flutter/test/material/colors_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/colors_test.dart",
"repo_id": "flutter",
"token_count": 1177
} | 661 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('copyWith, ==, hashCode basics', () {
expect(const DrawerThemeData(), const DrawerThemeData().copyWith());
expect(const DrawerThemeData().hashCode, const DrawerThemeData().copyWith().hashCode);
});
test('DrawerThemeData lerp special cases', () {
expect(DrawerThemeData.lerp(null, null, 0), null);
const DrawerThemeData data = DrawerThemeData();
expect(identical(DrawerThemeData.lerp(data, data, 0.5), data), true);
});
testWidgets('Default debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const DrawerThemeData().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('Custom debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const DrawerThemeData(
backgroundColor: Color(0x00000099),
scrimColor: Color(0x00000098),
elevation: 5.0,
shadowColor: Color(0x00000097),
surfaceTintColor: Color(0x00000096),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(2.0))),
width: 200.0,
).debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(description, <String>[
'backgroundColor: Color(0x00000099)',
'scrimColor: Color(0x00000098)',
'elevation: 5.0',
'shadowColor: Color(0x00000097)',
'surfaceTintColor: Color(0x00000096)',
'shape: RoundedRectangleBorder(BorderSide(width: 0.0, style: none), BorderRadius.circular(2.0))',
'width: 200.0',
]);
});
testWidgets('Material2 - Default values are used when no Drawer or DrawerThemeData properties are specified', (WidgetTester tester) async {
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
final ThemeData theme = ThemeData(useMaterial3: false);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
key: scaffoldKey,
drawer: const Drawer(),
),
),
);
scaffoldKey.currentState!.openDrawer();
await tester.pumpAndSettle();
expect(_drawerMaterial(tester).color, null);
expect(_drawerMaterial(tester).elevation, 16.0);
expect(_drawerMaterial(tester).shadowColor, theme.shadowColor);
expect(_drawerMaterial(tester).surfaceTintColor, null);
expect(_drawerMaterial(tester).shape, null);
expect(_scrim(tester).color, Colors.black54);
expect(_drawerRenderBox(tester).size.width, 304.0);
});
testWidgets('Material3 - Default values are used when no Drawer or DrawerThemeData properties are specified', (WidgetTester tester) async {
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
final ThemeData theme = ThemeData(useMaterial3: true);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
key: scaffoldKey,
drawer: const Drawer(),
),
),
);
scaffoldKey.currentState!.openDrawer();
await tester.pumpAndSettle();
expect(_drawerMaterial(tester).color, theme.colorScheme.surfaceContainerLow);
expect(_drawerMaterial(tester).elevation, 1.0);
expect(_drawerMaterial(tester).shadowColor, Colors.transparent);
expect(_drawerMaterial(tester).surfaceTintColor, Colors.transparent);
expect(
_drawerMaterial(tester).shape,
const RoundedRectangleBorder(borderRadius: BorderRadius.horizontal(right: Radius.circular(16.0)))
);
expect(_scrim(tester).color, Colors.black54);
expect(_drawerRenderBox(tester).size.width, 304.0);
});
testWidgets('Material2 - Default values are used when no Drawer or DrawerThemeData properties are specified in end drawer', (WidgetTester tester) async {
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
final ThemeData theme = ThemeData(useMaterial3: false);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
key: scaffoldKey,
endDrawer: const Drawer(),
),
),
);
scaffoldKey.currentState!.openEndDrawer();
await tester.pumpAndSettle();
expect(_drawerMaterial(tester).color, null);
expect(_drawerMaterial(tester).elevation, 16.0);
expect(_drawerMaterial(tester).shadowColor, theme.shadowColor);
expect(_drawerMaterial(tester).surfaceTintColor, null);
expect(_drawerMaterial(tester).shape, null);
expect(_scrim(tester).color, Colors.black54);
expect(_drawerRenderBox(tester).size.width, 304.0);
});
testWidgets('Material3 - Default values are used when no Drawer or DrawerThemeData properties are specified in end drawer', (WidgetTester tester) async {
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
final ThemeData theme = ThemeData(useMaterial3: true);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
key: scaffoldKey,
endDrawer: const Drawer(),
),
),
);
scaffoldKey.currentState!.openEndDrawer();
await tester.pumpAndSettle();
expect(_drawerMaterial(tester).color, theme.colorScheme.surfaceContainerLow);
expect(_drawerMaterial(tester).elevation, 1.0);
expect(_drawerMaterial(tester).shadowColor, Colors.transparent);
expect(_drawerMaterial(tester).surfaceTintColor, Colors.transparent);
expect(
_drawerMaterial(tester).shape,
const RoundedRectangleBorder(borderRadius: BorderRadius.horizontal(left: Radius.circular(16.0)))
);
expect(_scrim(tester).color, Colors.black54);
expect(_drawerRenderBox(tester).size.width, 304.0);
});
testWidgets('DrawerThemeData values are used when no Drawer properties are specified', (WidgetTester tester) async {
const Color backgroundColor = Color(0x00000001);
const Color scrimColor = Color(0x00000002);
const double elevation = 7.0;
const Color shadowColor = Color(0x00000003);
const Color surfaceTintColor = Color(0x00000004);
const RoundedRectangleBorder shape = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0)));
const double width = 200.0;
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
drawerTheme: const DrawerThemeData(
backgroundColor: backgroundColor,
scrimColor: scrimColor,
elevation: elevation,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
shape: shape,
width: width,
),
),
home: Scaffold(
key: scaffoldKey,
drawer: const Drawer(),
),
),
);
scaffoldKey.currentState!.openDrawer();
await tester.pumpAndSettle();
expect(_drawerMaterial(tester).color, backgroundColor);
expect(_drawerMaterial(tester).elevation, elevation);
expect(_drawerMaterial(tester).shadowColor, shadowColor);
expect(_drawerMaterial(tester).surfaceTintColor, surfaceTintColor);
expect(_drawerMaterial(tester).shape, shape);
expect(_scrim(tester).color, scrimColor);
expect(_drawerRenderBox(tester).size.width, width);
});
testWidgets('Drawer values take priority over DrawerThemeData values when both properties are specified', (WidgetTester tester) async {
const Color backgroundColor = Color(0x00000001);
const Color scrimColor = Color(0x00000002);
const double elevation = 7.0;
const Color shadowColor = Color(0x00000003);
const Color surfaceTintColor = Color(0x00000004);
const RoundedRectangleBorder shape = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0)));
const double width = 200.0;
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
drawerTheme: const DrawerThemeData(
backgroundColor: Color(0x00000005),
scrimColor: Color(0x00000006),
elevation: 13.0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(29.0))),
width: 400.0,
),
),
home: Scaffold(
key: scaffoldKey,
drawerScrimColor: scrimColor,
drawer: const Drawer(
backgroundColor: backgroundColor,
elevation: elevation,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
shape: shape,
width: width,
),
),
),
);
scaffoldKey.currentState!.openDrawer();
await tester.pumpAndSettle();
expect(_drawerMaterial(tester).color, backgroundColor);
expect(_drawerMaterial(tester).elevation, elevation);
expect(_drawerMaterial(tester).shadowColor, shadowColor);
expect(_drawerMaterial(tester).surfaceTintColor, surfaceTintColor);
expect(_drawerMaterial(tester).shape, shape);
expect(_scrim(tester).color, scrimColor);
expect(_drawerRenderBox(tester).size.width, width);
});
testWidgets('DrawerTheme values take priority over ThemeData.drawerTheme values when both properties are specified', (WidgetTester tester) async {
const Color backgroundColor = Color(0x00000001);
const Color scrimColor = Color(0x00000002);
const double elevation = 7.0;
const Color shadowColor = Color(0x00000003);
const Color surfaceTintColor = Color(0x00000004);
const RoundedRectangleBorder shape = RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(16.0)));
const double width = 200.0;
final GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
drawerTheme: const DrawerThemeData(
backgroundColor: Color(0x00000005),
scrimColor: Color(0x00000006),
elevation: 13.0,
shadowColor: Color(0x00000007),
surfaceTintColor: Color(0x00000007),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(29.0))),
width: 400.0
),
),
home: DrawerTheme(
data: const DrawerThemeData(
backgroundColor: backgroundColor,
scrimColor: scrimColor,
elevation: elevation,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
shape: shape,
width: width,
),
child: Scaffold(
key: scaffoldKey,
drawer: const Drawer(),
),
),
),
);
scaffoldKey.currentState!.openDrawer();
await tester.pumpAndSettle();
expect(_drawerMaterial(tester).color, backgroundColor);
expect(_drawerMaterial(tester).elevation, elevation);
expect(_drawerMaterial(tester).shadowColor, shadowColor);
expect(_drawerMaterial(tester).surfaceTintColor, surfaceTintColor);
expect(_drawerMaterial(tester).shape, shape);
expect(_scrim(tester).color, scrimColor);
expect(_drawerRenderBox(tester).size.width, width);
});
}
Material _drawerMaterial(WidgetTester tester) {
return tester.firstWidget<Material>(
find.descendant(
of: find.byType(Drawer),
matching: find.byType(Material),
),
);
}
// The scrim is a Container within a Semantics node labeled "Dismiss",
// within a DrawerController.
Container _scrim(WidgetTester tester) {
return tester.widget<Container>(
find.descendant(
of: find.descendant(
of: find.byType(DrawerController),
matching: find.byWidgetPredicate((Widget widget) {
return widget is Semantics
&& widget.properties.label == 'Dismiss';
}),
),
matching: find.byType(Container),
),
);
}
// The RenderBox representing the Drawer.
RenderBox _drawerRenderBox(WidgetTester tester) {
return tester.renderObject(find.byType(Drawer));
}
| flutter/packages/flutter/test/material/drawer_theme_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/drawer_theme_test.dart",
"repo_id": "flutter",
"token_count": 4881
} | 662 |
// 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/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'feedback_tester.dart';
/// Adds the basic requirements for a Chip.
Widget wrapForChip({
required Widget child,
TextDirection textDirection = TextDirection.ltr,
TextScaler textScaler = TextScaler.noScaling,
ThemeData? theme,
}) {
return MaterialApp(
theme: theme,
home: Directionality(
textDirection: textDirection,
child: MediaQuery(
data: MediaQueryData(textScaler: textScaler),
child: Material(child: child),
),
),
);
}
Future<void> pumpCheckmarkChip(
WidgetTester tester, {
required Widget chip,
Color? themeColor,
ThemeData? theme,
}) async {
await tester.pumpWidget(
wrapForChip(
theme: theme,
child: Builder(
builder: (BuildContext context) {
final ChipThemeData chipTheme = ChipTheme.of(context);
return ChipTheme(
data: themeColor == null ? chipTheme : chipTheme.copyWith(
checkmarkColor: themeColor,
),
child: chip,
);
},
),
),
);
}
Widget selectedFilterChip({ Color? checkmarkColor }) {
return FilterChip(
label: const Text('InputChip'),
selected: true,
showCheckmark: true,
checkmarkColor: checkmarkColor,
onSelected: (bool _) { },
);
}
void expectCheckmarkColor(Finder finder, Color color) {
expect(
finder,
paints
// Physical model path
..path()
// The first layer that is painted is the selection overlay. We do not care
// how it is painted but it has to be added it to this pattern so that the
// check mark can be checked next.
..rrect()
// The second layer that is painted is the check mark.
..path(color: color),
);
}
RenderBox getMaterialBox(WidgetTester tester, Finder type) {
return tester.firstRenderObject<RenderBox>(
find.descendant(
of: type,
matching: find.byType(CustomPaint),
),
);
}
void checkChipMaterialClipBehavior(WidgetTester tester, Clip clipBehavior) {
final Iterable<Material> materials = tester.widgetList<Material>(find.byType(Material));
// There should be two Material widgets, first Material is from the "_wrapForChip" and
// last Material is from the "RawChip".
expect(materials.length, 2);
// The last Material from `RawChip` should have the clip behavior.
expect(materials.last.clipBehavior, clipBehavior);
}
Material getMaterial(WidgetTester tester) {
return tester.widget<Material>(
find.descendant(
of: find.byType(FilterChip),
matching: find.byType(Material),
),
);
}
IconThemeData getIconData(WidgetTester tester) {
final IconTheme iconTheme = tester.firstWidget(
find.descendant(
of: find.byType(RawChip),
matching: find.byType(IconTheme),
),
);
return iconTheme.data;
}
DefaultTextStyle getLabelStyle(WidgetTester tester, String labelText) {
return tester.widget(
find.ancestor(
of: find.text(labelText),
matching: find.byType(DefaultTextStyle),
).first,
);
}
// Finds any container of a tooltip.
Finder findTooltipContainer(String tooltipText) {
return find.ancestor(
of: find.text(tooltipText),
matching: find.byType(Container),
);
}
void main() {
testWidgets('Material2 - FilterChip defaults', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: false);
const String label = 'filter chip';
// Test enabled FilterChip defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: FilterChip(
onSelected: (bool valueChanged) { },
label: const Text(label),
),
),
),
),
);
// Test default chip size.
expect(tester.getSize(find.byType(FilterChip)), const Size(178.0, 48.0));
// Test default label style.
expect(
getLabelStyle(tester, label).style.color,
theme.textTheme.bodyLarge!.color!.withAlpha(0xde),
);
Material chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, Colors.black);
expect(chipMaterial.shape, const StadiumBorder());
ShapeDecoration decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, Colors.black.withAlpha(0x1f));
// Test disabled FilterChip defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Material(
child: FilterChip(
onSelected: null,
label: Text(label),
),
),
),
);
await tester.pumpAndSettle();
chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, Colors.black);
expect(chipMaterial.shape, const StadiumBorder());
decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, Colors.black38);
// Test selected enabled FilterChip defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: FilterChip(
selected: true,
onSelected: (bool valueChanged) { },
label: const Text(label),
),
),
),
);
await tester.pumpAndSettle();
chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, Colors.black);
expect(chipMaterial.shape, const StadiumBorder());
decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, Colors.black.withAlpha(0x3d));
// Test selected disabled FilterChip defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Material(
child: FilterChip(
selected: true,
onSelected: null,
label: Text(label),
),
),
),
);
await tester.pumpAndSettle();
chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, Colors.black);
expect(chipMaterial.shape, const StadiumBorder());
decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, Colors.black.withAlpha(0x3d));
});
testWidgets('Material3 - FilterChip defaults', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
const String label = 'filter chip';
// Test enabled FilterChip defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: FilterChip(
onSelected: (bool valueChanged) { },
label: const Text(label),
),
),
),
),
);
// Test default chip size.
expect(
tester.getSize(find.byType(FilterChip)),
within(distance: 0.001, from: const Size(189.1, 48.0)),
);
// Test default label style.
expect(
getLabelStyle(tester, label).style.color!.value,
theme.colorScheme.onSurfaceVariant.value,
);
Material chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, Colors.transparent);
expect(chipMaterial.surfaceTintColor, Colors.transparent);
expect(
chipMaterial.shape,
RoundedRectangleBorder(
borderRadius: const BorderRadius.all(Radius.circular(8.0)),
side: BorderSide(color: theme.colorScheme.outline),
),
);
ShapeDecoration decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, null);
// Test disabled FilterChip defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Material(
child: FilterChip(
onSelected: null,
label: Text(label),
),
),
),
);
await tester.pumpAndSettle();
chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, Colors.transparent);
expect(chipMaterial.surfaceTintColor, Colors.transparent);
expect(
chipMaterial.shape,
RoundedRectangleBorder(
borderRadius: const BorderRadius.all(Radius.circular(8.0)),
side: BorderSide(color: theme.colorScheme.onSurface.withOpacity(0.12)),
),
);
decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, null);
// Test selected enabled FilterChip defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: FilterChip(
selected: true,
onSelected: (bool valueChanged) { },
label: const Text(label),
),
),
),
);
await tester.pumpAndSettle();
chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, null);
expect(chipMaterial.surfaceTintColor, Colors.transparent);
expect(
chipMaterial.shape,
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
side: BorderSide(color: Colors.transparent),
),
);
decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, theme.colorScheme.secondaryContainer);
// Test selected disabled FilterChip defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Material(
child: FilterChip(
selected: true,
onSelected: null,
label: Text(label),
),
),
),
);
await tester.pumpAndSettle();
chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, null);
expect(chipMaterial.surfaceTintColor, Colors.transparent);
expect(
chipMaterial.shape,
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
side: BorderSide(color: Colors.transparent),
),
);
decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, theme.colorScheme.onSurface.withOpacity(0.12));
});
testWidgets('Material3 - FilterChip.elevated defaults', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
const String label = 'filter chip';
// Test enabled FilterChip.elevated defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: FilterChip.elevated(
onSelected: (bool valueChanged) { },
label: const Text(label),
),
),
),
),
);
// Test default chip size.
expect(
tester.getSize(find.byType(FilterChip)),
within(distance: 0.001, from: const Size(189.1, 48.0)),
);
// Test default label style.
expect(
getLabelStyle(tester, 'filter chip').style.color!.value,
theme.colorScheme.onSurfaceVariant.value,
);
Material chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 1);
expect(chipMaterial.shadowColor, theme.colorScheme.shadow);
expect(chipMaterial.surfaceTintColor, Colors.transparent);
expect(
chipMaterial.shape,
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
side: BorderSide(color: Colors.transparent),
),
);
ShapeDecoration decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, theme.colorScheme.surfaceContainerLow);
// Test disabled FilterChip.elevated defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Material(
child: FilterChip.elevated(
onSelected: null,
label: Text(label),
),
),
),
);
await tester.pumpAndSettle();
chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, theme.colorScheme.shadow);
expect(chipMaterial.surfaceTintColor, Colors.transparent);
expect(
chipMaterial.shape,
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
side: BorderSide(color: Colors.transparent),
),
);
decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, theme.colorScheme.onSurface.withOpacity(0.12));
// Test selected enabled FilterChip.elevated defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: FilterChip.elevated(
selected: true,
onSelected: (bool valueChanged) { },
label: const Text(label),
),
),
),
);
await tester.pumpAndSettle();
chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 1);
expect(chipMaterial.shadowColor, null);
expect(chipMaterial.surfaceTintColor, Colors.transparent);
expect(
chipMaterial.shape,
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
side: BorderSide(color: Colors.transparent),
),
);
decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, theme.colorScheme.secondaryContainer);
// Test selected disabled FilterChip.elevated defaults.
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: const Material(
child: FilterChip.elevated(
selected: true,
onSelected: null,
label: Text(label),
),
),
),
);
await tester.pumpAndSettle();
chipMaterial = getMaterial(tester);
expect(chipMaterial.elevation, 0);
expect(chipMaterial.shadowColor, null);
expect(chipMaterial.surfaceTintColor, Colors.transparent);
expect(
chipMaterial.shape,
const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(8.0)),
side: BorderSide(color: Colors.transparent),
),
);
decoration = tester.widget<Ink>(find.byType(Ink)).decoration! as ShapeDecoration;
expect(decoration.color, theme.colorScheme.onSurface.withOpacity(0.12));
});
testWidgets('FilterChip.color resolves material states', (WidgetTester tester) async {
const Color disabledSelectedColor = Color(0xffffff00);
const Color disabledColor = Color(0xff00ff00);
const Color backgroundColor = Color(0xff0000ff);
const Color selectedColor = Color(0xffff0000);
final MaterialStateProperty<Color?> color = MaterialStateProperty.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.disabled) && states.contains(MaterialState.selected)) {
return disabledSelectedColor;
}
if (states.contains(MaterialState.disabled)) {
return disabledColor;
}
if (states.contains(MaterialState.selected)) {
return selectedColor;
}
return backgroundColor;
});
Widget buildApp({ required bool enabled, required bool selected }) {
return wrapForChip(
child: Column(
children: <Widget>[
FilterChip(
onSelected: enabled ? (bool value) { } : null,
selected: selected,
color: color,
label: const Text('FilterChip'),
),
FilterChip.elevated(
onSelected: enabled ? (bool value) { } : null,
selected: selected,
color: color,
label: const Text('FilterChip.elevated'),
),
],
),
);
}
// Test enabled state.
await tester.pumpWidget(buildApp(enabled: true, selected: false));
// Enabled FilterChip should have the provided backgroundColor.
expect(
getMaterialBox(tester, find.byType(RawChip).first),
paints..rrect(color: backgroundColor),
);
// Enabled elevated FilterChip should have the provided backgroundColor.
expect(
getMaterialBox(tester, find.byType(RawChip).last),
paints..rrect(color: backgroundColor),
);
// Test disabled state.
await tester.pumpWidget(buildApp(enabled: false, selected: false));
await tester.pumpAndSettle();
// Disabled FilterChip should have the provided disabledColor.
expect(
getMaterialBox(tester, find.byType(RawChip).first),
paints..rrect(color: disabledColor),
);
// Disabled elevated FilterChip should have the provided disabledColor.
expect(
getMaterialBox(tester, find.byType(RawChip).last),
paints..rrect(color: disabledColor),
);
// Test enabled & selected state.
await tester.pumpWidget(buildApp(enabled: true, selected: true));
await tester.pumpAndSettle();
// Enabled & selected FilterChip should have the provided selectedColor.
expect(
getMaterialBox(tester, find.byType(RawChip).first),
paints..rrect(color: selectedColor),
);
// Enabled & selected elevated FilterChip should have the provided selectedColor.
expect(
getMaterialBox(tester, find.byType(RawChip).last),
paints..rrect(color: selectedColor),
);
// Test disabled & selected state.
await tester.pumpWidget(buildApp(enabled: false, selected: true));
await tester.pumpAndSettle();
// Disabled & selected FilterChip should have the provided disabledSelectedColor.
expect(
getMaterialBox(tester, find.byType(RawChip).first),
paints..rrect(color: disabledSelectedColor),
);
// Disabled & selected elevated FilterChip should have the
// provided disabledSelectedColor.
expect(
getMaterialBox(tester, find.byType(RawChip).last),
paints..rrect(color: disabledSelectedColor),
);
});
testWidgets('FilterChip uses provided state color properties', (WidgetTester tester) async {
const Color disabledColor = Color(0xff00ff00);
const Color backgroundColor = Color(0xff0000ff);
const Color selectedColor = Color(0xffff0000);
Widget buildApp({ required bool enabled, required bool selected }) {
return wrapForChip(
child: Column(
children: <Widget>[
FilterChip(
onSelected: enabled ? (bool value) { } : null,
selected: selected,
disabledColor: disabledColor,
backgroundColor: backgroundColor,
selectedColor: selectedColor,
label: const Text('FilterChip'),
),
FilterChip.elevated(
onSelected: enabled ? (bool value) { } : null,
selected: selected,
disabledColor: disabledColor,
backgroundColor: backgroundColor,
selectedColor: selectedColor,
label: const Text('FilterChip.elevated'),
),
],
),
);
}
// Test enabled state.
await tester.pumpWidget(buildApp(enabled: true, selected: false));
// Enabled FilterChip should have the provided backgroundColor.
expect(
getMaterialBox(tester, find.byType(RawChip).first),
paints..rrect(color: backgroundColor),
);
// Enabled elevated FilterChip should have the provided backgroundColor.
expect(
getMaterialBox(tester, find.byType(RawChip).last),
paints..rrect(color: backgroundColor),
);
// Test disabled state.
await tester.pumpWidget(buildApp(enabled: false, selected: false));
await tester.pumpAndSettle();
// Disabled FilterChip should have the provided disabledColor.
expect(
getMaterialBox(tester, find.byType(RawChip).first),
paints..rrect(color: disabledColor),
);
// Disabled elevated FilterChip should have the provided disabledColor.
expect(
getMaterialBox(tester, find.byType(RawChip).last),
paints..rrect(color: disabledColor),
);
// Test enabled & selected state.
await tester.pumpWidget(buildApp(enabled: true, selected: true));
await tester.pumpAndSettle();
// Enabled & selected FilterChip should have the provided selectedColor.
expect(
getMaterialBox(tester, find.byType(RawChip).first),
paints..rrect(color: selectedColor),
);
// Enabled & selected elevated FilterChip should have the provided selectedColor.
expect(
getMaterialBox(tester, find.byType(RawChip).last),
paints..rrect(color: selectedColor),
);
});
testWidgets('FilterChip can be tapped', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: FilterChip(
onSelected: (bool valueChanged) { },
label: const Text('filter chip'),
),
),
),
);
await tester.tap(find.byType(FilterChip));
expect(tester.takeException(), null);
});
testWidgets('Material2 - Filter chip check mark color is determined by platform brightness when light', (WidgetTester tester) async {
await pumpCheckmarkChip(
tester,
chip: selectedFilterChip(),
theme: ThemeData(useMaterial3: false),
);
expectCheckmarkColor(find.byType(FilterChip), Colors.black.withAlpha(0xde));
});
testWidgets('Material3 - Filter chip check mark color is determined by platform brightness when light', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
await pumpCheckmarkChip(
tester,
chip: selectedFilterChip(),
theme: theme,
);
expectCheckmarkColor(
find.byType(FilterChip),
theme.colorScheme.onSecondaryContainer,
);
});
testWidgets('Material2 - Filter chip check mark color is determined by platform brightness when dark', (WidgetTester tester) async {
await pumpCheckmarkChip(
tester,
chip: selectedFilterChip(),
theme: ThemeData.dark(useMaterial3: false),
);
expectCheckmarkColor(
find.byType(FilterChip),
Colors.white.withAlpha(0xde),
);
});
testWidgets('Material3 - Filter chip check mark color is determined by platform brightness when dark', (WidgetTester tester) async {
final ThemeData theme = ThemeData(brightness: Brightness.dark);
await pumpCheckmarkChip(
tester,
chip: selectedFilterChip(),
theme: theme,
);
expectCheckmarkColor(
find.byType(FilterChip),
theme.colorScheme.onSecondaryContainer,
);
});
testWidgets('Filter chip check mark color can be set by the chip theme', (WidgetTester tester) async {
await pumpCheckmarkChip(
tester,
chip: selectedFilterChip(),
themeColor: const Color(0xff00ff00),
);
expectCheckmarkColor(find.byType(FilterChip), const Color(0xff00ff00));
});
testWidgets('Filter chip check mark color can be set by the chip constructor', (WidgetTester tester) async {
await pumpCheckmarkChip(
tester,
chip: selectedFilterChip(checkmarkColor: const Color(0xff00ff00)),
);
expectCheckmarkColor(find.byType(FilterChip), const Color(0xff00ff00));
});
testWidgets('Filter chip check mark color is set by chip constructor even when a theme color is specified', (WidgetTester tester) async {
await pumpCheckmarkChip(
tester,
chip: selectedFilterChip(checkmarkColor: const Color(0xffff0000)),
themeColor: const Color(0xff00ff00),
);
expectCheckmarkColor(find.byType(FilterChip), const Color(0xffff0000));
});
testWidgets('FilterChip clipBehavior properly passes through to the Material', (WidgetTester tester) async {
const Text label = Text('label');
await tester.pumpWidget(wrapForChip(child: FilterChip(label: label, onSelected: (bool b) { })));
checkChipMaterialClipBehavior(tester, Clip.none);
await tester.pumpWidget(wrapForChip(child: FilterChip(label: label, onSelected: (bool b) { }, clipBehavior: Clip.antiAlias)));
checkChipMaterialClipBehavior(tester, Clip.antiAlias);
});
testWidgets('Material3 - width should not change with selection', (WidgetTester tester) async {
// Regression tests for: https://github.com/flutter/flutter/issues/110645
// For the text "FilterChip" the chip should default to 175 regardless of selection.
const int expectedWidth = 175;
// Unselected
await tester.pumpWidget(MaterialApp(
home: Material(
child: Center(
child: FilterChip(
label: const Text('FilterChip'),
showCheckmark: false,
onSelected: (bool _) {},
)
),
),
));
expect(tester.getSize(find.byType(FilterChip)).width, expectedWidth);
// Selected
await tester.pumpWidget(MaterialApp(
home: Material(
child: Center(
child: FilterChip(
label: const Text('FilterChip'),
showCheckmark: false,
selected: true,
onSelected: (bool _) {},
)
),
),
));
await tester.pumpAndSettle();
expect(tester.getSize(find.byType(FilterChip)).width, expectedWidth);
});
testWidgets('FilterChip uses provided iconTheme', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
Widget buildChip({ IconThemeData? iconTheme }) {
return MaterialApp(
theme: theme,
home: Material(
child: FilterChip(
iconTheme: iconTheme,
avatar: const Icon(Icons.add),
label: const Text('FilterChip'),
onSelected: (bool _) {},
),
),
);
}
// Test default icon theme.
await tester.pumpWidget(buildChip());
expect(getIconData(tester).color, theme.colorScheme.primary);
// Test provided icon theme.
await tester.pumpWidget(buildChip(iconTheme: const IconThemeData(color: Color(0xff00ff00))));
expect(getIconData(tester).color, const Color(0xff00ff00));
});
testWidgets('Material3 - FilterChip supports delete button', (WidgetTester tester) async {
final ThemeData theme = ThemeData();
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: FilterChip(
onDeleted: () { },
onSelected: (bool valueChanged) { },
label: const Text('FilterChip'),
),
),
),
),
);
// Test the chip size with delete button.
expect(find.text('FilterChip'), findsOneWidget);
expect(tester.getSize(find.byType(FilterChip)), const Size(195.0, 48.0));
// Test the delete button icon.
expect(tester.getSize(find.byIcon(Icons.clear)), const Size(18.0, 18.0));
expect(getIconData(tester).color, theme.colorScheme.onSurfaceVariant);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: FilterChip.elevated(
onDeleted: () { },
onSelected: (bool valueChanged) { },
label: const Text('Elevated FilterChip'),
),
),
),
),
);
// Test the elevated chip size with delete button.
expect(find.text('Elevated FilterChip'), findsOneWidget);
expect(
tester.getSize(find.byType(FilterChip)),
within(distance: 0.001, from: const Size(321.9, 48.0)),
);
// Test the delete button icon.
expect(tester.getSize(find.byIcon(Icons.clear)), const Size(18.0, 18.0));
expect(getIconData(tester).color, theme.colorScheme.onSurfaceVariant);
}, skip: kIsWeb && !isCanvasKit); // https://github.com/flutter/flutter/issues/99933
testWidgets('Material2 - FilterChip supports delete button', (WidgetTester tester) async {
final ThemeData theme = ThemeData(useMaterial3: false);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: FilterChip(
onDeleted: () { },
onSelected: (bool valueChanged) { },
label: const Text('FilterChip'),
),
),
),
),
);
// Test the chip size with delete button.
expect(find.text('FilterChip'), findsOneWidget);
expect(tester.getSize(find.byType(FilterChip)), const Size(188.0, 48.0));
// Test the delete button icon.
expect(tester.getSize(find.byIcon(Icons.cancel)), const Size(18.0, 18.0));
expect(getIconData(tester).color, theme.iconTheme.color?.withAlpha(0xde));
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Material(
child: Center(
child: FilterChip.elevated(
onDeleted: () { },
onSelected: (bool valueChanged) { },
label: const Text('Elevated FilterChip'),
),
),
),
),
);
// Test the elevated chip size with delete button.
expect(find.text('Elevated FilterChip'), findsOneWidget);
expect(tester.getSize(find.byType(FilterChip)), const Size(314.0, 48.0));
// Test the delete button icon.
expect(tester.getSize(find.byIcon(Icons.cancel)), const Size(18.0, 18.0));
expect(getIconData(tester).color, theme.iconTheme.color?.withAlpha(0xde));
});
testWidgets('Customize FilterChip delete button', (WidgetTester tester) async {
Widget buildChip({
Widget? deleteIcon,
Color? deleteIconColor,
String? deleteButtonTooltipMessage,
}) {
return MaterialApp(
home: Material(
child: Center(
child: FilterChip(
deleteIcon: deleteIcon,
deleteIconColor: deleteIconColor,
deleteButtonTooltipMessage: deleteButtonTooltipMessage,
onDeleted: () { },
onSelected: (bool valueChanged) { },
label: const Text('FilterChip'),
),
),
),
);
}
// Test the custom delete icon.
await tester.pumpWidget(buildChip(deleteIcon: const Icon(Icons.delete)));
expect(find.byIcon(Icons.clear), findsNothing);
expect(find.byIcon(Icons.delete), findsOneWidget);
// Test the custom delete icon color.
await tester.pumpWidget(buildChip(
deleteIcon: const Icon(Icons.delete),
deleteIconColor: const Color(0xff00ff00)),
);
await tester.pumpAndSettle();
expect(find.byIcon(Icons.clear), findsNothing);
expect(find.byIcon(Icons.delete), findsOneWidget);
expect(getIconData(tester).color, const Color(0xff00ff00));
// Test the custom delete button tooltip message.
await tester.pumpWidget(buildChip(deleteButtonTooltipMessage: 'Delete FilterChip'));
await tester.pumpAndSettle();
// Hover over the delete icon of the chip
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byIcon(Icons.clear)));
await tester.pumpAndSettle();
// Verify the tooltip message is set.
expect(find.widgetWithText(Tooltip, 'Delete FilterChip'), findsOneWidget);
await gesture.up();
});
testWidgets('FilterChip delete button control test', (WidgetTester tester) async {
final FeedbackTester feedback = FeedbackTester();
final List<String> deletedButtonStrings = <String>[];
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Center(
child: FilterChip(
onDeleted: () {
deletedButtonStrings.add('A');
},
onSelected: (bool valueChanged) { },
label: const Text('FilterChip'),
),
),
),
),
);
expect(feedback.clickSoundCount, 0);
expect(deletedButtonStrings, isEmpty);
await tester.tap(find.byIcon(Icons.clear));
expect(deletedButtonStrings, equals(<String>['A']));
await tester.pumpAndSettle(const Duration(seconds: 1));
expect(feedback.clickSoundCount, 1);
await tester.tap(find.byIcon(Icons.clear));
expect(deletedButtonStrings, equals(<String>['A', 'A']));
await tester.pumpAndSettle(const Duration(seconds: 1));
expect(feedback.clickSoundCount, 2);
feedback.dispose();
});
testWidgets('Delete button is visible on disabled FilterChip', (WidgetTester tester) async {
await tester.pumpWidget(
wrapForChip(
child: FilterChip(
label: const Text('Label'),
onSelected: null,
onDeleted: () { },
)
),
);
// Delete button should be visible.
await expectLater(find.byType(RawChip), matchesGoldenFile('filter_chip.disabled.delete_button.png'));
});
testWidgets('Delete button tooltip is not shown on disabled FilterChip', (WidgetTester tester) async {
Widget buildChip({ bool enabled = true }) {
return wrapForChip(
child: FilterChip(
onSelected: enabled ? (bool value) { } : null,
label: const Text('Label'),
onDeleted: () { },
)
);
}
// Test enabled chip.
await tester.pumpWidget(buildChip());
final Offset deleteButtonLocation = tester.getCenter(find.byType(Icon));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.moveTo(deleteButtonLocation);
await tester.pump();
// Delete button tooltip should be visible.
expect(findTooltipContainer('Delete'), findsOneWidget);
// Test disabled chip.
await tester.pumpWidget(buildChip(enabled: false));
await tester.pump();
// Delete button tooltip should not be visible.
expect(findTooltipContainer('Delete'), findsNothing);
});
testWidgets('Material3 - Default FilterChip icon colors', (WidgetTester tester) async {
const IconData flatAvatar = Icons.favorite;
const IconData flatDeleteIcon = Icons.delete;
const IconData elevatedAvatar = Icons.house;
const IconData elevatedDeleteIcon = Icons.clear_all;
final ThemeData theme = ThemeData();
Widget buildChips({ required bool selected }) {
return MaterialApp(
theme: theme,
home: Material(
child: Column(
children: <Widget>[
FilterChip(
avatar: const Icon(flatAvatar),
deleteIcon: const Icon(flatDeleteIcon),
onSelected: (bool valueChanged) { },
label: const Text('FilterChip'),
selected: selected,
onDeleted: () { },
),
FilterChip.elevated(
avatar: const Icon(elevatedAvatar),
deleteIcon: const Icon(elevatedDeleteIcon),
onSelected: (bool valueChanged) { },
label: const Text('Elevated FilterChip'),
selected: selected,
onDeleted: () { },
),
],
),
),
);
}
Color getIconColor(WidgetTester tester, IconData icon) {
return tester.firstWidget<IconTheme>(find.ancestor(
of: find.byIcon(icon),
matching: find.byType(IconTheme),
)).data.color!;
}
// Test unselected state.
await tester.pumpWidget(buildChips(selected: false));
// Check the flat chip icon colors.
expect(getIconColor(tester, flatAvatar), theme.colorScheme.primary);
expect(
getIconColor(tester, flatDeleteIcon),
theme.colorScheme.onSurfaceVariant,
);
// Check the elevated chip icon colors.
expect(getIconColor(tester, elevatedAvatar), theme.colorScheme.primary);
expect(
getIconColor(tester, elevatedDeleteIcon),
theme.colorScheme.onSurfaceVariant,
);
// Test selected state.
await tester.pumpWidget(buildChips(selected: true));
// Check the flat chip icon colors.
expect(
getIconColor(tester, flatAvatar),
theme.colorScheme.onSecondaryContainer,
);
expect(
getIconColor(tester, flatDeleteIcon),
theme.colorScheme.onSecondaryContainer,
);
// Check the elevated chip icon colors.
expect(
getIconColor(tester, elevatedAvatar),
theme.colorScheme.onSecondaryContainer,
);
expect(
getIconColor(tester, elevatedDeleteIcon),
theme.colorScheme.onSecondaryContainer,
);
});
testWidgets('FilterChip avatar layout constraints can be customized', (WidgetTester tester) async {
const double border = 1.0;
const double iconSize = 18.0;
const double labelPadding = 8.0;
const double padding = 8.0;
const Size labelSize = Size(100, 100);
Widget buildChip({BoxConstraints? avatarBoxConstraints}) {
return wrapForChip(
child: Center(
child: FilterChip(
avatarBoxConstraints: avatarBoxConstraints,
avatar: const Icon(Icons.favorite),
label: Container(
width: labelSize.width,
height: labelSize.width,
color: const Color(0xFFFF0000),
),
onSelected: (bool value) { },
),
),
);
}
// Test default avatar layout constraints.
await tester.pumpWidget(buildChip());
expect(tester.getSize(find.byType(FilterChip)).width, equals(234.0));
expect(tester.getSize(find.byType(FilterChip)).height, equals(118.0));
// Calculate the distance between avatar and chip edges.
Offset chipTopLeft = tester.getTopLeft(find.byWidget(getMaterial(tester)));
final Offset avatarCenter = tester.getCenter(find.byIcon(Icons.favorite));
expect(chipTopLeft.dx, avatarCenter.dx - (labelSize.width / 2) - padding - border);
expect(chipTopLeft.dy, avatarCenter.dy - (labelSize.width / 2) - padding - border);
// Calculate the distnance between avatar and label.
Offset labelTopLeft = tester.getTopLeft(find.byType(Container));
expect(labelTopLeft.dx, avatarCenter.dx + (labelSize.width / 2) + labelPadding);
// Test custom avatar layout constraints.
await tester.pumpWidget(buildChip(avatarBoxConstraints: const BoxConstraints.tightForFinite()));
await tester.pump();
expect(tester.getSize(find.byType(FilterChip)).width, equals(152.0));
expect(tester.getSize(find.byType(FilterChip)).height, equals(118.0));
// Calculate the distance between avatar and chip edges.
chipTopLeft = tester.getTopLeft(find.byWidget(getMaterial(tester)));
expect(chipTopLeft.dx, avatarCenter.dx - (iconSize / 2) - padding - border);
expect(chipTopLeft.dy, avatarCenter.dy - (labelSize.width / 2) - padding - border);
// Calculate the distnance between avatar and label.
labelTopLeft = tester.getTopLeft(find.byType(Container));
expect(labelTopLeft.dx, avatarCenter.dx + (iconSize / 2) + labelPadding);
});
testWidgets('FilterChip delete icon layout constraints can be customized', (WidgetTester tester) async {
const double border = 1.0;
const double iconSize = 18.0;
const double labelPadding = 8.0;
const double padding = 8.0;
const Size labelSize = Size(100, 100);
Widget buildChip({BoxConstraints? deleteIconBoxConstraints}) {
return wrapForChip(
child: Center(
child: FilterChip(
deleteIconBoxConstraints: deleteIconBoxConstraints,
onDeleted: () { },
label: Container(
width: labelSize.width,
height: labelSize.width,
color: const Color(0xFFFF0000),
),
onSelected: (bool value) { },
),
),
);
}
// Test default delete icon layout constraints.
await tester.pumpWidget(buildChip());
expect(tester.getSize(find.byType(FilterChip)).width, equals(234.0));
expect(tester.getSize(find.byType(FilterChip)).height, equals(118.0));
// Calculate the distance between delete icon and chip edges.
Offset chipTopRight = tester.getTopRight(find.byWidget(getMaterial(tester)));
final Offset deleteIconCenter = tester.getCenter(find.byIcon(Icons.clear));
expect(chipTopRight.dx, deleteIconCenter.dx + (labelSize.width / 2) + padding + border);
expect(chipTopRight.dy, deleteIconCenter.dy - (labelSize.width / 2) - padding - border);
// Calculate the distance between delete icon and label.
Offset labelTopRight = tester.getTopRight(find.byType(Container));
expect(labelTopRight.dx, deleteIconCenter.dx - (labelSize.width / 2) - labelPadding);
// Test custom avatar layout constraints.
await tester.pumpWidget(buildChip(
deleteIconBoxConstraints: const BoxConstraints.tightForFinite(),
));
await tester.pump();
expect(tester.getSize(find.byType(FilterChip)).width, equals(152.0));
expect(tester.getSize(find.byType(FilterChip )).height, equals(118.0));
// Calculate the distance between delete icon and chip edges.
chipTopRight = tester.getTopRight(find.byWidget(getMaterial(tester)));
expect(chipTopRight.dx, deleteIconCenter.dx + (iconSize / 2) + padding + border);
expect(chipTopRight.dy, deleteIconCenter.dy - (labelSize.width / 2) - padding - border);
// Calculate the distance between delete icon and label.
labelTopRight = tester.getTopRight(find.byType(Container));
expect(labelTopRight.dx, deleteIconCenter.dx - (iconSize / 2) - labelPadding);
});
}
| flutter/packages/flutter/test/material/filter_chip_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/filter_chip_test.dart",
"repo_id": "flutter",
"token_count": 16513
} | 663 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/src/services/keyboard_key.g.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/semantics_tester.dart';
import 'feedback_tester.dart';
void main() {
testWidgets('InkWell gestures control test', (WidgetTester tester) async {
final List<String> log = <String>[];
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: InkWell(
onTap: () {
log.add('tap');
},
onDoubleTap: () {
log.add('double-tap');
},
onLongPress: () {
log.add('long-press');
},
onTapDown: (TapDownDetails details) {
log.add('tap-down');
},
onTapUp: (TapUpDetails details) {
log.add('tap-up');
},
onTapCancel: () {
log.add('tap-cancel');
},
),
),
),
));
await tester.tap(find.byType(InkWell), pointer: 1);
expect(log, isEmpty);
await tester.pump(const Duration(seconds: 1));
expect(log, equals(<String>['tap-down', 'tap-up', 'tap']));
log.clear();
await tester.tap(find.byType(InkWell), pointer: 2);
await tester.pump(const Duration(milliseconds: 100));
await tester.tap(find.byType(InkWell), pointer: 3);
expect(log, equals(<String>['double-tap']));
log.clear();
await tester.longPress(find.byType(InkWell), pointer: 4);
expect(log, equals(<String>['tap-down', 'tap-cancel', 'long-press']));
log.clear();
TestGesture gesture = await tester.startGesture(tester.getRect(find.byType(InkWell)).center);
await tester.pump(const Duration(milliseconds: 100));
expect(log, equals(<String>['tap-down']));
await gesture.up();
await tester.pump(const Duration(seconds: 1));
expect(log, equals(<String>['tap-down', 'tap-up', 'tap']));
log.clear();
gesture = await tester.startGesture(tester.getRect(find.byType(InkWell)).center);
await tester.pump(const Duration(milliseconds: 100));
await gesture.moveBy(const Offset(0.0, 200.0));
await gesture.cancel();
expect(log, equals(<String>['tap-down', 'tap-cancel']));
});
testWidgets('InkWell only onTapDown enables gestures', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/96030
bool downTapped = false;
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: InkWell(
onTapDown: (TapDownDetails details) {
downTapped = true;
},
),
),
),
));
await tester.tap(find.byType(InkWell));
expect(downTapped, true);
});
testWidgets('InkWell invokes activation actions when expected', (WidgetTester tester) async {
final List<String> log = <String>[];
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Shortcuts(
shortcuts: const <ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.space): ActivateIntent(),
SingleActivator(LogicalKeyboardKey.enter): ButtonActivateIntent(),
},
child: Material(
child: Center(
child: InkWell(
autofocus: true,
onTap: () {
log.add('tap');
},
),
),
),
),
));
await tester.sendKeyEvent(LogicalKeyboardKey.space);
await tester.pump();
expect(log, equals(<String>['tap']));
log.clear();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(log, equals(<String>['tap']));
});
testWidgets('long-press and tap on disabled should not throw', (WidgetTester tester) async {
await tester.pumpWidget(const Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: InkWell(),
),
),
));
await tester.tap(find.byType(InkWell), pointer: 1);
await tester.pump(const Duration(seconds: 1));
await tester.longPress(find.byType(InkWell), pointer: 1);
await tester.pump(const Duration(seconds: 1));
});
testWidgets('ink well changes color on hover', (WidgetTester tester) async {
await tester.pumpWidget(Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: InkWell(
hoverColor: const Color(0xff00ff00),
splashColor: const Color(0xffff0000),
focusColor: const Color(0xff0000ff),
highlightColor: const Color(0xf00fffff),
onTap: () { },
onLongPress: () { },
onHover: (bool hover) { },
),
),
),
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(SizedBox)));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paints..rect(rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), color: const Color(0xff00ff00)));
});
testWidgets('ink well changes color on hover with overlayColor', (WidgetTester tester) async {
// Same test as 'ink well changes color on hover' except that the
// hover color is specified with the overlayColor parameter.
await tester.pumpWidget(Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: InkWell(
overlayColor: MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return const Color(0xff00ff00);
}
if (states.contains(MaterialState.focused)) {
return const Color(0xff0000ff);
}
if (states.contains(MaterialState.pressed)) {
return const Color(0xf00fffff);
}
return const Color(0xffbadbad); // Shouldn't happen.
}),
onTap: () { },
onLongPress: () { },
onHover: (bool hover) { },
),
),
),
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(SizedBox)));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paints..rect(rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), color: const Color(0xff00ff00)));
});
testWidgets('ink response changes color on focus', (WidgetTester tester) async {
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus');
await tester.pumpWidget(
Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: InkWell(
focusNode: focusNode,
hoverColor: const Color(0xff00ff00),
splashColor: const Color(0xffff0000),
focusColor: const Color(0xff0000ff),
highlightColor: const Color(0xf00fffff),
onTap: () { },
onLongPress: () { },
onHover: (bool hover) { },
),
),
),
),
),
);
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paintsExactlyCountTimes(#drawRect, 0));
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(
inkFeatures,
paints ..rect(rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), color: const Color(0xff0000ff)),
);
focusNode.dispose();
});
testWidgets('ink response changes color on focus with overlayColor', (WidgetTester tester) async {
// Same test as 'ink well changes color on focus' except that the
// hover color is specified with the overlayColor parameter.
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus');
await tester.pumpWidget(
Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: InkWell(
focusNode: focusNode,
overlayColor: MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return const Color(0xff00ff00);
}
if (states.contains(MaterialState.focused)) {
return const Color(0xff0000ff);
}
if (states.contains(MaterialState.pressed)) {
return const Color(0xf00fffff);
}
return const Color(0xffbadbad); // Shouldn't happen.
}),
highlightColor: const Color(0xf00fffff),
onTap: () { },
onLongPress: () { },
onHover: (bool hover) { },
),
),
),
),
),
);
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paintsExactlyCountTimes(#drawRect, 0));
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(
inkFeatures,
paints..rect(rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), color: const Color(0xff0000ff)),
);
focusNode.dispose();
});
testWidgets('ink well changes color on pressed with overlayColor', (WidgetTester tester) async {
const Color pressedColor = Color(0xffdd00ff);
await tester.pumpWidget(Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Container(
alignment: Alignment.topLeft,
child: SizedBox(
width: 100,
height: 100,
child: InkWell(
splashFactory: NoSplash.splashFactory,
overlayColor: MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) {
if (states.contains(MaterialState.pressed)) {
return pressedColor;
}
return const Color(0xffbadbad); // Shouldn't happen.
}),
onTap: () { },
),
),
),
),
));
await tester.pumpAndSettle();
final TestGesture gesture = await tester.startGesture(tester.getRect(find.byType(InkWell)).center);
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paints..rect(rect: const Rect.fromLTRB(0, 0, 100, 100), color: pressedColor.withAlpha(0)));
await tester.pumpAndSettle(); // Let the press highlight animation finish.
expect(inkFeatures, paints..rect(rect: const Rect.fromLTRB(0, 0, 100, 100), color: pressedColor));
await gesture.up();
});
testWidgets('ink response splashColor matches splashColor parameter', (WidgetTester tester) async {
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTouch;
final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus');
const Color splashColor = Color(0xffff0000);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Focus(
focusNode: focusNode,
child: SizedBox(
width: 100,
height: 100,
child: InkWell(
hoverColor: const Color(0xff00ff00),
splashColor: splashColor,
focusColor: const Color(0xff0000ff),
highlightColor: const Color(0xf00fffff),
onTap: () { },
onLongPress: () { },
onHover: (bool hover) { },
),
),
),
),
),
),
));
await tester.pumpAndSettle();
final TestGesture gesture = await tester.startGesture(tester.getRect(find.byType(InkWell)).center);
await tester.pump(const Duration(milliseconds: 200)); // unconfirmed splash is well underway
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paints..circle(x: 50, y: 50, color: splashColor));
await gesture.up();
focusNode.dispose();
});
testWidgets('ink response splashColor matches resolved overlayColor for MaterialState.pressed', (WidgetTester tester) async {
// Same test as 'ink response splashColor matches splashColor
// parameter' except that the splash color is specified with the
// overlayColor parameter.
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTouch;
final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus');
const Color splashColor = Color(0xffff0000);
await tester.pumpWidget(MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: Focus(
focusNode: focusNode,
child: SizedBox(
width: 100,
height: 100,
child: InkWell(
overlayColor: MaterialStateProperty.resolveWith<Color>((Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return const Color(0xff00ff00);
}
if (states.contains(MaterialState.focused)) {
return const Color(0xff0000ff);
}
if (states.contains(MaterialState.pressed)) {
return splashColor;
}
return const Color(0xffbadbad); // Shouldn't happen.
}),
onTap: () { },
onLongPress: () { },
onHover: (bool hover) { },
),
),
),
),
),
),
));
await tester.pumpAndSettle();
final TestGesture gesture = await tester.startGesture(tester.getRect(find.byType(InkWell)).center);
await tester.pump(const Duration(milliseconds: 200)); // unconfirmed splash is well underway
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paints..circle(x: 50, y: 50, color: splashColor));
await gesture.up();
focusNode.dispose();
});
testWidgets('ink response uses radius for focus highlight', (WidgetTester tester) async {
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus');
await tester.pumpWidget(
Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: InkResponse(
focusNode: focusNode,
radius: 20,
focusColor: const Color(0xff0000ff),
onTap: () { },
),
),
),
),
),
);
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 0));
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(inkFeatures, paints..circle(radius: 20, color: const Color(0xff0000ff)));
focusNode.dispose();
});
testWidgets('InkWell uses borderRadius for focus highlight', (WidgetTester tester) async {
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus');
await tester.pumpWidget(
Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: InkWell(
focusNode: focusNode,
borderRadius: BorderRadius.circular(10),
focusColor: const Color(0xff0000ff),
onTap: () { },
),
),
),
),
),
);
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0));
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 1));
expect(inkFeatures, paints..rrect(
rrect: RRect.fromLTRBR(350.0, 250.0, 450.0, 350.0, const Radius.circular(10)),
color: const Color(0xff0000ff),
));
focusNode.dispose();
});
testWidgets('InkWell uses borderRadius for hover highlight', (WidgetTester tester) async {
await tester.pumpWidget(
Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: MouseRegion(
child: InkWell(
borderRadius: BorderRadius.circular(10),
hoverColor: const Color(0xff00ff00),
onTap: () { },
),
),
),
),
),
),
);
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0));
// Hover the ink well.
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getRect(find.byType(InkWell)).center);
await tester.pumpAndSettle();
expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 1));
expect(inkFeatures, paints..rrect(
rrect: RRect.fromLTRBR(350.0, 250.0, 450.0, 350.0, const Radius.circular(10)),
color: const Color(0xff00ff00),
));
});
testWidgets('InkWell customBorder clips for focus highlight', (WidgetTester tester) async {
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus');
await tester.pumpWidget(
Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: SizedBox(
width: 100,
height: 100,
child: MouseRegion(
child: InkWell(
focusNode: focusNode,
borderRadius: BorderRadius.circular(10),
customBorder: const CircleBorder(),
hoverColor: const Color(0xff00ff00),
onTap: () { },
),
),
),
),
),
),
);
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 0));
expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0));
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 1));
expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 1));
// Create a rounded rectangle path with a radius that makes it similar to the custom border circle.
const Rect expectedClipRect = Rect.fromLTRB(0, 0, 100, 100);
final Path expectedClipPath = Path()
..addRRect(RRect.fromRectAndRadius(
expectedClipRect,
const Radius.circular(50.0),
));
// The ink well custom border path should match the rounded rectangle path.
expect(
inkFeatures,
paints..clipPath(pathMatcher: coversSameAreaAs(
expectedClipPath,
areaToCompare: expectedClipRect.inflate(20.0),
sampleSize: 100,
)),
);
focusNode.dispose();
});
testWidgets('InkWell customBorder clips for hover highlight', (WidgetTester tester) async {
await tester.pumpWidget(
Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: SizedBox(
width: 100,
height: 100,
child: MouseRegion(
child: InkWell(
borderRadius: BorderRadius.circular(10),
customBorder: const CircleBorder(),
hoverColor: const Color(0xff00ff00),
onTap: () { },
),
),
),
),
),
),
);
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 0));
expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0));
// Hover the ink well.
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getRect(find.byType(InkWell)).center);
await tester.pumpAndSettle();
expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 1));
expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 1));
// Create a rounded rectangle path with a radius that makes it similar to the custom border circle.
const Rect expectedClipRect = Rect.fromLTRB(0, 0, 100, 100);
final Path expectedClipPath = Path()
..addRRect(RRect.fromRectAndRadius(
expectedClipRect,
const Radius.circular(50.0),
));
// The ink well custom border path should match the rounded rectangle path.
expect(
inkFeatures,
paints..clipPath(pathMatcher: coversSameAreaAs(
expectedClipPath,
areaToCompare: expectedClipRect.inflate(20.0),
sampleSize: 100,
)),
);
});
testWidgets('InkResponse radius can be updated', (WidgetTester tester) async {
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus');
Widget boilerplate(double radius) {
return Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: InkResponse(
focusNode: focusNode,
radius: radius,
focusColor: const Color(0xff0000ff),
onTap: () { },
),
),
),
),
);
}
await tester.pumpWidget(boilerplate(10));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 0));
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 1));
expect(inkFeatures, paints..circle(radius: 10, color: const Color(0xff0000ff)));
await tester.pumpWidget(boilerplate(20));
await tester.pumpAndSettle();
expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 1));
expect(inkFeatures, paints..circle(radius: 20, color: const Color(0xff0000ff)));
focusNode.dispose();
});
testWidgets('InkResponse highlightShape can be updated', (WidgetTester tester) async {
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus');
Widget boilerplate(BoxShape shape) {
return Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: InkResponse(
focusNode: focusNode,
highlightShape: shape,
borderRadius: BorderRadius.circular(10),
focusColor: const Color(0xff0000ff),
onTap: () { },
),
),
),
),
);
}
await tester.pumpWidget(boilerplate(BoxShape.circle));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 0));
expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0));
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 1));
expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0));
await tester.pumpWidget(boilerplate(BoxShape.rectangle));
await tester.pumpAndSettle();
expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 0));
expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 1));
focusNode.dispose();
});
testWidgets('InkWell borderRadius can be updated', (WidgetTester tester) async {
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus');
Widget boilerplate(BorderRadius borderRadius) {
return Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: InkWell(
focusNode: focusNode,
borderRadius: borderRadius,
focusColor: const Color(0xff0000ff),
onTap: () { },
),
),
),
),
);
}
await tester.pumpWidget(boilerplate(BorderRadius.circular(10)));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 0));
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 1));
expect(inkFeatures, paints..rrect(
rrect: RRect.fromLTRBR(350.0, 250.0, 450.0, 350.0, const Radius.circular(10)),
color: const Color(0xff0000ff),
));
await tester.pumpWidget(boilerplate(BorderRadius.circular(30)));
await tester.pumpAndSettle();
expect(inkFeatures, paintsExactlyCountTimes(#drawRRect, 1));
expect(inkFeatures, paints..rrect(
rrect: RRect.fromLTRBR(350.0, 250.0, 450.0, 350.0, const Radius.circular(30)),
color: const Color(0xff0000ff),
));
focusNode.dispose();
});
testWidgets('InkWell customBorder can be updated', (WidgetTester tester) async {
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTraditional;
final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus');
Widget boilerplate(BorderRadius borderRadius) {
return Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: SizedBox(
width: 100,
height: 100,
child: MouseRegion(
child: InkWell(
focusNode: focusNode,
customBorder: RoundedRectangleBorder(borderRadius: borderRadius),
hoverColor: const Color(0xff00ff00),
onTap: () { },
),
),
),
),
),
);
}
await tester.pumpWidget(boilerplate(BorderRadius.circular(20)));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 0));
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 1));
const Rect expectedClipRect = Rect.fromLTRB(0, 0, 100, 100);
Path expectedClipPath = Path()
..addRRect(RRect.fromRectAndRadius(
expectedClipRect,
const Radius.circular(20),
));
expect(
inkFeatures,
paints..clipPath(pathMatcher: coversSameAreaAs(
expectedClipPath,
areaToCompare: expectedClipRect.inflate(20.0),
sampleSize: 100,
)),
);
await tester.pumpWidget(boilerplate(BorderRadius.circular(40)));
await tester.pumpAndSettle();
expectedClipPath = Path()
..addRRect(RRect.fromRectAndRadius(
expectedClipRect,
const Radius.circular(40),
));
expect(
inkFeatures,
paints..clipPath(pathMatcher: coversSameAreaAs(
expectedClipPath,
areaToCompare: expectedClipRect.inflate(20.0),
sampleSize: 100,
)),
);
focusNode.dispose();
});
testWidgets('InkWell splash customBorder can be updated', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/121626.
final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus');
Widget boilerplate(BorderRadius borderRadius) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: SizedBox(
width: 100,
height: 100,
child: MouseRegion(
child: InkWell(
focusNode: focusNode,
customBorder: RoundedRectangleBorder(borderRadius: borderRadius),
onTap: () { },
),
),
),
),
),
),
);
}
await tester.pumpWidget(boilerplate(BorderRadius.circular(20)));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 0));
final TestGesture gesture = await tester.startGesture(tester.getRect(find.byType(InkWell)).center);
await tester.pump(const Duration(milliseconds: 200)); // Unconfirmed splash is well underway.
expect(inkFeatures, paintsExactlyCountTimes(#clipPath, 2)); // Splash and highlight.
const Rect expectedClipRect = Rect.fromLTRB(0, 0, 100, 100);
Path expectedClipPath = Path()
..addRRect(RRect.fromRectAndRadius(
expectedClipRect,
const Radius.circular(20),
));
// Check that the splash and the highlight are correctly clipped.
expect(
inkFeatures,
paints
..clipPath(pathMatcher: coversSameAreaAs(
expectedClipPath,
areaToCompare: expectedClipRect.inflate(20.0),
sampleSize: 100,
))
..clipPath(pathMatcher: coversSameAreaAs(
expectedClipPath,
areaToCompare: expectedClipRect.inflate(20.0),
sampleSize: 100,
)),
);
await tester.pumpWidget(boilerplate(BorderRadius.circular(40)));
await tester.pumpAndSettle();
expectedClipPath = Path()
..addRRect(RRect.fromRectAndRadius(
expectedClipRect,
const Radius.circular(40),
));
// Check that the splash and the highlight are correctly clipped.
expect(
inkFeatures,
paints
..clipPath(pathMatcher: coversSameAreaAs(
expectedClipPath,
areaToCompare: expectedClipRect.inflate(20.0),
sampleSize: 100,
))
..clipPath(pathMatcher: coversSameAreaAs(
expectedClipPath,
areaToCompare: expectedClipRect.inflate(20.0),
sampleSize: 100,
)),
);
await gesture.up();
focusNode.dispose();
});
testWidgets("ink response doesn't change color on focus when on touch device", (WidgetTester tester) async {
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTouch;
final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus');
await tester.pumpWidget(Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: InkWell(
focusNode: focusNode,
hoverColor: const Color(0xff00ff00),
splashColor: const Color(0xffff0000),
focusColor: const Color(0xff0000ff),
highlightColor: const Color(0xf00fffff),
onTap: () { },
onLongPress: () { },
onHover: (bool hover) { },
),
),
),
),
));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paintsExactlyCountTimes(#drawRect, 0));
focusNode.requestFocus();
await tester.pumpAndSettle();
expect(inkFeatures, paintsExactlyCountTimes(#drawRect, 0));
focusNode.dispose();
});
testWidgets('InkWell.mouseCursor changes cursor on hover', (WidgetTester tester) async {
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: const Offset(1, 1));
// Test argument works
await tester.pumpWidget(
Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: InkWell(
mouseCursor: SystemMouseCursors.click,
onTap: () {},
),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
// Test default of InkWell()
await tester.pumpWidget(
Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: InkWell(
onTap: () {},
),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
// Test disabled
await tester.pumpWidget(
const Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: InkWell(),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
// Test default of InkResponse()
await tester.pumpWidget(
Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: InkResponse(
onTap: () {},
),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
// Test disabled
await tester.pumpWidget(
const Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: InkResponse(),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
});
testWidgets('InkResponse containing selectable text changes mouse cursor when hovered', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/104595.
await tester.pumpWidget(MaterialApp(
home: SelectionArea(
child: Material(
child: InkResponse(
onTap: () {},
child: const Text('button'),
),
),
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.byType(Text)));
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
});
group('feedback', () {
late FeedbackTester feedback;
setUp(() {
feedback = FeedbackTester();
});
tearDown(() {
feedback.dispose();
});
testWidgets('enabled (default)', (WidgetTester tester) async {
await tester.pumpWidget(Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: InkWell(
onTap: () { },
onLongPress: () { },
),
),
),
));
await tester.tap(find.byType(InkWell), pointer: 1);
await tester.pump(const Duration(seconds: 1));
expect(feedback.clickSoundCount, 1);
expect(feedback.hapticCount, 0);
await tester.tap(find.byType(InkWell), pointer: 1);
await tester.pump(const Duration(seconds: 1));
expect(feedback.clickSoundCount, 2);
expect(feedback.hapticCount, 0);
await tester.longPress(find.byType(InkWell), pointer: 1);
await tester.pump(const Duration(seconds: 1));
expect(feedback.clickSoundCount, 2);
expect(feedback.hapticCount, 1);
});
testWidgets('disabled', (WidgetTester tester) async {
await tester.pumpWidget(Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: InkWell(
onTap: () { },
onLongPress: () { },
enableFeedback: false,
),
),
),
));
await tester.tap(find.byType(InkWell), pointer: 1);
await tester.pump(const Duration(seconds: 1));
expect(feedback.clickSoundCount, 0);
expect(feedback.hapticCount, 0);
await tester.longPress(find.byType(InkWell), pointer: 1);
await tester.pump(const Duration(seconds: 1));
expect(feedback.clickSoundCount, 0);
expect(feedback.hapticCount, 0);
});
});
testWidgets('splashing survives scrolling when keep-alive is enabled', (WidgetTester tester) async {
Future<void> runTest(bool keepAlive) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: CompositedTransformFollower(
// forces a layer, which makes the paints easier to separate out
link: LayerLink(),
child: ListView(
addAutomaticKeepAlives: keepAlive,
dragStartBehavior: DragStartBehavior.down,
children: <Widget>[
SizedBox(height: 500.0, child: InkWell(onTap: () {}, child: const Placeholder())),
const SizedBox(height: 500.0),
const SizedBox(height: 500.0),
],
),
),
),
),
);
expect(tester.renderObject<RenderProxyBox>(find.byType(PhysicalModel)).child, isNot(paints..circle()));
await tester.tap(find.byType(InkWell));
await tester.pump();
await tester.pump(const Duration(milliseconds: 10));
expect(tester.renderObject<RenderProxyBox>(find.byType(PhysicalModel)).child, paints..circle());
await tester.drag(find.byType(ListView), const Offset(0.0, -1000.0));
await tester.pump(const Duration(milliseconds: 10));
await tester.drag(find.byType(ListView), const Offset(0.0, 1000.0));
await tester.pump(const Duration(milliseconds: 10));
expect(
tester.renderObject<RenderProxyBox>(find.byType(PhysicalModel)).child,
keepAlive ? (paints..circle()) : isNot(paints..circle()),
);
}
await runTest(true);
await runTest(false);
});
testWidgets('excludeFromSemantics', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: InkWell(
onTap: () { },
child: const Text('Button'),
),
),
));
expect(semantics, includesNodeWith(label: 'Button', actions: <SemanticsAction>[SemanticsAction.tap]));
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: InkWell(
onTap: () { },
excludeFromSemantics: true,
child: const Text('Button'),
),
),
));
expect(semantics, isNot(includesNodeWith(label: 'Button', actions: <SemanticsAction>[SemanticsAction.tap])));
semantics.dispose();
});
testWidgets("ink response doesn't focus when disabled", (WidgetTester tester) async {
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTouch;
final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus');
final GlobalKey childKey = GlobalKey();
await tester.pumpWidget(
Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: InkWell(
autofocus: true,
onTap: () {},
onLongPress: () {},
onHover: (bool hover) {},
focusNode: focusNode,
child: Container(key: childKey),
),
),
),
);
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
await tester.pumpWidget(
Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: InkWell(
focusNode: focusNode,
child: Container(key: childKey),
),
),
),
);
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isFalse);
focusNode.dispose();
});
testWidgets('ink response accepts focus when disabled in directional navigation mode', (WidgetTester tester) async {
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTouch;
final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus');
final GlobalKey childKey = GlobalKey();
await tester.pumpWidget(
Material(
child: MediaQuery(
data: const MediaQueryData(
navigationMode: NavigationMode.directional,
),
child: Directionality(
textDirection: TextDirection.ltr,
child: InkWell(
autofocus: true,
onTap: () {},
onLongPress: () {},
onHover: (bool hover) {},
focusNode: focusNode,
child: Container(key: childKey),
),
),
),
),
);
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
await tester.pumpWidget(
Material(
child: MediaQuery(
data: const MediaQueryData(
navigationMode: NavigationMode.directional,
),
child: Directionality(
textDirection: TextDirection.ltr,
child: InkWell(
focusNode: focusNode,
child: Container(key: childKey),
),
),
),
),
);
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
focusNode.dispose();
});
testWidgets("ink response doesn't hover when disabled", (WidgetTester tester) async {
FocusManager.instance.highlightStrategy = FocusHighlightStrategy.alwaysTouch;
final FocusNode focusNode = FocusNode(debugLabel: 'Ink Focus');
final GlobalKey childKey = GlobalKey();
bool hovering = false;
await tester.pumpWidget(
Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: SizedBox(
width: 100,
height: 100,
child: InkWell(
autofocus: true,
onTap: () {},
onLongPress: () {},
onHover: (bool value) { hovering = value; },
focusNode: focusNode,
child: SizedBox(key: childKey),
),
),
),
),
);
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isTrue);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byKey(childKey)));
await tester.pumpAndSettle();
expect(hovering, isTrue);
await tester.pumpWidget(
Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: SizedBox(
width: 100,
height: 100,
child: InkWell(
focusNode: focusNode,
onHover: (bool value) { hovering = value; },
child: SizedBox(key: childKey),
),
),
),
),
);
await tester.pumpAndSettle();
expect(focusNode.hasPrimaryFocus, isFalse);
focusNode.dispose();
});
testWidgets('When ink wells are nested, only the inner one is triggered by tap splash', (WidgetTester tester) async {
final GlobalKey middleKey = GlobalKey();
final GlobalKey innerKey = GlobalKey();
Widget paddedInkWell({Key? key, Widget? child}) {
return InkWell(
key: key,
onTap: () {},
child: Padding(
padding: const EdgeInsets.all(50),
child: child,
),
);
}
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: paddedInkWell(
child: paddedInkWell(
key: middleKey,
child: paddedInkWell(
key: innerKey,
child: const SizedBox(width: 50, height: 50),
),
),
),
),
),
),
),
);
final MaterialInkController material = Material.of(tester.element(find.byKey(innerKey)));
// Press
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(innerKey)), pointer: 1);
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
// Up
await gesture.up();
await tester.pumpAndSettle();
expect(material, paintsNothing);
// Press again
await gesture.down(tester.getCenter(find.byKey(innerKey)));
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
// Cancel
await gesture.cancel();
await tester.pumpAndSettle();
expect(material, paintsNothing);
// Press again
await gesture.down(tester.getCenter(find.byKey(innerKey)));
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
// Use a second pointer to press
final TestGesture gesture2 = await tester.startGesture(tester.getCenter(find.byKey(innerKey)), pointer: 2);
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
await gesture2.up();
});
testWidgets('Reparenting parent should allow both inkwells to show splash afterwards', (WidgetTester tester) async {
final GlobalKey middleKey = GlobalKey();
final GlobalKey innerKey = GlobalKey();
Widget paddedInkWell({Key? key, Widget? child}) {
return InkWell(
key: key,
onTap: () {},
child: Padding(
padding: const EdgeInsets.all(50),
child: child,
),
);
}
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: SizedBox(
width: 200,
height: 100,
child: Row(
children: <Widget>[
paddedInkWell(
key: middleKey,
child: paddedInkWell(
key: innerKey,
),
),
const SizedBox(),
],
),
),
),
),
),
),
);
final MaterialInkController material = Material.of(tester.element(find.byKey(innerKey)));
// Press
final TestGesture gesture1 = await tester.startGesture(tester.getCenter(find.byKey(innerKey)), pointer: 1);
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
// Reparent parent
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: SizedBox(
width: 200,
height: 100,
child: Row(
children: <Widget>[
paddedInkWell(
key: innerKey,
),
paddedInkWell(
key: middleKey,
),
],
),
),
),
),
),
),
);
// Up
await gesture1.up();
await tester.pumpAndSettle();
expect(material, paintsNothing);
// Press the previous parent
await gesture1.down(tester.getCenter(find.byKey(middleKey)));
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
// Use a second pointer to press the previous child
final TestGesture gesture2 = await tester.startGesture(tester.getCenter(find.byKey(innerKey)), pointer: 2);
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 2));
// Finish gesture to release resources.
await gesture1.up();
await gesture2.up();
await tester.pumpAndSettle();
});
testWidgets('Parent inkwell does not block child inkwells from splashes', (WidgetTester tester) async {
final GlobalKey middleKey = GlobalKey();
final GlobalKey innerKey = GlobalKey();
Widget paddedInkWell({Key? key, Widget? child}) {
return InkWell(
key: key,
onTap: () {},
child: Padding(
padding: const EdgeInsets.all(50),
child: child,
),
);
}
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: paddedInkWell(
child: paddedInkWell(
key: middleKey,
child: paddedInkWell(
key: innerKey,
child: const SizedBox(width: 50, height: 50),
),
),
),
),
),
),
),
);
final MaterialInkController material = Material.of(tester.element(find.byKey(innerKey)));
// Press middle
final TestGesture gesture1 = await tester.startGesture(tester.getTopLeft(find.byKey(middleKey)) + const Offset(1, 1), pointer: 1);
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
// Press inner
final TestGesture gesture2 = await tester.startGesture(tester.getCenter(find.byKey(innerKey)), pointer: 2);
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 2));
// Finish gesture to release resources.
await gesture1.up();
await gesture2.up();
await tester.pumpAndSettle();
});
testWidgets('Parent inkwell can count the number of pressed children to prevent splash', (WidgetTester tester) async {
final GlobalKey parentKey = GlobalKey();
final GlobalKey leftKey = GlobalKey();
final GlobalKey rightKey = GlobalKey();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: InkWell(
key: parentKey,
onTap: () {},
child: Center(
child: SizedBox(
width: 100,
height: 50,
child: Row(
children: <Widget>[
SizedBox(
width: 50,
height: 50,
child: InkWell(
key: leftKey,
onTap: () {},
),
),
SizedBox(
width: 50,
height: 50,
child: InkWell(
key: rightKey,
onTap: () {},
),
),
],
),
),
),
),
),
),
),
),
),
);
final MaterialInkController material = Material.of(tester.element(find.byKey(leftKey)));
final Offset parentPosition = tester.getTopLeft(find.byKey(parentKey)) + const Offset(1, 1);
// Press left child
final TestGesture gesture1 = await tester.startGesture(tester.getCenter(find.byKey(leftKey)), pointer: 1);
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
// Press right child
final TestGesture gesture2 = await tester.startGesture(tester.getCenter(find.byKey(rightKey)), pointer: 2);
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 2));
// Press parent
final TestGesture gesture3 = await tester.startGesture(parentPosition, pointer: 3);
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 2));
await gesture3.up();
// Release left child
await gesture1.up();
await tester.pumpAndSettle();
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
// Press parent
await gesture3.down(parentPosition);
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
await gesture3.up();
// Release right child
await gesture2.up();
await tester.pumpAndSettle();
expect(material, paintsExactlyCountTimes(#drawCircle, 0));
// Press parent
await gesture3.down(parentPosition);
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
await gesture3.up();
});
testWidgets('When ink wells are reparented, the old parent can display splash while the new parent can not', (WidgetTester tester) async {
final GlobalKey innerKey = GlobalKey();
final GlobalKey leftKey = GlobalKey();
final GlobalKey rightKey = GlobalKey();
Widget doubleInkWellRow({
required double leftWidth,
required double rightWidth,
Widget? leftChild,
Widget? rightChild,
}) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: SizedBox(
width: leftWidth+rightWidth,
height: 100,
child: Row(
children: <Widget>[
SizedBox(
width: leftWidth,
height: 100,
child: InkWell(
key: leftKey,
onTap: () {},
child: Center(
child: SizedBox(
width: leftWidth,
height: 50,
child: leftChild,
),
),
),
),
SizedBox(
width: rightWidth,
height: 100,
child: InkWell(
key: rightKey,
onTap: () {},
child: Center(
child: SizedBox(
width: leftWidth,
height: 50,
child: rightChild,
),
),
),
),
],
),
),
),
),
),
);
}
await tester.pumpWidget(
doubleInkWellRow(
leftWidth: 110,
rightWidth: 90,
leftChild: InkWell(
key: innerKey,
onTap: () {},
),
),
);
final MaterialInkController material = Material.of(tester.element(find.byKey(innerKey)));
// Press inner
final TestGesture gesture = await tester.startGesture(const Offset(100, 50), pointer: 1);
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
// Switch side
await tester.pumpWidget(
doubleInkWellRow(
leftWidth: 90,
rightWidth: 110,
rightChild: InkWell(
key: innerKey,
onTap: () {},
),
),
);
expect(material, paintsExactlyCountTimes(#drawCircle, 0));
// A second pointer presses inner
final TestGesture gesture2 = await tester.startGesture(const Offset(100, 50), pointer: 2);
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
await gesture.up();
await gesture2.up();
await tester.pumpAndSettle();
// Press inner
await gesture.down(const Offset(100, 50));
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
// Press left
await gesture2.down(const Offset(50, 50));
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 2));
await gesture.up();
await gesture2.up();
});
testWidgets("Ink wells's splash starts before tap is confirmed and disappear after tap is canceled", (WidgetTester tester) async {
final GlobalKey innerKey = GlobalKey();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: GestureDetector(
onHorizontalDragStart: (_) {},
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: InkWell(
onTap: () {},
child: Center(
child: SizedBox(
width: 50,
height: 50,
child: InkWell(
key: innerKey,
onTap: () {},
),
),
),
),
),
),
),
),
),
),
);
final MaterialInkController material = Material.of(tester.element(find.byKey(innerKey)));
// Press
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byKey(innerKey)), pointer: 1);
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
// Scroll upward
await gesture.moveBy(const Offset(0, -100));
await tester.pumpAndSettle();
expect(material, paintsNothing);
// Up
await gesture.up();
await tester.pumpAndSettle();
expect(material, paintsNothing);
// Press again
await gesture.down(tester.getCenter(find.byKey(innerKey)));
await tester.pump(const Duration(milliseconds: 200));
expect(material, paintsExactlyCountTimes(#drawCircle, 1));
});
testWidgets('disabled and hovered inkwell responds to mouse-exit', (WidgetTester tester) async {
int onHoverCount = 0;
late bool hover;
Widget buildFrame({ required bool enabled }) {
return Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: InkWell(
onTap: enabled ? () { } : null,
onHover: (bool value) {
onHoverCount += 1;
hover = value;
},
),
),
),
),
);
}
await tester.pumpWidget(buildFrame(enabled: true));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(InkWell)));
await tester.pumpAndSettle();
expect(onHoverCount, 1);
expect(hover, true);
await tester.pumpWidget(buildFrame(enabled: false));
await tester.pumpAndSettle();
await gesture.moveTo(Offset.zero);
// Even though the InkWell has been disabled, the mouse-exit still
// causes onHover(false) to be called.
expect(onHoverCount, 2);
expect(hover, false);
await gesture.moveTo(tester.getCenter(find.byType(InkWell)));
await tester.pumpAndSettle();
// We no longer see hover events because the InkWell is disabled
// and it's no longer in the "hovering" state.
expect(onHoverCount, 2);
expect(hover, false);
await tester.pumpWidget(buildFrame(enabled: true));
await tester.pumpAndSettle();
// The InkWell was enabled while it contained the mouse, however
// we do not call onHover() because it may call setState().
expect(onHoverCount, 2);
expect(hover, false);
await gesture.moveTo(tester.getCenter(find.byType(InkWell)) - const Offset(1, 1));
await tester.pumpAndSettle();
// Moving the mouse a little within the InkWell doesn't change anything.
expect(onHoverCount, 2);
expect(hover, false);
});
testWidgets('hovered ink well draws a transparent highlight when disabled', (WidgetTester tester) async {
Widget buildFrame({ required bool enabled }) {
return Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: InkWell(
onTap: enabled ? () { } : null,
onHover: (bool value) { },
hoverColor: const Color(0xff00ff00),
),
),
),
),
);
}
await tester.pumpWidget(buildFrame(enabled: true));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
// Hover the enabled InkWell.
await gesture.moveTo(tester.getCenter(find.byType(InkWell)));
await tester.pumpAndSettle();
expect(
find.byType(Material),
paints
..rect(
color: const Color(0xff00ff00),
rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0),
)
);
// Disable the hovered InkWell.
await tester.pumpWidget(buildFrame(enabled: false));
await tester.pumpAndSettle();
expect(
find.byType(Material),
paints
..rect(
color: const Color(0x0000ff00),
rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0),
)
);
});
testWidgets('Changing InkWell.enabled should not trigger TextButton setState()', (WidgetTester tester) async {
Widget buildFrame({ required bool enabled }) {
return Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: TextButton(
onPressed: enabled ? () { } : null,
child: const Text('button'),
),
),
),
);
}
await tester.pumpWidget(buildFrame(enabled: false));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(TextButton)));
await tester.pumpAndSettle();
// Rebuilding the button with enabled:true causes InkWell.didUpdateWidget()
// to be called per the change in its enabled flag. If onHover() was called,
// this test would crash.
await tester.pumpWidget(buildFrame(enabled: true));
await tester.pumpAndSettle();
// Rebuild again, with enabled:false
await gesture.moveBy(const Offset(1, 1));
await tester.pumpWidget(buildFrame(enabled: false));
await tester.pumpAndSettle();
});
testWidgets('InkWell does not attach semantics handler for onTap if it was not provided an onTap handler', (WidgetTester tester) async {
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: InkWell(
onLongPress: () { },
child: const Text('Foo'),
),
),
),
));
expect(tester.getSemantics(find.bySemanticsLabel('Foo')), matchesSemantics(
label: 'Foo',
hasLongPressAction: true,
isFocusable: true,
textDirection: TextDirection.ltr,
));
// Add tap handler and confirm addition to semantic actions.
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: InkWell(
onLongPress: () { },
onTap: () { },
child: const Text('Foo'),
),
),
),
));
expect(tester.getSemantics(find.bySemanticsLabel('Foo')), matchesSemantics(
label: 'Foo',
hasTapAction: true,
hasLongPressAction: true,
isFocusable: true,
textDirection: TextDirection.ltr,
));
});
testWidgets('InkWell highlight should not survive after [onTapDown, onDoubleTap] sequence', (WidgetTester tester) async {
final List<String> log = <String>[];
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: InkWell(
onTap: () {
log.add('tap');
},
onDoubleTap: () {
log.add('double-tap');
},
onTapDown: (TapDownDetails details) {
log.add('tap-down');
},
onTapCancel: () {
log.add('tap-cancel');
},
),
),
),
));
final Offset taplocation = tester.getRect(find.byType(InkWell)).center;
final TestGesture gesture = await tester.startGesture(taplocation);
await tester.pump(const Duration(milliseconds: 100));
expect(log, equals(<String>['tap-down']));
await gesture.up();
await tester.pump(const Duration(milliseconds: 100));
await tester.tap(find.byType(InkWell));
await tester.pump(const Duration(milliseconds: 100));
expect(log, equals(<String>['tap-down', 'double-tap']));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paintsExactlyCountTimes(#drawRect, 0));
});
testWidgets('InkWell splash should not survive after [onTapDown, onTapDown, onTapCancel, onDoubleTap] sequence', (WidgetTester tester) async {
final List<String> log = <String>[];
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: InkWell(
onTap: () {
log.add('tap');
},
onDoubleTap: () {
log.add('double-tap');
},
onTapDown: (TapDownDetails details) {
log.add('tap-down');
},
onTapCancel: () {
log.add('tap-cancel');
},
),
),
),
));
final Offset tapLocation = tester.getRect(find.byType(InkWell)).center;
final TestGesture gesture1 = await tester.startGesture(tapLocation);
await tester.pump(const Duration(milliseconds: 100));
expect(log, equals(<String>['tap-down']));
await gesture1.up();
await tester.pump(const Duration(milliseconds: 100));
final TestGesture gesture2 = await tester.startGesture(tapLocation);
await tester.pump(const Duration(milliseconds: 100));
expect(log, equals(<String>['tap-down', 'tap-down']));
await gesture2.up();
await tester.pump(const Duration(milliseconds: 100));
expect(log, equals(<String>['tap-down', 'tap-down', 'tap-cancel', 'double-tap']));
await tester.pumpAndSettle();
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 0));
});
testWidgets('InkWell disposes statesController', (WidgetTester tester) async {
int tapCount = 0;
Widget buildFrame(MaterialStatesController? statesController) {
return MaterialApp(
home: Scaffold(
body: Center(
child: InkWell(
statesController: statesController,
onTap: () { tapCount += 1; },
child: const Text('inkwell'),
),
),
),
);
}
final MaterialStatesController controller = MaterialStatesController();
addTearDown(controller.dispose);
int pressedCount = 0;
controller.addListener(() {
if (controller.value.contains(MaterialState.pressed)) {
pressedCount += 1;
}
});
await tester.pumpWidget(buildFrame(controller));
await tester.tap(find.byType(InkWell));
await tester.pumpAndSettle();
expect(tapCount, 1);
expect(pressedCount, 1);
await tester.pumpWidget(buildFrame(null));
await tester.tap(find.byType(InkWell));
await tester.pumpAndSettle();
expect(tapCount, 2);
expect(pressedCount, 1);
await tester.pumpWidget(buildFrame(controller));
await tester.tap(find.byType(InkWell));
await tester.pumpAndSettle();
expect(tapCount, 3);
expect(pressedCount, 2);
});
testWidgets('ink well overlayColor opacity fades from 0xff when hover ends', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/110266
await tester.pumpWidget(Material(
child: Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100,
height: 100,
child: InkWell(
overlayColor: MaterialStateProperty.resolveWith<Color?>((Set<MaterialState> states) {
if (states.contains(MaterialState.hovered)) {
return const Color(0xff00ff00);
}
return null;
}),
onTap: () { },
onLongPress: () { },
onHover: (bool hover) { },
),
),
),
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tester.getCenter(find.byType(SizedBox)));
await tester.pumpAndSettle();
await gesture.moveTo(const Offset(10, 10)); // fade out the overlay
await tester.pump(); // trigger the fade out animation
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
// Fadeout begins with the MaterialStates.hovered overlay color
expect(inkFeatures, paints..rect(rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), color: const Color(0xff00ff00)));
// 50ms fadeout is 50% complete, overlay color alpha goes from 0xff to 0x80
await tester.pump(const Duration(milliseconds: 25));
expect(inkFeatures, paints..rect(rect: const Rect.fromLTRB(350.0, 250.0, 450.0, 350.0), color: const Color(0x8000ff00)));
});
testWidgets('InkWell secondary tap test', (WidgetTester tester) async {
final List<String> log = <String>[];
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: InkWell(
onSecondaryTap: () {
log.add('secondary-tap');
},
onSecondaryTapDown: (TapDownDetails details) {
log.add('secondary-tap-down');
},
onSecondaryTapUp: (TapUpDetails details) {
log.add('secondary-tap-up');
},
onSecondaryTapCancel: () {
log.add('secondary-tap-cancel');
},
),
),
),
));
await tester.tap(find.byType(InkWell), pointer: 1, buttons: kSecondaryButton);
expect(log, equals(<String>['secondary-tap-down', 'secondary-tap-up', 'secondary-tap']));
log.clear();
final TestGesture gesture = await tester.startGesture(tester.getCenter(find.byType(InkWell)), pointer: 2, buttons: kSecondaryButton);
await gesture.moveTo(const Offset(100, 100));
await gesture.up();
expect(log, equals(<String>['secondary-tap-down', 'secondary-tap-cancel']));
});
// Regression test for https://github.com/flutter/flutter/issues/124328.
testWidgets('InkWell secondary tap should not draw a splash when no secondary callbacks are defined', (WidgetTester tester) async {
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: InkWell(
onTap: () {},
),
),
),
));
final TestGesture gesture = await tester.startGesture(
tester.getRect(find.byType(InkWell)).center,
buttons: kSecondaryButton,
);
await tester.pump(const Duration(milliseconds: 200));
// No splash should be painted.
final RenderObject inkFeatures = tester.allRenderObjects.firstWhere((RenderObject object) => object.runtimeType.toString() == '_RenderInkFeatures');
expect(inkFeatures, paintsExactlyCountTimes(#drawCircle, 0));
await gesture.up();
});
testWidgets('try out hoverDuration property', (WidgetTester tester) async {
final List<String> log = <String>[];
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Material(
child: Center(
child: InkWell(
hoverDuration: const Duration(milliseconds: 1000),
onTap: () {
log.add('tap');
},
),
),
),
));
await tester.tap(find.byType(InkWell), pointer: 1);
await tester.pump(const Duration(seconds: 1));
expect(log, equals(<String>['tap']));
log.clear();
});
testWidgets('InkWell activation action does not end immediately', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/132377.
final MaterialStatesController controller = MaterialStatesController();
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: Shortcuts(
shortcuts: const <ShortcutActivator, Intent>{
SingleActivator(LogicalKeyboardKey.enter): ButtonActivateIntent(),
},
child: Material(
child: Center(
child: InkWell(
autofocus: true,
onTap: () {},
statesController: controller,
),
),
),
),
));
// Invoke the InkWell activation action.
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
// The InkWell is in pressed state.
await tester.pump(const Duration(milliseconds: 99));
expect(controller.value.contains(MaterialState.pressed), isTrue);
await tester.pumpAndSettle();
expect(controller.value.contains(MaterialState.pressed), isFalse);
controller.dispose();
});
}
| flutter/packages/flutter/test/material/ink_well_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/ink_well_test.dart",
"repo_id": "flutter",
"token_count": 35849
} | 664 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
Finder findMenuPanels() {
return find.byWidgetPredicate((Widget widget) => widget.runtimeType.toString() == '_MenuPanel');
}
Material getMenuBarMaterial(WidgetTester tester) {
return tester.widget<Material>(
find.descendant(of: findMenuPanels(), matching: find.byType(Material)).first,
);
}
Padding getMenuBarPadding(WidgetTester tester) {
return tester.widget<Padding>(
find.descendant(of: findMenuPanels(), matching: find.byType(Padding)).first,
);
}
Material getMenuMaterial(WidgetTester tester) {
return tester.widget<Material>(
find.descendant(of: findMenuPanels().at(1), matching: find.byType(Material)).first,
);
}
Padding getMenuPadding(WidgetTester tester) {
return tester.widget<Padding>(
find.descendant(of: findMenuPanels().at(1), matching: find.byType(Padding)).first,
);
}
group('MenuStyle', () {
test('MenuStyle lerp special cases', () {
expect(MenuStyle.lerp(null, null, 0), null);
const MenuStyle data = MenuStyle();
expect(identical(MenuStyle.lerp(data, data, 0.5), data), true);
});
testWidgets('fixedSize affects geometry', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
MenuBarTheme(
data: const MenuBarThemeData(
style: MenuStyle(
fixedSize: MaterialStatePropertyAll<Size>(Size(600, 60)),
),
),
child: MenuTheme(
data: const MenuThemeData(
style: MenuStyle(
fixedSize: MaterialStatePropertyAll<Size>(Size(100, 100)),
),
),
child: MenuBar(
children: createTestMenus(onPressed: (TestMenu menu) {}),
),
),
),
const Expanded(child: Placeholder()),
],
),
),
),
);
// Have to open a menu initially to start things going.
await tester.tap(find.text(TestMenu.mainMenu0.label));
await tester.pump();
// MenuBarTheme affects MenuBar.
expect(tester.getRect(findMenuPanels().first), equals(const Rect.fromLTRB(100.0, 0.0, 700.0, 60.0)));
expect(tester.getRect(findMenuPanels().first).size, equals(const Size(600.0, 60.0)));
// MenuTheme affects menus.
if (!kIsWeb || isCanvasKit) { // https://github.com/flutter/flutter/issues/99933
expect(tester.getRect(findMenuPanels().at(1)), equals(const Rect.fromLTRB(104.0, 54.0, 204.0, 154.0)));
expect(tester.getRect(findMenuPanels().at(1)).size, equals(const Size(100.0, 100.0)));
}
});
testWidgets('maximumSize affects geometry', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
MenuBarTheme(
data: const MenuBarThemeData(
style: MenuStyle(
maximumSize: MaterialStatePropertyAll<Size>(Size(250, 40)),
),
),
child: MenuTheme(
data: const MenuThemeData(
style: MenuStyle(
maximumSize: MaterialStatePropertyAll<Size>(Size(100, 100)),
),
),
child: MenuBar(
children: createTestMenus(onPressed: (TestMenu menu) {}),
),
),
),
const Expanded(child: Placeholder()),
],
),
),
),
);
// Have to open a menu initially to start things going.
await tester.tap(find.text(TestMenu.mainMenu0.label));
await tester.pump();
// MenuBarTheme affects MenuBar.
expect(tester.getRect(findMenuPanels().first), equals(const Rect.fromLTRB(275.0, 0.0, 525.0, 40.0)));
expect(tester.getRect(findMenuPanels().first).size, equals(const Size(250.0, 40.0)));
// MenuTheme affects menus.
expect(tester.getRect(findMenuPanels().at(1)), equals(const Rect.fromLTRB(279.0, 44.0, 379.0, 144.0)));
expect(tester.getRect(findMenuPanels().at(1)).size, equals(const Size(100.0, 100.0)));
});
testWidgets('minimumSize affects geometry', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
MenuBarTheme(
data: const MenuBarThemeData(
style: MenuStyle(
minimumSize: MaterialStatePropertyAll<Size>(Size(400, 60)),
),
),
child: MenuTheme(
data: const MenuThemeData(
style: MenuStyle(
minimumSize: MaterialStatePropertyAll<Size>(Size(300, 300)),
),
),
child: MenuBar(
children: createTestMenus(onPressed: (TestMenu menu) {}),
),
),
),
const Expanded(child: Placeholder()),
],
),
),
),
);
// Have to open a menu initially to start things going.
await tester.tap(find.text(TestMenu.mainMenu0.label));
await tester.pump();
// MenuBarTheme affects MenuBar.
expect(tester.getRect(findMenuPanels().first), equals(const Rect.fromLTRB(200.0, 0.0, 600.0, 60.0)));
expect(tester.getRect(findMenuPanels().first).size, equals(const Size(400.0, 60.0)));
// MenuTheme affects menus.
expect(tester.getRect(findMenuPanels().at(1)), equals(const Rect.fromLTRB(204.0, 54.0, 504.0, 354.0)));
expect(tester.getRect(findMenuPanels().at(1)).size, equals(const Size(300.0, 300.0)));
});
testWidgets('Material parameters are honored', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
MenuBarTheme(
data: const MenuBarThemeData(
style: MenuStyle(
backgroundColor: MaterialStatePropertyAll<Color>(Colors.red),
shadowColor: MaterialStatePropertyAll<Color>(Colors.green),
surfaceTintColor: MaterialStatePropertyAll<Color>(Colors.blue),
padding: MaterialStatePropertyAll<EdgeInsetsGeometry>(EdgeInsets.all(10)),
elevation: MaterialStatePropertyAll<double>(10),
side: MaterialStatePropertyAll<BorderSide>(BorderSide(color: Colors.redAccent)),
shape: MaterialStatePropertyAll<OutlinedBorder>(StadiumBorder()),
),
),
child: MenuTheme(
data: const MenuThemeData(
style: MenuStyle(
backgroundColor: MaterialStatePropertyAll<Color>(Colors.cyan),
shadowColor: MaterialStatePropertyAll<Color>(Colors.purple),
surfaceTintColor: MaterialStatePropertyAll<Color>(Colors.yellow),
padding: MaterialStatePropertyAll<EdgeInsetsGeometry>(EdgeInsets.all(20)),
elevation: MaterialStatePropertyAll<double>(20),
side: MaterialStatePropertyAll<BorderSide>(BorderSide(color: Colors.cyanAccent)),
shape: MaterialStatePropertyAll<OutlinedBorder>(StarBorder()),
),
),
child: MenuBar(
children: createTestMenus(onPressed: (TestMenu menu) {}),
),
),
),
const Expanded(child: Placeholder()),
],
),
),
),
);
// Have to open a menu initially to start things going.
await tester.tap(find.text(TestMenu.mainMenu0.label));
await tester.pump();
final Material menuBarMaterial = getMenuBarMaterial(tester);
final Padding menuBarPadding = getMenuBarPadding(tester);
final Material panelMaterial = getMenuMaterial(tester);
final Padding panelPadding = getMenuPadding(tester);
// MenuBarTheme affects MenuBar.
expect(menuBarMaterial.color, equals(Colors.red));
expect(menuBarMaterial.shadowColor, equals(Colors.green));
expect(menuBarMaterial.surfaceTintColor, equals(Colors.blue));
expect(menuBarMaterial.shape, equals(const StadiumBorder(side: BorderSide(color: Colors.redAccent))));
expect(menuBarPadding.padding, equals(const EdgeInsets.all(10)));
// MenuBarTheme affects menus.
expect(panelMaterial.color, equals(Colors.cyan));
expect(panelMaterial.shadowColor, equals(Colors.purple));
expect(panelMaterial.surfaceTintColor, equals(Colors.yellow));
expect(panelMaterial.shape, equals(const StarBorder(side: BorderSide(color: Colors.cyanAccent))));
expect(panelPadding.padding, equals(const EdgeInsets.all(20)));
});
testWidgets('visual density', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Material(
child: Column(
children: <Widget>[
MenuBarTheme(
data: const MenuBarThemeData(
style: MenuStyle(
visualDensity: VisualDensity(horizontal: 1.5, vertical: -1.5),
),
),
child: MenuTheme(
data: const MenuThemeData(
style: MenuStyle(
visualDensity: VisualDensity(horizontal: 0.5, vertical: -0.5),
),
),
child: MenuBar(
children: createTestMenus(onPressed: (TestMenu menu) {}),
),
),
),
const Expanded(child: Placeholder()),
],
),
),
),
);
await tester.pump();
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(228.0, 0.0, 572.0, 48.0)));
// Open and make sure things are the right size.
await tester.tap(find.text(TestMenu.mainMenu1.label));
await tester.pump();
expect(tester.getRect(find.byType(MenuBar)), equals(const Rect.fromLTRB(228.0, 0.0, 572.0, 48.0)));
expect(
tester.getRect(find.text(TestMenu.subMenu10.label)),
equals(const Rect.fromLTRB(366.0, 68.0, 520.0, 82.0)),
);
expect(
tester.getRect(find.ancestor(of: find.text(TestMenu.subMenu10.label), matching: find.byType(Material)).at(1)),
equals(const Rect.fromLTRB(346.0, 48.0, 579.0, 186.0)),
);
});
});
}
List<Widget> createTestMenus({
void Function(TestMenu)? onPressed,
void Function(TestMenu)? onOpen,
void Function(TestMenu)? onClose,
Map<TestMenu, MenuSerializableShortcut> shortcuts = const <TestMenu, MenuSerializableShortcut>{},
bool includeStandard = false,
bool includeExtraGroups = false,
}) {
final List<Widget> result = <Widget>[
SubmenuButton(
onOpen: onOpen != null ? () => onOpen(TestMenu.mainMenu0) : null,
onClose: onClose != null ? () => onClose(TestMenu.mainMenu0) : null,
menuChildren: <Widget>[
MenuItemButton(
onPressed: onPressed != null ? () => onPressed(TestMenu.subMenu00) : null,
shortcut: shortcuts[TestMenu.subMenu00],
child: Text(TestMenu.subMenu00.label),
),
MenuItemButton(
onPressed: onPressed != null ? () => onPressed(TestMenu.subMenu01) : null,
shortcut: shortcuts[TestMenu.subMenu01],
child: Text(TestMenu.subMenu01.label),
),
MenuItemButton(
onPressed: onPressed != null ? () => onPressed(TestMenu.subMenu02) : null,
shortcut: shortcuts[TestMenu.subMenu02],
child: Text(TestMenu.subMenu02.label),
),
],
child: Text(TestMenu.mainMenu0.label),
),
SubmenuButton(
onOpen: onOpen != null ? () => onOpen(TestMenu.mainMenu1) : null,
onClose: onClose != null ? () => onClose(TestMenu.mainMenu1) : null,
menuChildren: <Widget>[
MenuItemButton(
onPressed: onPressed != null ? () => onPressed(TestMenu.subMenu10) : null,
shortcut: shortcuts[TestMenu.subMenu10],
child: Text(TestMenu.subMenu10.label),
),
SubmenuButton(
onOpen: onOpen != null ? () => onOpen(TestMenu.subMenu11) : null,
onClose: onClose != null ? () => onClose(TestMenu.subMenu11) : null,
menuChildren: <Widget>[
MenuItemButton(
key: UniqueKey(),
onPressed: onPressed != null ? () => onPressed(TestMenu.subSubMenu110) : null,
shortcut: shortcuts[TestMenu.subSubMenu110],
child: Text(TestMenu.subSubMenu110.label),
),
MenuItemButton(
onPressed: onPressed != null ? () => onPressed(TestMenu.subSubMenu111) : null,
shortcut: shortcuts[TestMenu.subSubMenu111],
child: Text(TestMenu.subSubMenu111.label),
),
MenuItemButton(
onPressed: onPressed != null ? () => onPressed(TestMenu.subSubMenu112) : null,
shortcut: shortcuts[TestMenu.subSubMenu112],
child: Text(TestMenu.subSubMenu112.label),
),
MenuItemButton(
onPressed: onPressed != null ? () => onPressed(TestMenu.subSubMenu113) : null,
shortcut: shortcuts[TestMenu.subSubMenu113],
child: Text(TestMenu.subSubMenu113.label),
),
],
child: Text(TestMenu.subMenu11.label),
),
MenuItemButton(
onPressed: onPressed != null ? () => onPressed(TestMenu.subMenu12) : null,
shortcut: shortcuts[TestMenu.subMenu12],
child: Text(TestMenu.subMenu12.label),
),
],
child: Text(TestMenu.mainMenu1.label),
),
SubmenuButton(
onOpen: onOpen != null ? () => onOpen(TestMenu.mainMenu2) : null,
onClose: onClose != null ? () => onClose(TestMenu.mainMenu2) : null,
menuChildren: <Widget>[
MenuItemButton(
// Always disabled.
shortcut: shortcuts[TestMenu.subMenu20],
child: Text(TestMenu.subMenu20.label),
),
],
child: Text(TestMenu.mainMenu2.label),
),
if (includeExtraGroups)
SubmenuButton(
onOpen: onOpen != null ? () => onOpen(TestMenu.mainMenu3) : null,
onClose: onClose != null ? () => onClose(TestMenu.mainMenu3) : null,
menuChildren: <Widget>[
MenuItemButton(
// Always disabled.
shortcut: shortcuts[TestMenu.subMenu30],
// Always disabled.
child: Text(TestMenu.subMenu30.label),
),
],
child: Text(TestMenu.mainMenu3.label),
),
if (includeExtraGroups)
SubmenuButton(
onOpen: onOpen != null ? () => onOpen(TestMenu.mainMenu4) : null,
onClose: onClose != null ? () => onClose(TestMenu.mainMenu4) : null,
menuChildren: <Widget>[
MenuItemButton(
// Always disabled.
shortcut: shortcuts[TestMenu.subMenu40],
// Always disabled.
child: Text(TestMenu.subMenu40.label),
),
MenuItemButton(
// Always disabled.
shortcut: shortcuts[TestMenu.subMenu41],
// Always disabled.
child: Text(TestMenu.subMenu41.label),
),
MenuItemButton(
// Always disabled.
shortcut: shortcuts[TestMenu.subMenu42],
// Always disabled.
child: Text(TestMenu.subMenu42.label),
),
],
child: Text(TestMenu.mainMenu4.label),
),
];
return result;
}
enum TestMenu {
mainMenu0('Menu 0'),
mainMenu1('Menu 1'),
mainMenu2('Menu 2'),
mainMenu3('Menu 3'),
mainMenu4('Menu 4'),
subMenu00('Sub Menu 00'),
subMenu01('Sub Menu 01'),
subMenu02('Sub Menu 02'),
subMenu10('Sub Menu 10'),
subMenu11('Sub Menu 11'),
subMenu12('Sub Menu 12'),
subMenu20('Sub Menu 20'),
subMenu30('Sub Menu 30'),
subMenu40('Sub Menu 40'),
subMenu41('Sub Menu 41'),
subMenu42('Sub Menu 42'),
subSubMenu110('Sub Sub Menu 110'),
subSubMenu111('Sub Sub Menu 111'),
subSubMenu112('Sub Sub Menu 112'),
subSubMenu113('Sub Sub Menu 113');
const TestMenu(this.label);
final String label;
}
| flutter/packages/flutter/test/material/menu_style_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/menu_style_test.dart",
"repo_id": "flutter",
"token_count": 8257
} | 665 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' show DisplayFeature, DisplayFeatureState, DisplayFeatureType, SemanticsFlag;
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';
import 'feedback_tester.dart';
void main() {
testWidgets('Navigator.push works within a PopupMenuButton', (WidgetTester tester) async {
final Key targetKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
routes: <String, WidgetBuilder>{
'/next': (BuildContext context) {
return const Text('Next');
},
},
home: Material(
child: Center(
child: Builder(
key: targetKey,
builder: (BuildContext context) {
return PopupMenuButton<int>(
onSelected: (int value) {
Navigator.pushNamed(context, '/next');
},
itemBuilder: (BuildContext context) {
return <PopupMenuItem<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('One'),
),
];
},
);
},
),
),
),
),
);
await tester.tap(find.byKey(targetKey));
await tester.pump();
await tester.pump(const Duration(seconds: 1)); // finish the menu animation
expect(find.text('One'), findsOneWidget);
expect(find.text('Next'), findsNothing);
await tester.tap(find.text('One'));
await tester.pump(); // return the future
await tester.pump(); // start the navigation
await tester.pump(const Duration(seconds: 1)); // end the navigation
expect(find.text('One'), findsNothing);
expect(find.text('Next'), findsOneWidget);
});
testWidgets('PopupMenuButton calls onOpened callback when the menu is opened', (WidgetTester tester) async {
int opens = 0;
late BuildContext popupContext;
final Key noItemsKey = UniqueKey();
final Key noCallbackKey = UniqueKey();
final Key withCallbackKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
PopupMenuButton<int>(
key: noItemsKey,
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<int>>[];
},
onOpened: () => opens++,
),
PopupMenuButton<int>(
key: noCallbackKey,
itemBuilder: (BuildContext context) {
popupContext = context;
return <PopupMenuEntry<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('Tap me please!'),
),
];
},
),
PopupMenuButton<int>(
key: withCallbackKey,
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('Tap me, too!'),
),
];
},
onOpened: () => opens++,
),
],
),
),
),
);
// Make sure callback is not called when the menu is not shown
await tester.tap(find.byKey(noItemsKey));
await tester.pump();
expect(opens, equals(0));
// Make sure everything works if no callback is provided
await tester.tap(find.byKey(noCallbackKey));
await tester.pump();
expect(opens, equals(0));
// Close the opened menu
Navigator.of(popupContext).pop();
await tester.pump();
// Make sure callback is called when the button is tapped
await tester.tap(find.byKey(withCallbackKey));
await tester.pump();
expect(opens, equals(1));
});
testWidgets('PopupMenuButton calls onCanceled callback when an item is not selected', (WidgetTester tester) async {
int cancels = 0;
late BuildContext popupContext;
final Key noCallbackKey = UniqueKey();
final Key withCallbackKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
PopupMenuButton<int>(
key: noCallbackKey,
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('Tap me please!'),
),
];
},
),
PopupMenuButton<int>(
key: withCallbackKey,
onCanceled: () => cancels++,
itemBuilder: (BuildContext context) {
popupContext = context;
return <PopupMenuEntry<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('Tap me, too!'),
),
];
},
),
],
),
),
),
);
// Make sure everything works if no callback is provided
await tester.tap(find.byKey(noCallbackKey));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
await tester.tapAt(Offset.zero);
await tester.pump();
expect(cancels, equals(0));
// Make sure callback is called when a non-selection tap occurs
await tester.tap(find.byKey(withCallbackKey));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
await tester.tapAt(Offset.zero);
await tester.pump();
expect(cancels, equals(1));
// Make sure callback is called when back navigation occurs
await tester.tap(find.byKey(withCallbackKey));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
Navigator.of(popupContext).pop();
await tester.pump();
expect(cancels, equals(2));
});
testWidgets('Disabled PopupMenuButton will not call itemBuilder, onOpened, onSelected or onCanceled', (WidgetTester tester) async {
final GlobalKey popupButtonKey = GlobalKey();
bool itemBuilderCalled = false;
bool onOpenedCalled = false;
bool onSelectedCalled = false;
bool onCanceledCalled = false;
Widget buildApp({bool directional = false}) {
return MaterialApp(
home: Builder(builder: (BuildContext context) {
return MediaQuery(
data: MediaQuery.of(context).copyWith(
navigationMode: NavigationMode.directional,
),
child: Material(
child: Column(
children: <Widget>[
PopupMenuButton<int>(
enabled: false,
child: Text('Tap Me', key: popupButtonKey),
itemBuilder: (BuildContext context) {
itemBuilderCalled = true;
return <PopupMenuEntry<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('Tap me please!'),
),
];
},
onOpened: ()=> onOpenedCalled = true,
onSelected: (int selected) => onSelectedCalled = true,
onCanceled: () => onCanceledCalled = true,
),
],
),
),
);
}),
);
}
await tester.pumpWidget(buildApp());
// Try to bring up the popup menu and select the first item from it
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
expect(itemBuilderCalled, isFalse);
expect(onOpenedCalled, isFalse);
expect(onSelectedCalled, isFalse);
// Try to bring up the popup menu and tap outside it to cancel the menu
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
await tester.tapAt(Offset.zero);
await tester.pumpAndSettle();
expect(itemBuilderCalled, isFalse);
expect(onOpenedCalled, isFalse);
expect(onCanceledCalled, isFalse);
// Test again, with directional navigation mode and after focusing the button.
await tester.pumpWidget(buildApp(directional: true));
// Try to bring up the popup menu and select the first item from it
Focus.of(popupButtonKey.currentContext!).requestFocus();
await tester.pumpAndSettle();
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
expect(itemBuilderCalled, isFalse);
expect(onOpenedCalled, isFalse);
expect(onSelectedCalled, isFalse);
// Try to bring up the popup menu and tap outside it to cancel the menu
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
await tester.tapAt(Offset.zero);
await tester.pumpAndSettle();
expect(itemBuilderCalled, isFalse);
expect(onOpenedCalled, isFalse);
expect(onCanceledCalled, isFalse);
});
testWidgets('disabled PopupMenuButton is not focusable', (WidgetTester tester) async {
final Key popupButtonKey = UniqueKey();
final GlobalKey childKey = GlobalKey();
bool itemBuilderCalled = false;
bool onOpenedCalled = false;
bool onSelectedCalled = false;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
PopupMenuButton<int>(
key: popupButtonKey,
enabled: false,
child: Container(key: childKey),
itemBuilder: (BuildContext context) {
itemBuilderCalled = true;
return <PopupMenuEntry<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('Tap me please!'),
),
];
},
onOpened: () => onOpenedCalled = true,
onSelected: (int selected) => onSelectedCalled = true,
),
],
),
),
),
);
Focus.of(childKey.currentContext!).requestFocus();
await tester.pump();
expect(Focus.of(childKey.currentContext!).hasPrimaryFocus, isFalse);
expect(itemBuilderCalled, isFalse);
expect(onOpenedCalled, isFalse);
expect(onSelectedCalled, isFalse);
});
testWidgets('Disabled PopupMenuButton is focusable with directional navigation', (WidgetTester tester) async {
final Key popupButtonKey = UniqueKey();
final GlobalKey childKey = GlobalKey();
await tester.pumpWidget(
MaterialApp(
home: Builder(builder: (BuildContext context) {
return MediaQuery(
data: MediaQuery.of(context).copyWith(
navigationMode: NavigationMode.directional,
),
child: Material(
child: Column(
children: <Widget>[
PopupMenuButton<int>(
key: popupButtonKey,
enabled: false,
child: Container(key: childKey),
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('Tap me please!'),
),
];
},
onSelected: (int selected) {},
),
],
),
),
);
}),
),
);
Focus.of(childKey.currentContext!).requestFocus();
await tester.pump();
expect(Focus.of(childKey.currentContext!).hasPrimaryFocus, isTrue);
});
testWidgets('PopupMenuItem onTap callback is called when defined', (WidgetTester tester) async {
final List<int> menuItemTapCounters = <int>[0, 0];
await tester.pumpWidget(
TestApp(
textDirection: TextDirection.ltr,
child: Material(
child: RepaintBoundary(
child: PopupMenuButton<void>(
child: const Text('Actions'),
itemBuilder: (BuildContext context) => <PopupMenuItem<void>>[
PopupMenuItem<void>(
child: const Text('First option'),
onTap: () {
menuItemTapCounters[0] += 1;
},
),
PopupMenuItem<void>(
child: const Text('Second option'),
onTap: () {
menuItemTapCounters[1] += 1;
},
),
const PopupMenuItem<void>(
child: Text('Option without onTap'),
),
],
),
),
),
),
);
// Tap the first time
await tester.tap(find.text('Actions'));
await tester.pumpAndSettle();
await tester.tap(find.text('First option'));
await tester.pumpAndSettle();
expect(menuItemTapCounters, <int>[1, 0]);
// Tap the item again
await tester.tap(find.text('Actions'));
await tester.pumpAndSettle();
await tester.tap(find.text('First option'));
await tester.pumpAndSettle();
expect(menuItemTapCounters, <int>[2, 0]);
// Tap a different item
await tester.tap(find.text('Actions'));
await tester.pumpAndSettle();
await tester.tap(find.text('Second option'));
await tester.pumpAndSettle();
expect(menuItemTapCounters, <int>[2, 1]);
// Tap an item without onTap
await tester.tap(find.text('Actions'));
await tester.pumpAndSettle();
await tester.tap(find.text('Option without onTap'));
await tester.pumpAndSettle();
expect(menuItemTapCounters, <int>[2, 1]);
});
testWidgets('PopupMenuItem can have both onTap and value', (WidgetTester tester) async {
final List<int> menuItemTapCounters = <int>[0, 0];
String? selected;
await tester.pumpWidget(
TestApp(
textDirection: TextDirection.ltr,
child: Material(
child: RepaintBoundary(
child: PopupMenuButton<String>(
child: const Text('Actions'),
onSelected: (String value) { selected = value; },
itemBuilder: (BuildContext context) => <PopupMenuItem<String>>[
PopupMenuItem<String>(
value: 'first',
child: const Text('First option'),
onTap: () {
menuItemTapCounters[0] += 1;
},
),
PopupMenuItem<String>(
value: 'second',
child: const Text('Second option'),
onTap: () {
menuItemTapCounters[1] += 1;
},
),
const PopupMenuItem<String>(
value: 'third',
child: Text('Option without onTap'),
),
],
),
),
),
),
);
// Tap the first item
await tester.tap(find.text('Actions'));
await tester.pumpAndSettle();
await tester.tap(find.text('First option'));
await tester.pumpAndSettle();
expect(menuItemTapCounters, <int>[1, 0]);
expect(selected, 'first');
// Tap the item again
await tester.tap(find.text('Actions'));
await tester.pumpAndSettle();
await tester.tap(find.text('First option'));
await tester.pumpAndSettle();
expect(menuItemTapCounters, <int>[2, 0]);
expect(selected, 'first');
// Tap a different item
await tester.tap(find.text('Actions'));
await tester.pumpAndSettle();
await tester.tap(find.text('Second option'));
await tester.pumpAndSettle();
expect(menuItemTapCounters, <int>[2, 1]);
expect(selected, 'second');
// Tap an item without onTap
await tester.tap(find.text('Actions'));
await tester.pumpAndSettle();
await tester.tap(find.text('Option without onTap'));
await tester.pumpAndSettle();
expect(menuItemTapCounters, <int>[2, 1]);
expect(selected, 'third');
});
testWidgets('PopupMenuItem is only focusable when enabled', (WidgetTester tester) async {
final Key popupButtonKey = UniqueKey();
final GlobalKey childKey = GlobalKey();
bool itemBuilderCalled = false;
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
PopupMenuButton<int>(
key: popupButtonKey,
itemBuilder: (BuildContext context) {
itemBuilderCalled = true;
return <PopupMenuEntry<int>>[
PopupMenuItem<int>(
value: 1,
child: Text('Tap me please!', key: childKey),
),
];
},
),
],
),
),
),
);
// Open the popup to build and show the menu contents.
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
final FocusNode childNode = Focus.of(childKey.currentContext!);
// Now that the contents are shown, request focus on the child text.
childNode.requestFocus();
await tester.pumpAndSettle();
expect(itemBuilderCalled, isTrue);
// Make sure that the focus went where we expected it to.
expect(childNode.hasPrimaryFocus, isTrue);
itemBuilderCalled = false;
// Close the popup.
await tester.tap(find.byKey(popupButtonKey), warnIfMissed: false);
await tester.pumpAndSettle();
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
PopupMenuButton<int>(
key: popupButtonKey,
itemBuilder: (BuildContext context) {
itemBuilderCalled = true;
return <PopupMenuEntry<int>>[
PopupMenuItem<int>(
enabled: false,
value: 1,
child: Text('Tap me please!', key: childKey),
),
];
},
),
],
),
),
),
);
await tester.pumpAndSettle();
// Open the popup again to rebuild the contents with enabled == false.
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
expect(itemBuilderCalled, isTrue);
expect(Focus.of(childKey.currentContext!).hasPrimaryFocus, isFalse);
});
testWidgets('PopupMenuButton is horizontal on iOS', (WidgetTester tester) async {
Widget build(TargetPlatform platform) {
debugDefaultTargetPlatformOverride = platform;
return MaterialApp(
home: Scaffold(
appBar: AppBar(
actions: <Widget>[
PopupMenuButton<int>(
itemBuilder: (BuildContext context) {
return <PopupMenuItem<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('One'),
),
];
},
),
],
),
),
);
}
await tester.pumpWidget(build(TargetPlatform.android));
expect(find.byIcon(Icons.more_vert), findsOneWidget);
expect(find.byIcon(Icons.more_horiz), findsNothing);
await tester.pumpWidget(build(TargetPlatform.iOS));
await tester.pumpAndSettle(); // Run theme change animation.
expect(find.byIcon(Icons.more_vert), findsNothing);
expect(find.byIcon(Icons.more_horiz), findsOneWidget);
await tester.pumpWidget(build(TargetPlatform.macOS));
await tester.pumpAndSettle(); // Run theme change animation.
expect(find.byIcon(Icons.more_vert), findsNothing);
expect(find.byIcon(Icons.more_horiz), findsOneWidget);
debugDefaultTargetPlatformOverride = null;
});
group('PopupMenuButton with Icon', () {
// Helper function to create simple and valid popup menus.
List<PopupMenuItem<int>> simplePopupMenuItemBuilder(BuildContext context) {
return <PopupMenuItem<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('1'),
),
];
}
testWidgets('PopupMenuButton fails when given both child and icon', (WidgetTester tester) async {
expect(() {
PopupMenuButton<int>(
icon: const Icon(Icons.view_carousel),
itemBuilder: simplePopupMenuItemBuilder,
child: const Text('heyo'),
);
}, throwsAssertionError);
});
testWidgets('PopupMenuButton creates IconButton when given an icon', (WidgetTester tester) async {
final PopupMenuButton<int> button = PopupMenuButton<int>(
icon: const Icon(Icons.view_carousel),
itemBuilder: simplePopupMenuItemBuilder,
);
await tester.pumpWidget(MaterialApp(
home: Scaffold(
appBar: AppBar(
actions: <Widget>[button],
),
),
),
);
expect(find.byType(IconButton), findsOneWidget);
expect(find.byIcon(Icons.view_carousel), findsOneWidget);
});
});
testWidgets('PopupMenu positioning', (WidgetTester tester) async {
final Widget testButton = PopupMenuButton<int>(
itemBuilder: (BuildContext context) {
return <PopupMenuItem<int>>[
const PopupMenuItem<int>(value: 1, child: Text('AAA')),
const PopupMenuItem<int>(value: 2, child: Text('BBB')),
const PopupMenuItem<int>(value: 3, child: Text('CCC')),
];
},
child: const SizedBox(
height: 100.0,
width: 100.0,
child: Text('XXX'),
),
);
bool popupMenu(Widget widget) {
final String widgetType = widget.runtimeType.toString();
// TODO(mraleph): Remove the old case below.
return widgetType == '_PopupMenu<int?>' // normal case
|| widgetType == '_PopupMenu'; // for old versions of Dart that don't reify method type arguments
}
Future<void> openMenu(TextDirection textDirection, Alignment alignment) async {
return TestAsyncUtils.guard<void>(() async {
await tester.pumpWidget(Container()); // reset in case we had a menu up already
await tester.pumpWidget(TestApp(
textDirection: textDirection,
child: Align(
alignment: alignment,
child: testButton,
),
));
await tester.tap(find.text('XXX'));
await tester.pump();
});
}
Future<void> testPositioningDown(
WidgetTester tester,
TextDirection textDirection,
Alignment alignment,
TextDirection growthDirection,
Rect startRect,
) {
return TestAsyncUtils.guard<void>(() async {
await openMenu(textDirection, alignment);
Rect rect = tester.getRect(find.byWidgetPredicate(popupMenu));
expect(rect, startRect);
bool doneVertically = false;
bool doneHorizontally = false;
do {
await tester.pump(const Duration(milliseconds: 20));
final Rect newRect = tester.getRect(find.byWidgetPredicate(popupMenu));
expect(newRect.top, rect.top);
if (doneVertically) {
expect(newRect.bottom, rect.bottom);
} else {
if (newRect.bottom == rect.bottom) {
doneVertically = true;
} else {
expect(newRect.bottom, greaterThan(rect.bottom));
}
}
switch (growthDirection) {
case TextDirection.rtl:
expect(newRect.right, rect.right);
if (doneHorizontally) {
expect(newRect.left, rect.left);
} else {
if (newRect.left == rect.left) {
doneHorizontally = true;
} else {
expect(newRect.left, lessThan(rect.left));
}
}
case TextDirection.ltr:
expect(newRect.left, rect.left);
if (doneHorizontally) {
expect(newRect.right, rect.right);
} else {
if (newRect.right == rect.right) {
doneHorizontally = true;
} else {
expect(newRect.right, greaterThan(rect.right));
}
}
}
rect = newRect;
} while (tester.binding.hasScheduledFrame);
});
}
Future<void> testPositioningDownThenUp(
WidgetTester tester,
TextDirection textDirection,
Alignment alignment,
TextDirection growthDirection,
Rect startRect,
) {
return TestAsyncUtils.guard<void>(() async {
await openMenu(textDirection, alignment);
Rect rect = tester.getRect(find.byWidgetPredicate(popupMenu));
expect(rect, startRect);
int verticalStage = 0; // 0=down, 1=up, 2=done
bool doneHorizontally = false;
do {
await tester.pump(const Duration(milliseconds: 20));
final Rect newRect = tester.getRect(find.byWidgetPredicate(popupMenu));
switch (verticalStage) {
case 0:
if (newRect.top < rect.top) {
verticalStage = 1;
expect(newRect.bottom, greaterThanOrEqualTo(rect.bottom));
break;
}
expect(newRect.top, rect.top);
expect(newRect.bottom, greaterThan(rect.bottom));
case 1:
if (newRect.top == rect.top) {
verticalStage = 2;
expect(newRect.bottom, rect.bottom);
break;
}
expect(newRect.top, lessThan(rect.top));
expect(newRect.bottom, rect.bottom);
case 2:
expect(newRect.bottom, rect.bottom);
expect(newRect.top, rect.top);
default:
assert(false);
}
switch (growthDirection) {
case TextDirection.rtl:
expect(newRect.right, rect.right);
if (doneHorizontally) {
expect(newRect.left, rect.left);
} else {
if (newRect.left == rect.left) {
doneHorizontally = true;
} else {
expect(newRect.left, lessThan(rect.left));
}
}
case TextDirection.ltr:
expect(newRect.left, rect.left);
if (doneHorizontally) {
expect(newRect.right, rect.right);
} else {
if (newRect.right == rect.right) {
doneHorizontally = true;
} else {
expect(newRect.right, greaterThan(rect.right));
}
}
}
rect = newRect;
} while (tester.binding.hasScheduledFrame);
});
}
await testPositioningDown(tester, TextDirection.ltr, Alignment.topRight, TextDirection.rtl, const Rect.fromLTWH(792.0, 8.0, 0.0, 0.0));
await testPositioningDown(tester, TextDirection.rtl, Alignment.topRight, TextDirection.rtl, const Rect.fromLTWH(792.0, 8.0, 0.0, 0.0));
await testPositioningDown(tester, TextDirection.ltr, Alignment.topLeft, TextDirection.ltr, const Rect.fromLTWH(8.0, 8.0, 0.0, 0.0));
await testPositioningDown(tester, TextDirection.rtl, Alignment.topLeft, TextDirection.ltr, const Rect.fromLTWH(8.0, 8.0, 0.0, 0.0));
await testPositioningDown(tester, TextDirection.ltr, Alignment.topCenter, TextDirection.ltr, const Rect.fromLTWH(350.0, 8.0, 0.0, 0.0));
await testPositioningDown(tester, TextDirection.rtl, Alignment.topCenter, TextDirection.rtl, const Rect.fromLTWH(450.0, 8.0, 0.0, 0.0));
await testPositioningDown(tester, TextDirection.ltr, Alignment.centerRight, TextDirection.rtl, const Rect.fromLTWH(792.0, 250.0, 0.0, 0.0));
await testPositioningDown(tester, TextDirection.rtl, Alignment.centerRight, TextDirection.rtl, const Rect.fromLTWH(792.0, 250.0, 0.0, 0.0));
await testPositioningDown(tester, TextDirection.ltr, Alignment.centerLeft, TextDirection.ltr, const Rect.fromLTWH(8.0, 250.0, 0.0, 0.0));
await testPositioningDown(tester, TextDirection.rtl, Alignment.centerLeft, TextDirection.ltr, const Rect.fromLTWH(8.0, 250.0, 0.0, 0.0));
await testPositioningDown(tester, TextDirection.ltr, Alignment.center, TextDirection.ltr, const Rect.fromLTWH(350.0, 250.0, 0.0, 0.0));
await testPositioningDown(tester, TextDirection.rtl, Alignment.center, TextDirection.rtl, const Rect.fromLTWH(450.0, 250.0, 0.0, 0.0));
await testPositioningDownThenUp(tester, TextDirection.ltr, Alignment.bottomRight, TextDirection.rtl, const Rect.fromLTWH(792.0, 500.0, 0.0, 0.0));
await testPositioningDownThenUp(tester, TextDirection.rtl, Alignment.bottomRight, TextDirection.rtl, const Rect.fromLTWH(792.0, 500.0, 0.0, 0.0));
await testPositioningDownThenUp(tester, TextDirection.ltr, Alignment.bottomLeft, TextDirection.ltr, const Rect.fromLTWH(8.0, 500.0, 0.0, 0.0));
await testPositioningDownThenUp(tester, TextDirection.rtl, Alignment.bottomLeft, TextDirection.ltr, const Rect.fromLTWH(8.0, 500.0, 0.0, 0.0));
await testPositioningDownThenUp(tester, TextDirection.ltr, Alignment.bottomCenter, TextDirection.ltr, const Rect.fromLTWH(350.0, 500.0, 0.0, 0.0));
await testPositioningDownThenUp(tester, TextDirection.rtl, Alignment.bottomCenter, TextDirection.rtl, const Rect.fromLTWH(450.0, 500.0, 0.0, 0.0));
});
testWidgets('PopupMenu positioning inside nested Overlay', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
late final OverlayEntry entry;
addTearDown(() => entry..remove()..dispose());
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Example')),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Overlay(
initialEntries: <OverlayEntry>[
entry = OverlayEntry(
builder: (_) => Center(
child: PopupMenuButton<int>(
key: buttonKey,
itemBuilder: (_) => <PopupMenuItem<int>>[
const PopupMenuItem<int>(value: 1, child: Text('Item 1')),
const PopupMenuItem<int>(value: 2, child: Text('Item 2')),
],
child: const Text('Show Menu'),
),
),
),
],
),
),
),
),
);
final Finder buttonFinder = find.byKey(buttonKey);
final Finder popupFinder = find.bySemanticsLabel('Popup menu');
await tester.tap(buttonFinder);
await tester.pumpAndSettle();
final Offset buttonTopLeft = tester.getTopLeft(buttonFinder);
expect(tester.getTopLeft(popupFinder), buttonTopLeft);
});
testWidgets('PopupMenu positioning inside nested Navigator', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Example')),
body: Padding(
padding: const EdgeInsets.all(8.0),
child: Navigator(
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<dynamic>(
builder: (BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Center(
child: PopupMenuButton<int>(
key: buttonKey,
itemBuilder: (_) => <PopupMenuItem<int>>[
const PopupMenuItem<int>(value: 1, child: Text('Item 1')),
const PopupMenuItem<int>(value: 2, child: Text('Item 2')),
],
child: const Text('Show Menu'),
),
),
);
},
);
},
),
),
),
),
);
final Finder buttonFinder = find.byKey(buttonKey);
final Finder popupFinder = find.bySemanticsLabel('Popup menu');
await tester.tap(buttonFinder);
await tester.pumpAndSettle();
final Offset buttonTopLeft = tester.getTopLeft(buttonFinder);
expect(tester.getTopLeft(popupFinder), buttonTopLeft);
});
testWidgets('Popup menu with RouteSettings', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
const RouteSettings popupRoute = RouteSettings(name: '/popup');
late RouteSettings currentRouteSetting;
await tester.pumpWidget(
MaterialApp(
navigatorObservers: <NavigatorObserver>[
_ClosureNavigatorObserver(onDidChange: (Route<dynamic> newRoute) {
currentRouteSetting = newRoute.settings;
}),
],
home: Scaffold(
body: PopupMenuButton<int>(
key: buttonKey,
routeSettings: popupRoute,
itemBuilder: (_) => <PopupMenuItem<int>>[
const PopupMenuItem<int>(value: 1, child: Text('Item 1')),
const PopupMenuItem<int>(value: 2, child: Text('Item 2')),
],
child: const Text('Show Menu'),
),
),
),
);
final Finder buttonFinder = find.byKey(buttonKey);
await tester.tap(buttonFinder);
await tester.pumpAndSettle();
expect(currentRouteSetting, popupRoute);
});
testWidgets('PopupMenu positioning around display features', (WidgetTester tester) async {
final Key buttonKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: MediaQuery(
data: const MediaQueryData(
size: Size(800, 600),
displayFeatures: <DisplayFeature>[
// A 20-pixel wide vertical display feature, similar to a foldable
// with a visible hinge. Splits the display into two "virtual screens"
// and the popup menu should never overlap the display feature.
DisplayFeature(
bounds: Rect.fromLTRB(390, 0, 410, 600),
type: DisplayFeatureType.cutout,
state: DisplayFeatureState.unknown,
),
],
),
child: Scaffold(
body: Navigator(
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<dynamic>(
builder: (BuildContext context) {
return Padding(
// Position the button in the top-right of the first "virtual screen"
padding: const EdgeInsets.only(right:390.0),
child: Align(
alignment: Alignment.topRight,
child: PopupMenuButton<int>(
key: buttonKey,
itemBuilder: (_) => <PopupMenuItem<int>>[
const PopupMenuItem<int>(value: 1, child: Text('Item 1')),
const PopupMenuItem<int>(value: 2, child: Text('Item 2')),
],
child: const Text('Show Menu'),
),
),
);
},
);
},
),
),
),
),
);
final Finder buttonFinder = find.byKey(buttonKey);
final Finder popupFinder = find.bySemanticsLabel('Popup menu');
await tester.tap(buttonFinder);
await tester.pumpAndSettle();
// Since the display feature splits the display into 2 sub-screens, popup
// menu should be positioned to fit in the first virtual screen, where the
// originating button is.
// The 8 pixels is [_kMenuScreenPadding].
expect(tester.getTopRight(popupFinder), const Offset(390 - 8, 8));
});
testWidgets('PopupMenu removes MediaQuery padding', (WidgetTester tester) async {
late BuildContext popupContext;
await tester.pumpWidget(MaterialApp(
home: MediaQuery(
data: const MediaQueryData(
padding: EdgeInsets.all(50.0),
),
child: Material(
child: PopupMenuButton<int>(
itemBuilder: (BuildContext context) {
popupContext = context;
return <PopupMenuItem<int>>[
PopupMenuItem<int>(
value: 1,
child: Builder(
builder: (BuildContext context) {
popupContext = context;
return const Text('AAA');
},
),
),
];
},
child: const SizedBox(
height: 100.0,
width: 100.0,
child: Text('XXX'),
),
),
),
),
));
await tester.tap(find.text('XXX'));
await tester.pump();
expect(MediaQuery.of(popupContext).padding, EdgeInsets.zero);
});
testWidgets('Popup Menu Offset Test', (WidgetTester tester) async {
PopupMenuButton<int> buildMenuButton({Offset offset = Offset.zero}) {
return PopupMenuButton<int>(
offset: offset,
itemBuilder: (BuildContext context) {
return <PopupMenuItem<int>>[
PopupMenuItem<int>(
value: 1,
child: Builder(
builder: (BuildContext context) {
return const Text('AAA');
},
),
),
];
},
);
}
// Popup a menu without any offset.
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Material(
child: buildMenuButton(),
),
),
),
);
// Popup the menu.
await tester.tap(find.byType(IconButton));
await tester.pumpAndSettle();
// Initial state, the menu start at Offset(8.0, 8.0), the 8 pixels is edge padding when offset.dx < 8.0.
expect(tester.getTopLeft(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_PopupMenu<int?>')), const Offset(8.0, 8.0));
// Collapse the menu.
await tester.tap(find.byType(IconButton), warnIfMissed: false);
await tester.pumpAndSettle();
// Popup a new menu with Offset(50.0, 50.0).
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Material(
child: buildMenuButton(offset: const Offset(50.0, 50.0)),
),
),
),
);
await tester.tap(find.byType(IconButton));
await tester.pumpAndSettle();
// This time the menu should start at Offset(50.0, 50.0), the padding only added when offset.dx < 8.0.
expect(tester.getTopLeft(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_PopupMenu<int?>')), const Offset(50.0, 50.0));
});
testWidgets('Opened PopupMenu has correct semantics', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: PopupMenuButton<int>(
itemBuilder: (BuildContext context) {
return <PopupMenuItem<int>>[
const PopupMenuItem<int>(value: 1, child: Text('1')),
const PopupMenuItem<int>(value: 2, child: Text('2')),
const PopupMenuItem<int>(value: 3, child: Text('3')),
const PopupMenuItem<int>(value: 4, child: Text('4')),
const PopupMenuItem<int>(value: 5, child: Text('5')),
];
},
child: const SizedBox(
height: 100.0,
width: 100.0,
child: Text('XXX'),
),
),
),
),
);
await tester.tap(find.text('XXX'));
await tester.pumpAndSettle();
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.scopesRoute,
SemanticsFlag.namesRoute,
],
label: 'Popup menu',
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.hasImplicitScrolling,
],
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.hasEnabledState,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[SemanticsAction.tap],
label: '1',
textDirection: TextDirection.ltr,
),
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.hasEnabledState,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[SemanticsAction.tap],
label: '2',
textDirection: TextDirection.ltr,
),
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.hasEnabledState,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[SemanticsAction.tap],
label: '3',
textDirection: TextDirection.ltr,
),
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.hasEnabledState,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[SemanticsAction.tap],
label: '4',
textDirection: TextDirection.ltr,
),
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.hasEnabledState,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[SemanticsAction.tap],
label: '5',
textDirection: TextDirection.ltr,
),
],
),
],
),
],
),
TestSemantics(
actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss],
label: 'Dismiss menu',
textDirection: TextDirection.ltr,
),
],
),
],
),
ignoreId: true, ignoreTransform: true, ignoreRect: true,
));
semantics.dispose();
});
testWidgets('PopupMenuItem merges the semantics of its descendants', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: PopupMenuButton<int>(
itemBuilder: (BuildContext context) {
return <PopupMenuItem<int>>[
PopupMenuItem<int>(
value: 1,
child: Row(
children: <Widget>[
Semantics(
child: const Text('test1'),
),
Semantics(
child: const Text('test2'),
),
],
),
),
];
},
child: const SizedBox(
height: 100.0,
width: 100.0,
child: Text('XXX'),
),
),
),
),
);
await tester.tap(find.text('XXX'));
await tester.pumpAndSettle();
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.scopesRoute,
SemanticsFlag.namesRoute,
],
label: 'Popup menu',
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.hasImplicitScrolling,
],
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.hasEnabledState,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[SemanticsAction.tap],
label: 'test1\ntest2',
textDirection: TextDirection.ltr,
),
],
),
],
),
],
),
TestSemantics(
actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss],
label: 'Dismiss menu',
textDirection: TextDirection.ltr,
),
],
),
],
),
ignoreId: true, ignoreTransform: true, ignoreRect: true,
));
semantics.dispose();
});
testWidgets('Disabled PopupMenuItem has correct semantics', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/45044.
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
MaterialApp(
home: Material(
child: PopupMenuButton<int>(
itemBuilder: (BuildContext context) {
return <PopupMenuItem<int>>[
const PopupMenuItem<int>(value: 1, child: Text('1')),
const PopupMenuItem<int>(value: 2, enabled: false ,child: Text('2')),
const PopupMenuItem<int>(value: 3, child: Text('3')),
const PopupMenuItem<int>(value: 4, child: Text('4')),
const PopupMenuItem<int>(value: 5, child: Text('5')),
];
},
child: const SizedBox(
height: 100.0,
width: 100.0,
child: Text('XXX'),
),
),
),
),
);
await tester.tap(find.text('XXX'));
await tester.pumpAndSettle();
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.scopesRoute,
SemanticsFlag.namesRoute,
],
label: 'Popup menu',
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.hasImplicitScrolling,
],
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.hasEnabledState,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[SemanticsAction.tap],
label: '1',
textDirection: TextDirection.ltr,
),
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.hasEnabledState,
],
actions: <SemanticsAction>[],
label: '2',
textDirection: TextDirection.ltr,
),
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.hasEnabledState,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[SemanticsAction.tap],
label: '3',
textDirection: TextDirection.ltr,
),
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.hasEnabledState,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[SemanticsAction.tap],
label: '4',
textDirection: TextDirection.ltr,
),
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.isButton,
SemanticsFlag.hasEnabledState,
SemanticsFlag.isEnabled,
SemanticsFlag.isFocusable,
],
actions: <SemanticsAction>[SemanticsAction.tap],
label: '5',
textDirection: TextDirection.ltr,
),
],
),
],
),
],
),
TestSemantics(
actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.dismiss],
label: 'Dismiss menu',
textDirection: TextDirection.ltr,
),
],
),
],
),
ignoreId: true, ignoreTransform: true, ignoreRect: true,
));
semantics.dispose();
});
testWidgets('PopupMenuButton PopupMenuDivider', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/27072
late String selectedValue;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: PopupMenuButton<String>(
onSelected: (String result) {
selectedValue = result;
},
initialValue: '1',
child: const Text('Menu Button'),
itemBuilder: (BuildContext context) => <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
value: '1',
child: Text('1'),
),
const PopupMenuDivider(),
const PopupMenuItem<String>(
value: '2',
child: Text('2'),
),
],
),
),
),
),
);
await tester.tap(find.text('Menu Button'));
await tester.pumpAndSettle();
expect(find.text('1'), findsOneWidget);
expect(find.byType(PopupMenuDivider), findsOneWidget);
expect(find.text('2'), findsOneWidget);
await tester.tap(find.text('1'));
await tester.pumpAndSettle();
expect(selectedValue, '1');
await tester.tap(find.text('Menu Button'));
await tester.pumpAndSettle();
expect(find.text('1'), findsOneWidget);
expect(find.byType(PopupMenuDivider), findsOneWidget);
expect(find.text('2'), findsOneWidget);
await tester.tap(find.text('2'));
await tester.pumpAndSettle();
expect(selectedValue, '2');
});
testWidgets('PopupMenuItem child height is a minimum, child is vertically centered', (WidgetTester tester) async {
final Key popupMenuButtonKey = UniqueKey();
final Type menuItemType = const PopupMenuItem<String>(child: Text('item')).runtimeType;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: PopupMenuButton<String>(
key: popupMenuButtonKey,
child: const Text('button'),
onSelected: (String result) { },
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<String>>[
// This menu item's height will be 48 because the default minimum height
// is 48 and the height of the text is less than 48.
const PopupMenuItem<String>(
value: '0',
child: Text('Item 0'),
),
// This menu item's height parameter specifies its minimum height. The
// overall height of the menu item will be 50 because the child's
// height 40, is less than 50.
const PopupMenuItem<String>(
height: 50,
value: '1',
child: SizedBox(
height: 40,
child: Text('Item 1'),
),
),
// This menu item's height parameter specifies its minimum height, so the
// overall height of the menu item will be 75.
const PopupMenuItem<String>(
height: 75,
value: '2',
child: SizedBox(
child: Text('Item 2'),
),
),
// This menu item's height will be 100.
const PopupMenuItem<String>(
value: '3',
child: SizedBox(
height: 100,
child: Text('Item 3'),
),
),
];
},
),
),
),
),
);
// Show the menu
await tester.tap(find.byKey(popupMenuButtonKey));
await tester.pumpAndSettle();
// The menu items and their InkWells should have the expected vertical size
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 0')).height, 48);
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 1')).height, 50);
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 2')).height, 75);
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 3')).height, 100);
expect(tester.getSize(find.widgetWithText(InkWell, 'Item 0')).height, 48);
expect(tester.getSize(find.widgetWithText(InkWell, 'Item 1')).height, 50);
expect(tester.getSize(find.widgetWithText(InkWell, 'Item 2')).height, 75);
expect(tester.getSize(find.widgetWithText(InkWell, 'Item 3')).height, 100);
// Menu item children which whose height is less than the PopupMenuItem
// are vertically centered.
expect(
tester.getRect(find.widgetWithText(menuItemType, 'Item 0')).center.dy,
tester.getRect(find.text('Item 0')).center.dy,
);
expect(
tester.getRect(find.widgetWithText(menuItemType, 'Item 2')).center.dy,
tester.getRect(find.text('Item 2')).center.dy,
);
});
testWidgets('Material3 - PopupMenuItem default padding', (WidgetTester tester) async {
final Key popupMenuButtonKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: true),
home: Scaffold(
body: Center(
child: PopupMenuButton<String>(
key: popupMenuButtonKey,
child: const Text('button'),
onSelected: (String result) { },
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
value: '0',
enabled: false,
child: Text('Item 0'),
),
const PopupMenuItem<String>(
value: '1',
child: Text('Item 1'),
),
];
},
),
),
),
),
);
// Show the menu.
await tester.tap(find.byKey(popupMenuButtonKey));
await tester.pumpAndSettle();
expect(tester.widget<Container>(find.widgetWithText(Container, 'Item 0')).padding, const EdgeInsets.symmetric(horizontal: 12.0));
expect(tester.widget<Container>(find.widgetWithText(Container, 'Item 1')).padding, const EdgeInsets.symmetric(horizontal: 12.0));
});
testWidgets('Material2 - PopupMenuItem default padding', (WidgetTester tester) async {
final Key popupMenuButtonKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
body: Center(
child: PopupMenuButton<String>(
key: popupMenuButtonKey,
child: const Text('button'),
onSelected: (String result) { },
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
value: '0',
enabled: false,
child: Text('Item 0'),
),
const PopupMenuItem<String>(
value: '1',
child: Text('Item 1'),
),
];
},
),
),
),
),
);
// Show the menu.
await tester.tap(find.byKey(popupMenuButtonKey));
await tester.pumpAndSettle();
expect(tester.widget<Container>(find.widgetWithText(Container, 'Item 0')).padding, const EdgeInsets.symmetric(horizontal: 16.0));
expect(tester.widget<Container>(find.widgetWithText(Container, 'Item 1')).padding, const EdgeInsets.symmetric(horizontal: 16.0));
});
testWidgets('PopupMenuItem custom padding', (WidgetTester tester) async {
final Key popupMenuButtonKey = UniqueKey();
final Type menuItemType = const PopupMenuItem<String>(child: Text('item')).runtimeType;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
body: Center(
child: PopupMenuButton<String>(
key: popupMenuButtonKey,
child: const Text('button'),
onSelected: (String result) { },
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
padding: EdgeInsets.zero,
value: '0',
child: Text('Item 0'),
),
const PopupMenuItem<String>(
padding: EdgeInsets.zero,
height: 0,
value: '0',
child: Text('Item 1'),
),
const PopupMenuItem<String>(
padding: EdgeInsets.all(20),
value: '0',
child: Text('Item 2'),
),
const PopupMenuItem<String>(
padding: EdgeInsets.all(20),
height: 100,
value: '0',
child: Text('Item 3'),
),
];
},
),
),
),
),
);
// Show the menu
await tester.tap(find.byKey(popupMenuButtonKey));
await tester.pumpAndSettle();
// The menu items and their InkWells should have the expected vertical size
// given the interactions between heights and padding.
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 0')).height, 48); // Minimum interactive height (48)
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 1')).height, 16); // Height of text (16)
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 2')).height, 56); // Padding (20.0 + 20.0) + Height of text (16) = 56
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 3')).height, 100); // Height value of 100, since child (16) + padding (40) < 100
expect(tester.widget<Container>(find.widgetWithText(Container, 'Item 0')).padding, EdgeInsets.zero);
expect(tester.widget<Container>(find.widgetWithText(Container, 'Item 1')).padding, EdgeInsets.zero);
expect(tester.widget<Container>(find.widgetWithText(Container, 'Item 2')).padding, const EdgeInsets.all(20));
expect(tester.widget<Container>(find.widgetWithText(Container, 'Item 3')).padding, const EdgeInsets.all(20));
});
testWidgets('CheckedPopupMenuItem child height is a minimum, child is vertically centered', (WidgetTester tester) async {
final Key popupMenuButtonKey = UniqueKey();
final Type menuItemType = const CheckedPopupMenuItem<String>(child: Text('item')).runtimeType;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: PopupMenuButton<String>(
key: popupMenuButtonKey,
child: const Text('button'),
onSelected: (String result) { },
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<String>>[
// This menu item's height will be 56.0 because the default minimum height
// is 48, but the contents of PopupMenuItem are 56.0 tall.
const CheckedPopupMenuItem<String>(
checked: true,
value: '0',
child: Text('Item 0'),
),
// This menu item's height parameter specifies its minimum height. The
// overall height of the menu item will be 60 because the child's
// height 56, is less than 60.
const CheckedPopupMenuItem<String>(
checked: true,
height: 60,
value: '1',
child: SizedBox(
height: 40,
child: Text('Item 1'),
),
),
// This menu item's height parameter specifies its minimum height, so the
// overall height of the menu item will be 75.
const CheckedPopupMenuItem<String>(
checked: true,
height: 75,
value: '2',
child: SizedBox(
child: Text('Item 2'),
),
),
// This menu item's height will be 100.
const CheckedPopupMenuItem<String>(
checked: true,
height: 100,
value: '3',
child: SizedBox(
child: Text('Item 3'),
),
),
];
},
),
),
),
),
);
// Show the menu
await tester.tap(find.byKey(popupMenuButtonKey));
await tester.pumpAndSettle();
// The menu items and their InkWells should have the expected vertical size
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 0')).height, 56);
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 1')).height, 60);
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 2')).height, 75);
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 3')).height, 100);
// We evaluate the InkWell at the first index because that is the ListTile's
// InkWell, which wins in the gesture arena over the child's InkWell and
// is the one of interest.
expect(tester.getSize(find.widgetWithText(InkWell, 'Item 0').at(1)).height, 56);
expect(tester.getSize(find.widgetWithText(InkWell, 'Item 1').at(1)).height, 60);
expect(tester.getSize(find.widgetWithText(InkWell, 'Item 2').at(1)).height, 75);
expect(tester.getSize(find.widgetWithText(InkWell, 'Item 3').at(1)).height, 100);
// Menu item children which whose height is less than the PopupMenuItem
// are vertically centered.
expect(
tester.getRect(find.widgetWithText(menuItemType, 'Item 0')).center.dy,
tester.getRect(find.text('Item 0')).center.dy,
);
expect(
tester.getRect(find.widgetWithText(menuItemType, 'Item 2')).center.dy,
tester.getRect(find.text('Item 2')).center.dy,
);
});
testWidgets('CheckedPopupMenuItem custom padding', (WidgetTester tester) async {
final Key popupMenuButtonKey = UniqueKey();
final Type menuItemType = const CheckedPopupMenuItem<String>(child: Text('item')).runtimeType;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: PopupMenuButton<String>(
key: popupMenuButtonKey,
child: const Text('button'),
onSelected: (String result) { },
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<String>>[
const CheckedPopupMenuItem<String>(
padding: EdgeInsets.zero,
value: '0',
child: Text('Item 0'),
),
const CheckedPopupMenuItem<String>(
padding: EdgeInsets.zero,
height: 0,
value: '0',
child: Text('Item 1'),
),
const CheckedPopupMenuItem<String>(
padding: EdgeInsets.all(20),
value: '0',
child: Text('Item 2'),
),
const CheckedPopupMenuItem<String>(
padding: EdgeInsets.all(20),
height: 100,
value: '0',
child: Text('Item 3'),
),
];
},
),
),
),
),
);
// Show the menu
await tester.tap(find.byKey(popupMenuButtonKey));
await tester.pumpAndSettle();
// The menu items and their InkWells should have the expected vertical size
// given the interactions between heights and padding.
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 0')).height, 56); // Minimum ListTile height (56)
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 1')).height, 56); // Minimum ListTile height (56)
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 2')).height, 96); // Padding (20.0 + 20.0) + Height of ListTile (56) = 96
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 3')).height, 100); // Height value of 100, since child (56) + padding (40) < 100
expect(tester.widget<Container>(find.widgetWithText(Container, 'Item 0')).padding, EdgeInsets.zero);
expect(tester.widget<Container>(find.widgetWithText(Container, 'Item 1')).padding, EdgeInsets.zero);
expect(tester.widget<Container>(find.widgetWithText(Container, 'Item 2')).padding, const EdgeInsets.all(20));
expect(tester.widget<Container>(find.widgetWithText(Container, 'Item 3')).padding, const EdgeInsets.all(20));
});
testWidgets('Update PopupMenuItem layout while the menu is visible', (WidgetTester tester) async {
final Key popupMenuButtonKey = UniqueKey();
final Type menuItemType = const PopupMenuItem<String>(child: Text('item')).runtimeType;
Widget buildFrame({
TextDirection textDirection = TextDirection.ltr,
double fontSize = 24,
}) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
builder: (BuildContext context, Widget? child) {
return Directionality(
textDirection: textDirection,
child: PopupMenuTheme(
data: PopupMenuTheme.of(context).copyWith(
textStyle: Theme.of(context).textTheme.titleMedium!.copyWith(fontSize: fontSize),
),
child: child!,
),
);
},
home: Scaffold(
body: PopupMenuButton<String>(
key: popupMenuButtonKey,
child: const Text('button'),
onSelected: (String result) { },
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
value: '0',
child: Text('Item 0'),
),
const PopupMenuItem<String>(
value: '1',
child: Text('Item 1'),
),
];
},
),
),
);
}
// Show the menu
await tester.pumpWidget(buildFrame());
await tester.tap(find.byKey(popupMenuButtonKey));
await tester.pumpAndSettle();
// The menu items should have their default heights and horizontal alignment.
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 0')).height, 48);
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 1')).height, 48);
expect(tester.getTopLeft(find.text('Item 0')).dx, 24);
expect(tester.getTopLeft(find.text('Item 1')).dx, 24);
// While the menu is up, change its font size to 64 (default is 16).
await tester.pumpWidget(buildFrame(fontSize: 64));
await tester.pumpAndSettle(); // Theme changes are animated.
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 0')).height, 128);
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 1')).height, 128);
expect(tester.getSize(find.text('Item 0')).height, 128);
expect(tester.getSize(find.text('Item 1')).height, 128);
expect(tester.getTopLeft(find.text('Item 0')).dx, 24);
expect(tester.getTopLeft(find.text('Item 1')).dx, 24);
// While the menu is up, change the textDirection to rtl. Now menu items
// will be aligned right.
await tester.pumpWidget(buildFrame(textDirection: TextDirection.rtl));
await tester.pumpAndSettle(); // Theme changes are animated.
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 0')).height, 48);
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 1')).height, 48);
expect(tester.getTopLeft(find.text('Item 0')).dx, 72);
expect(tester.getTopLeft(find.text('Item 1')).dx, 72);
});
test("PopupMenuButton's child and icon properties cannot be simultaneously defined", () {
expect(() {
PopupMenuButton<int>(
itemBuilder: (BuildContext context) => <PopupMenuItem<int>>[],
icon: const Icon(Icons.error),
child: Container(),
);
}, throwsAssertionError);
});
testWidgets('PopupMenuButton default tooltip', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
// Default Tooltip should be present when [PopupMenuButton.icon]
// and [PopupMenuButton.child] are undefined.
PopupMenuButton<int>(
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('Tap me please!'),
),
];
},
),
// Default Tooltip should be present when
// [PopupMenuButton.child] is defined.
PopupMenuButton<int>(
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('Tap me please!'),
),
];
},
child: const Text('Test text'),
),
// Default Tooltip should be present when
// [PopupMenuButton.icon] is defined.
PopupMenuButton<int>(
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('Tap me please!'),
),
];
},
icon: const Icon(Icons.check),
),
],
),
),
),
);
// The default tooltip is defined as [MaterialLocalizations.showMenuTooltip]
// and it is used when no tooltip is provided.
expect(find.byType(Tooltip), findsNWidgets(3));
expect(find.byTooltip(const DefaultMaterialLocalizations().showMenuTooltip), findsNWidgets(3));
});
testWidgets('PopupMenuButton custom tooltip', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
// Tooltip should work when [PopupMenuButton.icon]
// and [PopupMenuButton.child] are undefined.
PopupMenuButton<int>(
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('Tap me please!'),
),
];
},
tooltip: 'Test tooltip',
),
// Tooltip should work when
// [PopupMenuButton.child] is defined.
PopupMenuButton<int>(
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('Tap me please!'),
),
];
},
tooltip: 'Test tooltip',
child: const Text('Test text'),
),
// Tooltip should work when
// [PopupMenuButton.icon] is defined.
PopupMenuButton<int>(
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('Tap me please!'),
),
];
},
tooltip: 'Test tooltip',
icon: const Icon(Icons.check),
),
],
),
),
),
);
expect(find.byType(Tooltip), findsNWidgets(3));
expect(find.byTooltip('Test tooltip'), findsNWidgets(3));
});
testWidgets('Allow Widget for PopupMenuButton.icon', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Material(
child: PopupMenuButton<int>(
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('Tap me please!'),
),
];
},
tooltip: 'Test tooltip',
icon: const Text('PopupMenuButton icon'),
),
),
),
);
expect(find.text('PopupMenuButton icon'), findsOneWidget);
});
testWidgets('showMenu uses nested navigator by default', (WidgetTester tester) async {
final MenuObserver rootObserver = MenuObserver();
final MenuObserver nestedObserver = MenuObserver();
await tester.pumpWidget(MaterialApp(
navigatorObservers: <NavigatorObserver>[rootObserver],
home: Navigator(
observers: <NavigatorObserver>[nestedObserver],
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<dynamic>(
builder: (BuildContext context) {
return ElevatedButton(
onPressed: () {
showMenu<int>(
context: context,
position: RelativeRect.fill,
items: <PopupMenuItem<int>>[
const PopupMenuItem<int>(
value: 1, child: Text('1'),
),
],
);
},
child: const Text('Show Menu'),
);
},
);
},
),
));
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
expect(rootObserver.menuCount, 0);
expect(nestedObserver.menuCount, 1);
});
testWidgets('showMenu uses root navigator if useRootNavigator is true', (WidgetTester tester) async {
final MenuObserver rootObserver = MenuObserver();
final MenuObserver nestedObserver = MenuObserver();
await tester.pumpWidget(MaterialApp(
navigatorObservers: <NavigatorObserver>[rootObserver],
home: Navigator(
observers: <NavigatorObserver>[nestedObserver],
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<dynamic>(
builder: (BuildContext context) {
return ElevatedButton(
onPressed: () {
showMenu<int>(
context: context,
useRootNavigator: true,
position: RelativeRect.fill,
items: <PopupMenuItem<int>>[
const PopupMenuItem<int>(
value: 1, child: Text('1'),
),
],
);
},
child: const Text('Show Menu'),
);
},
);
},
),
));
// Open the dialog.
await tester.tap(find.byType(ElevatedButton));
expect(rootObserver.menuCount, 1);
expect(nestedObserver.menuCount, 0);
});
testWidgets('PopupMenuButton calling showButtonMenu manually', (WidgetTester tester) async {
final GlobalKey<PopupMenuButtonState<int>> globalKey = GlobalKey();
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
PopupMenuButton<int>(
key: globalKey,
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('Tap me please!'),
),
];
},
),
],
),
),
),
);
expect(find.text('Tap me please!'), findsNothing);
globalKey.currentState!.showButtonMenu();
// The PopupMenuItem will appear after an animation, hence,
// we have to first wait for the tester to settle.
await tester.pumpAndSettle();
expect(find.text('Tap me please!'), findsOneWidget);
});
testWidgets('PopupMenuItem changes mouse cursor when hovered', (WidgetTester tester) async {
const Key key = ValueKey<int>(1);
// Test PopupMenuItem() constructor
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: Material(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: PopupMenuItem<int>(
key: key,
mouseCursor: SystemMouseCursors.text,
value: 1,
child: Container(),
),
),
),
),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.byKey(key)));
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
// Test default cursor
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: Material(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: PopupMenuItem<int>(
key: key,
value: 1,
child: Container(),
),
),
),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
// Test default cursor when disabled
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: Material(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: PopupMenuItem<int>(
key: key,
value: 1,
enabled: false,
child: Container(),
),
),
),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
});
testWidgets('CheckedPopupMenuItem changes mouse cursor when hovered', (WidgetTester tester) async {
const Key key = ValueKey<int>(1);
// Test CheckedPopupMenuItem() constructor
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: Material(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: CheckedPopupMenuItem<int>(
key: key,
mouseCursor: SystemMouseCursors.text,
value: 1,
child: Container(),
),
),
),
),
),
),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.byKey(key)));
addTearDown(gesture.removePointer);
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
// Test default cursor
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: Material(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: CheckedPopupMenuItem<int>(
key: key,
value: 1,
child: Container(),
),
),
),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
// Test default cursor when disabled
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: Material(
child: MouseRegion(
cursor: SystemMouseCursors.forbidden,
child: CheckedPopupMenuItem<int>(
key: key,
value: 1,
enabled: false,
child: Container(),
),
),
),
),
),
),
);
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.basic);
});
testWidgets('PopupMenu in AppBar does not overlap with the status bar', (WidgetTester tester) async {
const List<PopupMenuItem<int>> choices = <PopupMenuItem<int>>[
PopupMenuItem<int>(value: 1, child: Text('Item 1')),
PopupMenuItem<int>(value: 2, child: Text('Item 2')),
PopupMenuItem<int>(value: 3, child: Text('Item 3')),
];
const double statusBarHeight = 24.0;
final PopupMenuItem<int> firstItem = choices[0];
int selectedValue = choices[0].value!;
await tester.pumpWidget(
MaterialApp(
builder: (BuildContext context, Widget? child) {
return MediaQuery(
data: const MediaQueryData(padding: EdgeInsets.only(top: statusBarHeight)), // status bar
child: child!,
);
},
home: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return Scaffold(
appBar: AppBar(
title: const Text('PopupMenu Test'),
actions: <Widget>[
PopupMenuButton<int>(
onSelected: (int result) {
setState(() {
selectedValue = result;
});
},
initialValue: selectedValue,
itemBuilder: (BuildContext context) {
return choices;
},
),
],
),
);
},
),
),
);
await tester.tap(find.byIcon(Icons.more_vert));
await tester.pumpAndSettle();
// Tap third item.
await tester.tap(find.text('Item 3'));
await tester.pumpAndSettle();
// Open popupMenu again.
await tester.tap(find.byIcon(Icons.more_vert));
await tester.pumpAndSettle();
// Check whether the first item is not overlapping with status bar.
expect(tester.getTopLeft(find.byWidget(firstItem)).dy, greaterThan(statusBarHeight));
});
testWidgets('Vertically long PopupMenu does not overlap with the status bar and bottom notch', (WidgetTester tester) async {
const double windowPaddingTop = 44;
const double windowPaddingBottom = 34;
await tester.pumpWidget(
MaterialApp(
builder: (BuildContext context, Widget? child) {
return MediaQuery(
data: const MediaQueryData(
padding: EdgeInsets.only(
top: windowPaddingTop,
bottom: windowPaddingBottom,
),
),
child: child!,
);
},
home: Scaffold(
appBar: AppBar(
title: const Text('PopupMenu Test'),
),
body: PopupMenuButton<int>(
child: const Text('Show Menu'),
itemBuilder: (BuildContext context) => Iterable<PopupMenuItem<int>>.generate(
20, (int i) => PopupMenuItem<int>(
value: i,
child: Text('Item $i'),
),
).toList(),
),
),
),
);
await tester.tap(find.text('Show Menu'));
await tester.pumpAndSettle();
final Offset topRightOfMenu = tester.getTopRight(find.byType(SingleChildScrollView));
final Offset bottomRightOfMenu = tester.getBottomRight(find.byType(SingleChildScrollView));
expect(topRightOfMenu.dy, windowPaddingTop + 8.0);
expect(bottomRightOfMenu.dy, 600.0 - windowPaddingBottom - 8.0); // Screen height is 600.
});
testWidgets('PopupMenu position test when have unsafe area', (WidgetTester tester) async {
final GlobalKey buttonKey = GlobalKey();
Widget buildFrame(double width, double height) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
builder: (BuildContext context, Widget? child) {
return MediaQuery(
data: const MediaQueryData(
padding: EdgeInsets.only(
top: 32.0,
bottom: 32.0,
),
),
child: child!,
);
},
home: Scaffold(
appBar: AppBar(
title: const Text('PopupMenu Test'),
actions: <Widget>[
PopupMenuButton<int>(
child: SizedBox(
key: buttonKey,
height: height,
width: width,
child: const ColoredBox(
color: Colors.pink,
),
),
itemBuilder: (BuildContext context) => <PopupMenuEntry<int>>[
const PopupMenuItem<int>(value: 1, child: Text('-1-')),
const PopupMenuItem<int>(value: 2, child: Text('-2-')),
],
),
],
),
body: Container(),
),
);
}
await tester.pumpWidget(buildFrame(20.0, 20.0));
await tester.tap(find.byKey(buttonKey));
await tester.pumpAndSettle();
final Offset button = tester.getTopRight(find.byKey(buttonKey));
expect(button, const Offset(800.0, 32.0)); // The topPadding is 32.0.
final Offset popupMenu = tester.getTopRight(find.byType(SingleChildScrollView));
// The menu should be positioned directly next to the top of the button.
// The 8.0 pixels is [_kMenuScreenPadding].
expect(popupMenu, Offset(button.dx - 8.0, button.dy + 8.0));
});
// Regression test for https://github.com/flutter/flutter/issues/82874
testWidgets('PopupMenu position test when have unsafe area - left/right padding', (WidgetTester tester) async {
final GlobalKey buttonKey = GlobalKey();
const EdgeInsets padding = EdgeInsets.only(left: 300.0, top: 32.0, right: 310.0, bottom: 64.0);
EdgeInsets? mediaQueryPadding;
Widget buildFrame(double width, double height) {
return MaterialApp(
theme: ThemeData(useMaterial3: false),
builder: (BuildContext context, Widget? child) {
return MediaQuery(
data: const MediaQueryData(
padding: padding,
),
child: child!,
);
},
home: Scaffold(
appBar: AppBar(
title: const Text('PopupMenu Test'),
actions: <Widget>[
PopupMenuButton<int>(
child: SizedBox(
key: buttonKey,
height: height,
width: width,
child: const ColoredBox(
color: Colors.pink,
),
),
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<int>>[
PopupMenuItem<int>(
value: 1,
child: Builder(
builder: (BuildContext context) {
mediaQueryPadding = MediaQuery.paddingOf(context);
return Text('-1-' * 500); // A long long text string.
},
),
),
const PopupMenuItem<int>(value: 2, child: Text('-2-')),
];
},
),
],
),
body: const SizedBox.shrink(),
),
);
}
await tester.pumpWidget(buildFrame(20.0, 20.0));
await tester.tap(find.byKey(buttonKey));
await tester.pumpAndSettle();
final Offset button = tester.getTopRight(find.byKey(buttonKey));
expect(button, Offset(800.0 - padding.right, padding.top)); // The topPadding is 32.0.
final Offset popupMenuTopRight = tester.getTopRight(find.byType(SingleChildScrollView));
// The menu should be positioned directly next to the top of the button.
// The 8.0 pixels is [_kMenuScreenPadding].
expect(popupMenuTopRight, Offset(800.0 - padding.right - 8.0, padding.top + 8.0));
final Offset popupMenuTopLeft = tester.getTopLeft(find.byType(SingleChildScrollView));
expect(popupMenuTopLeft, Offset(padding.left + 8.0, padding.top + 8.0));
final Offset popupMenuBottomLeft = tester.getBottomLeft(find.byType(SingleChildScrollView));
expect(popupMenuBottomLeft, Offset(padding.left + 8.0, 600.0 - padding.bottom - 8.0));
// The `MediaQueryData.padding` should be removed.
expect(mediaQueryPadding, EdgeInsets.zero);
});
group('feedback', () {
late FeedbackTester feedback;
setUp(() {
feedback = FeedbackTester();
});
tearDown(() {
feedback.dispose();
});
Widget buildFrame({ bool? widgetEnableFeedback, bool? themeEnableFeedback }) {
return MaterialApp(
home: Scaffold(
body: PopupMenuTheme(
data: PopupMenuThemeData(
enableFeedback: themeEnableFeedback,
),
child: PopupMenuButton<int>(
enableFeedback: widgetEnableFeedback,
child: const Text('Show Menu'),
itemBuilder: (BuildContext context) {
return <PopupMenuItem<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('One'),
),
];
},
),
),
),
);
}
testWidgets('PopupMenuButton enableFeedback works properly', (WidgetTester tester) async {
expect(feedback.clickSoundCount, 0);
expect(feedback.hapticCount, 0);
// PopupMenuButton with enabled feedback.
await tester.pumpWidget(buildFrame(widgetEnableFeedback: true));
await tester.tap(find.text('Show Menu'));
await tester.pumpAndSettle();
expect(feedback.clickSoundCount, 1);
expect(feedback.hapticCount, 0);
await tester.pumpWidget(Container());
// PopupMenuButton with disabled feedback.
await tester.pumpWidget(buildFrame(widgetEnableFeedback: false));
await tester.tap(find.text('Show Menu'));
await tester.pumpAndSettle();
expect(feedback.clickSoundCount, 1);
expect(feedback.hapticCount, 0);
await tester.pumpWidget(Container());
// PopupMenuButton with enabled feedback by default.
await tester.pumpWidget(buildFrame());
await tester.tap(find.text('Show Menu'));
await tester.pumpAndSettle();
expect(feedback.clickSoundCount, 2);
expect(feedback.hapticCount, 0);
await tester.pumpWidget(Container());
// PopupMenu with disabled feedback using PopupMenuButtonTheme.
await tester.pumpWidget(buildFrame(themeEnableFeedback: false));
await tester.tap(find.text('Show Menu'));
await tester.pumpAndSettle();
expect(feedback.clickSoundCount, 2);
expect(feedback.hapticCount, 0);
await tester.pumpWidget(Container());
// PopupMenu enableFeedback property overrides PopupMenuButtonTheme.
await tester.pumpWidget(buildFrame(widgetEnableFeedback: false,themeEnableFeedback: true));
await tester.tap(find.text('Show Menu'));
await tester.pumpAndSettle();
expect(feedback.clickSoundCount, 2);
expect(feedback.hapticCount, 0);
});
});
testWidgets('Can customize PopupMenuButton icon', (WidgetTester tester) async {
const Color iconColor = Color(0xffffff00);
const double iconSize = 29.5;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: PopupMenuButton<String>(
iconColor: iconColor,
iconSize: iconSize,
itemBuilder: (_) => <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
value: 'value',
child: Text('child'),
),
],
),
),
),
),
);
expect(_iconStyle(tester, Icons.adaptive.more)?.color, iconColor);
expect(tester.getSize(find.byIcon(Icons.adaptive.more)), const Size(iconSize, iconSize));
});
testWidgets('does not crash in small overlay', (WidgetTester tester) async {
final GlobalKey navigator = GlobalKey();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Column(
children: <Widget>[
OutlinedButton(
onPressed: () {
showMenu<void>(
context: navigator.currentContext!,
position: RelativeRect.fill,
items: const <PopupMenuItem<void>>[
PopupMenuItem<void>(child: Text('foo')),
],
);
},
child: const Text('press'),
),
SizedBox(
height: 10,
width: 10,
child: Navigator(
key: navigator,
onGenerateRoute: (RouteSettings settings) => MaterialPageRoute<void>(
builder: (BuildContext context) => Container(color: Colors.red),
),
),
),
],
),
),
),
);
await tester.tap(find.text('press'));
await tester.pumpAndSettle();
expect(find.text('foo'), findsOneWidget);
});
// Regression test for https://github.com/flutter/flutter/issues/80869
testWidgets('The menu position test in the scrollable widget', (WidgetTester tester) async {
final GlobalKey buttonKey = GlobalKey();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
child: Column(
children: <Widget>[
const SizedBox(height: 100),
PopupMenuButton<int>(
child: SizedBox(
key: buttonKey,
height: 10.0,
width: 10.0,
child: const ColoredBox(
color: Colors.pink,
),
),
itemBuilder: (BuildContext context) => <PopupMenuEntry<int>>[
const PopupMenuItem<int>(value: 1, child: Text('-1-')),
const PopupMenuItem<int>(value: 2, child: Text('-2-')),
],
),
const SizedBox(height: 600),
],
),
),
),
),
);
// Open the menu.
await tester.tap(find.byKey(buttonKey));
await tester.pumpAndSettle();
Offset button = tester.getTopLeft(find.byKey(buttonKey));
expect(button, const Offset(0.0, 100.0));
Offset popupMenu = tester.getTopLeft(find.byType(SingleChildScrollView).last);
// The menu should be positioned directly next to the top of the button.
// The 8.0 pixels is [_kMenuScreenPadding].
expect(popupMenu, const Offset(8.0, 100.0));
// Close the menu.
await tester.tap(find.byKey(buttonKey), warnIfMissed: false);
await tester.pumpAndSettle();
// Scroll a little bit.
await tester.drag(find.byType(SingleChildScrollView), const Offset(0.0, -50.0));
button = tester.getTopLeft(find.byKey(buttonKey));
expect(button, const Offset(0.0, 50.0));
// Open the menu again.
await tester.tap(find.byKey(buttonKey));
await tester.pumpAndSettle();
popupMenu = tester.getTopLeft(find.byType(SingleChildScrollView).last);
// The menu should be positioned directly next to the top of the button.
// The 8.0 pixels is [_kMenuScreenPadding].
expect(popupMenu, const Offset(8.0, 50.0));
});
testWidgets('PopupMenuButton custom splash radius', (WidgetTester tester) async {
Future<void> buildFrameWithoutChild({double? splashRadius}) {
return tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
body: Center(
child: PopupMenuButton<String>(
splashRadius: splashRadius,
itemBuilder: (_) => <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
value: 'value',
child: Text('child'),
),
],
),
),
),
),
);
}
Future<void> buildFrameWithChild({double? splashRadius}) {
return tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: PopupMenuButton<String>(
splashRadius: splashRadius,
child: const Text('An item'),
itemBuilder: (_) => <PopupMenuEntry<String>>[
const PopupMenuDivider(),
],
),
),
),
),
);
}
await buildFrameWithoutChild();
expect(tester.widget<InkResponse>(find.byType(InkResponse)).radius,
Material.defaultSplashRadius);
await buildFrameWithChild();
expect(tester.widget<InkWell>(find.byType(InkWell)).radius, null);
const double testSplashRadius = 50;
await buildFrameWithoutChild(splashRadius: testSplashRadius);
expect(tester.widget<InkResponse>(find.byType(InkResponse)).radius,
testSplashRadius);
await buildFrameWithChild(splashRadius: testSplashRadius);
expect(tester.widget<InkWell>(find.byType(InkWell)).radius,
testSplashRadius);
});
testWidgets('Can override menu size constraints', (WidgetTester tester) async {
final Key popupMenuButtonKey = UniqueKey();
final Type menuItemType = const PopupMenuItem<String>(child: Text('item')).runtimeType;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: PopupMenuButton<String>(
key: popupMenuButtonKey,
constraints: const BoxConstraints(
minWidth: 500,
),
itemBuilder: (_) => <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
value: 'value',
child: Text('Item 0'),
),
],
),
),
),
),
);
// Show the menu
await tester.tap(find.byKey(popupMenuButtonKey));
await tester.pumpAndSettle();
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 0')).height, 48);
expect(tester.getSize(find.widgetWithText(menuItemType, 'Item 0')).width, 500);
});
testWidgets('Can change menu position and offset', (WidgetTester tester) async {
PopupMenuButton<int> buildMenuButton({required PopupMenuPosition position}) {
return PopupMenuButton<int>(
position: position,
itemBuilder: (BuildContext context) {
return <PopupMenuItem<int>>[
PopupMenuItem<int>(
value: 1,
child: Builder(
builder: (BuildContext context) {
return const Text('AAA');
},
),
),
];
},
);
}
// Popup menu with `MenuPosition.over (default) with default offset`.
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Material(
child: buildMenuButton(position: PopupMenuPosition.over),
),
),
),
);
// Open the popup menu.
await tester.tap(find.byType(IconButton));
await tester.pumpAndSettle();
expect(tester.getTopLeft(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_PopupMenu<int?>')), const Offset(8.0, 8.0));
// Close the popup menu.
await tester.tapAt(Offset.zero);
await tester.pump();
// Popup menu with `MenuPosition.under`(custom) with default offset`.
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Material(
child: buildMenuButton(position: PopupMenuPosition.under),
),
),
),
);
// Open the popup menu.
await tester.tap(find.byType(IconButton));
await tester.pumpAndSettle();
expect(tester.getTopLeft(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_PopupMenu<int?>')), const Offset(8.0, 40.0));
// Close the popup menu.
await tester.tapAt(Offset.zero);
await tester.pump();
// Popup menu with `MenuPosition.over (default) with custom offset`.
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Material(
child: PopupMenuButton<int>(
offset: const Offset(0.0, 50),
itemBuilder: (BuildContext context) {
return <PopupMenuItem<int>>[
PopupMenuItem<int>(
value: 1,
child: Builder(
builder: (BuildContext context) {
return const Text('AAA');
},
),
),
];
},
),
),
),
),
);
// Open the popup menu.
await tester.tap(find.byType(IconButton));
await tester.pumpAndSettle();
expect(tester.getTopLeft(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_PopupMenu<int?>')), const Offset(8.0, 50.0));
// Close the popup menu.
await tester.tapAt(Offset.zero);
await tester.pump();
// Popup menu with `MenuPosition.under (custom) with custom offset`.
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Material(
child: PopupMenuButton<int>(
offset: const Offset(0.0, 50),
position: PopupMenuPosition.under,
itemBuilder: (BuildContext context) {
return <PopupMenuItem<int>>[
PopupMenuItem<int>(
value: 1,
child: Builder(
builder: (BuildContext context) {
return const Text('AAA');
},
),
),
];
},
),
),
),
),
);
// Open the popup menu.
await tester.tap(find.byType(IconButton));
await tester.pumpAndSettle();
expect(tester.getTopLeft(find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_PopupMenu<int?>')), const Offset(8.0, 90.0));
});
testWidgets("PopupMenuButton icon inherits IconTheme's size", (WidgetTester tester) async {
Widget buildPopupMenu({double? themeIconSize, double? iconSize}) {
return MaterialApp(
theme: ThemeData(
iconTheme: IconThemeData(
size: themeIconSize,
),
),
home: Scaffold(
body: Center(
child: PopupMenuButton<String>(
iconSize: iconSize,
itemBuilder: (_) => <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
value: 'value',
child: Text('Item 0'),
),
],
),
),
),
);
}
// Popup menu with default icon size.
await tester.pumpWidget(buildPopupMenu());
// Default PopupMenuButton icon size is 24.0.
expect(tester.getSize(find.byIcon(Icons.more_vert)), const Size(24.0, 24.0));
// Popup menu with custom theme icon size.
await tester.pumpWidget(buildPopupMenu(themeIconSize: 30.0));
await tester.pumpAndSettle();
// PopupMenuButton icon inherits IconTheme's size.
expect(tester.getSize(find.byIcon(Icons.more_vert)), const Size(30.0, 30.0));
// Popup menu with custom icon size.
await tester.pumpWidget(buildPopupMenu(themeIconSize: 30.0, iconSize: 50.0));
await tester.pumpAndSettle();
// PopupMenuButton icon size overrides IconTheme's size.
expect(tester.getSize(find.byIcon(Icons.more_vert)), const Size(50.0, 50.0));
});
testWidgets('Popup menu clip behavior', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/107215
final Key popupButtonKey = UniqueKey();
const double radius = 20.0;
Widget buildPopupMenu({required Clip clipBehavior}) {
return MaterialApp(
home: Scaffold(
body: Center(
child: PopupMenuButton<String>(
key: popupButtonKey,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(radius)),
),
clipBehavior: clipBehavior,
itemBuilder: (_) => <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
value: 'value',
child: Text('Item 0'),
),
],
),
),
),
);
}
// Popup menu with default ClipBehavior.
await tester.pumpWidget(buildPopupMenu(clipBehavior: Clip.none));
// Open the popup to build and show the menu contents.
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
Material material = tester.widget<Material>(find.byType(Material).last);
expect(material.clipBehavior, Clip.none);
// Close the popup menu.
await tester.tapAt(Offset.zero);
await tester.pumpAndSettle();
// Popup menu with custom ClipBehavior.
await tester.pumpWidget(buildPopupMenu(clipBehavior: Clip.hardEdge));
// Open the popup to build and show the menu contents.
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
material = tester.widget<Material>(find.byType(Material).last);
expect(material.clipBehavior, Clip.hardEdge);
});
testWidgets('Uses closed loop focus traversal', (WidgetTester tester) async {
FocusNode nodeA() => Focus.of(find.text('A').evaluate().single);
FocusNode nodeB() => Focus.of(find.text('B').evaluate().single);
final GlobalKey popupButtonKey = GlobalKey();
await tester.pumpWidget(MaterialApp(
home: Scaffold(
body: Center(
child: PopupMenuButton<String>(
key: popupButtonKey,
itemBuilder: (_) => const <PopupMenuEntry<String>>[
PopupMenuItem<String>(
value: 'a',
child: Text('A'),
),
PopupMenuItem<String>(
value: 'b',
child: Text('B'),
),
],
),
),
),
));
// Open the popup to build and show the menu contents.
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
Future<bool> nextFocus() async {
final bool result = Actions.invoke(
primaryFocus!.context!,
const NextFocusIntent(),
)! as bool;
await tester.pump();
return result;
}
Future<bool> previousFocus() async {
final bool result = Actions.invoke(
primaryFocus!.context!,
const PreviousFocusIntent(),
)! as bool;
await tester.pump();
return result;
}
// Start at A
nodeA().requestFocus();
await tester.pump();
expect(nodeA().hasFocus, true);
expect(nodeB().hasFocus, false);
// A -> B
expect(await nextFocus(), true);
expect(nodeA().hasFocus, false);
expect(nodeB().hasFocus, true);
// B -> A (wrap around)
expect(await nextFocus(), true);
expect(nodeA().hasFocus, true);
expect(nodeB().hasFocus, false);
// B <- A
expect(await previousFocus(), true);
expect(nodeA().hasFocus, false);
expect(nodeB().hasFocus, true);
// A <- B (wrap around)
expect(await previousFocus(), true);
expect(nodeA().hasFocus, true);
expect(nodeB().hasFocus, false);
});
testWidgets('Popup menu scrollbar inherits ScrollbarTheme', (WidgetTester tester) async {
final Key popupButtonKey = UniqueKey();
const ScrollbarThemeData scrollbarTheme = ScrollbarThemeData(
thumbColor: MaterialStatePropertyAll<Color?>(Color(0xffff0000)),
thumbVisibility: MaterialStatePropertyAll<bool?>(true),
);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
scrollbarTheme: scrollbarTheme,
useMaterial3: true,
),
home: Material(
child: Column(
children: <Widget>[
PopupMenuButton<void>(
key: popupButtonKey,
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<void>>[
const PopupMenuItem<void>(
height: 1000,
child: Text('Example'),
),
];
},
),
],
),
),
)
);
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
expect(find.byType(Scrollbar), findsOneWidget);
// Test Scrollbar thumb color.
expect(
find.byType(Scrollbar),
paints..rrect(color: const Color(0xffff0000)),
);
// Close the menu.
await tester.tapAt(const Offset(20.0, 20.0));
await tester.pumpAndSettle();
// Test local ScrollbarTheme overrides global ScrollbarTheme.
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
scrollbarTheme: scrollbarTheme,
useMaterial3: true,
),
home: Material(
child: Column(
children: <Widget>[
ScrollbarTheme(
data: scrollbarTheme.copyWith(
thumbColor: const MaterialStatePropertyAll<Color?>(Color(0xff0000ff)),
),
child: PopupMenuButton<void>(
key: popupButtonKey,
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<void>>[
const PopupMenuItem<void>(
height: 1000,
child: Text('Example'),
),
];
},
),
),
],
),
),
)
);
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
expect(find.byType(Scrollbar), findsOneWidget);
// Scrollbar thumb color should be updated.
expect(
find.byType(Scrollbar),
paints..rrect(color: const Color(0xff0000ff)),
);
}, variant: TargetPlatformVariant.desktop());
testWidgets('Popup menu with RouteSettings', (WidgetTester tester) async {
late RouteSettings currentRouteSetting;
await tester.pumpWidget(
MaterialApp(
navigatorObservers: <NavigatorObserver>[
_ClosureNavigatorObserver(onDidChange: (Route<dynamic> newRoute) {
currentRouteSetting = newRoute.settings;
}),
],
home: const Material(
child: Center(
child: ElevatedButton(
onPressed: null,
child: Text('Go'),
),
),
),
),
);
final BuildContext context = tester.element(find.text('Go'));
const RouteSettings exampleSetting = RouteSettings(name: 'simple');
showMenu<void>(
context: context,
position: RelativeRect.fill,
items: const <PopupMenuItem<void>>[
PopupMenuItem<void>(child: Text('foo')),
],
routeSettings: exampleSetting,
);
await tester.pumpAndSettle();
expect(find.text('foo'), findsOneWidget);
expect(currentRouteSetting, exampleSetting);
await tester.tap(find.text('foo'));
await tester.pumpAndSettle();
expect(currentRouteSetting.name, '/');
});
testWidgets('Popup menu is positioned under the child', (WidgetTester tester) async {
final Key popupButtonKey = UniqueKey();
final Key childKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Column(
children: <Widget>[
PopupMenuButton<void>(
key: popupButtonKey,
position: PopupMenuPosition.under,
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<void>>[
const PopupMenuItem<void>(
child: Text('Example'),
),
];
},
child: SizedBox(
key: childKey,
height: 50,
width: 50,
)
),
],
),
),
)
);
await tester.tap(find.byKey(popupButtonKey));
await tester.pumpAndSettle();
final Offset childBottomLeft = tester.getBottomLeft(find.byKey(childKey));
final Offset menuTopLeft = tester.getTopLeft(find.bySemanticsLabel('Popup menu'));
expect(childBottomLeft, menuTopLeft);
});
testWidgets('PopupMenuItem onTap should be calling after Navigator.pop', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
appBar: AppBar(
actions: <Widget>[
PopupMenuButton<int>(
itemBuilder: (BuildContext context) => <PopupMenuItem<int>>[
PopupMenuItem<int>(
onTap: () {
showModalBottomSheet<void>(
context: context,
builder: (BuildContext context) {
return const SizedBox(
height: 200.0,
child: Center(child: Text('ModalBottomSheet')),
);
},
);
},
value: 10,
child: const Text('ACTION'),
),
],
),
],
),
),
),
);
await tester.tap(find.byType(PopupMenuButton<int>));
await tester.pumpAndSettle();
await tester.tap(find.text('ACTION'));
await tester.pumpAndSettle();
// Verify that the ModalBottomSheet is displayed
final Finder modalBottomSheet = find.text('ModalBottomSheet');
expect(modalBottomSheet, findsOneWidget);
});
testWidgets('Material3 - CheckedPopupMenuItem.labelTextStyle uses correct text style', (WidgetTester tester) async {
final Key popupMenuButtonKey = UniqueKey();
ThemeData theme = ThemeData(useMaterial3: true);
Widget buildMenu() {
return MaterialApp(
theme: theme,
home: Scaffold(
appBar: AppBar(
actions: <Widget>[
PopupMenuButton<void>(
key: popupMenuButtonKey,
itemBuilder: (BuildContext context) => <PopupMenuItem<void>>[
const CheckedPopupMenuItem<void>(
child: Text('Item 1'),
),
const CheckedPopupMenuItem<int>(
checked: true,
child: Text('Item 2'),
),
],
),
],
),
),
);
}
await tester.pumpWidget(buildMenu());
// Show the menu
await tester.tap(find.byKey(popupMenuButtonKey));
await tester.pumpAndSettle();
// Test default text style.
expect(_labelStyle(tester, 'Item 1')!.fontSize, 14.0);
expect(_labelStyle(tester, 'Item 1')!.color, theme.colorScheme.onSurface);
// Close the menu.
await tester.tapAt(const Offset(20.0, 20.0));
await tester.pumpAndSettle();
// Test custom text theme.
const TextStyle customTextStyle = TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic,
);
theme = theme.copyWith(
textTheme: const TextTheme(labelLarge: customTextStyle),
);
await tester.pumpWidget(buildMenu());
// Show the menu.
await tester.tap(find.byKey(popupMenuButtonKey));
await tester.pumpAndSettle();
// Test custom text theme.
expect(_labelStyle(tester, 'Item 1')!.fontSize, customTextStyle.fontSize);
expect(_labelStyle(tester, 'Item 1')!.fontWeight, customTextStyle.fontWeight);
expect(_labelStyle(tester, 'Item 1')!.fontStyle, customTextStyle.fontStyle);
});
testWidgets('CheckedPopupMenuItem.labelTextStyle resolve material states', (WidgetTester tester) async {
final Key popupMenuButtonKey = UniqueKey();
final MaterialStateProperty<TextStyle?> labelTextStyle = MaterialStateProperty.resolveWith(
(Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return const TextStyle(color: Colors.red, fontSize: 24.0);
}
return const TextStyle(color: Colors.amber, fontSize: 20.0);
});
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
appBar: AppBar(
actions: <Widget>[
PopupMenuButton<void>(
key: popupMenuButtonKey,
itemBuilder: (BuildContext context) => <PopupMenuItem<void>>[
CheckedPopupMenuItem<void>(
labelTextStyle: labelTextStyle,
child: const Text('Item 1'),
),
CheckedPopupMenuItem<int>(
checked: true,
labelTextStyle: labelTextStyle,
child: const Text('Item 2'),
),
],
),
],
),
),
),
);
// Show the menu.
await tester.tap(find.byKey(popupMenuButtonKey));
await tester.pumpAndSettle();
expect(
_labelStyle(tester, 'Item 1'),
labelTextStyle.resolve(<MaterialState>{})
);
expect(
_labelStyle(tester, 'Item 2'),
labelTextStyle.resolve(<MaterialState>{MaterialState.selected})
);
});
testWidgets('CheckedPopupMenuItem overrides redundant ListTile.contentPadding', (WidgetTester tester) async {
final Key popupMenuButtonKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
body: Center(
child: PopupMenuButton<String>(
key: popupMenuButtonKey,
child: const Text('button'),
onSelected: (String result) { },
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<String>>[
const CheckedPopupMenuItem<String>(
value: '0',
child: Text('Item 0'),
),
const CheckedPopupMenuItem<String>(
value: '1',
checked: true,
child: Text('Item 1'),
),
];
},
),
),
),
),
);
// Show the menu.
await tester.tap(find.byKey(popupMenuButtonKey));
await tester.pumpAndSettle();
SafeArea getItemSafeArea(String label) {
return tester.widget<SafeArea>(find.ancestor(
of: find.text(label),
matching: find.byType(SafeArea),
));
}
expect(getItemSafeArea('Item 0').minimum, EdgeInsets.zero);
expect(getItemSafeArea('Item 1').minimum, EdgeInsets.zero);
});
testWidgets('PopupMenuItem overrides redundant ListTile.contentPadding', (WidgetTester tester) async {
final Key popupMenuButtonKey = UniqueKey();
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
body: Center(
child: PopupMenuButton<String>(
key: popupMenuButtonKey,
child: const Text('button'),
onSelected: (String result) { },
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<String>>[
const PopupMenuItem<String>(
value: '0',
enabled: false,
child: ListTile(title: Text('Item 0')),
),
const PopupMenuItem<String>(
value: '1',
child: ListTile(title: Text('Item 1')),
),
];
},
),
),
),
),
);
// Show the menu.
await tester.tap(find.byKey(popupMenuButtonKey));
await tester.pumpAndSettle();
SafeArea getItemSafeArea(String label) {
return tester.widget<SafeArea>(find.ancestor(
of: find.text(label),
matching: find.byType(SafeArea),
));
}
expect(getItemSafeArea('Item 0').minimum, EdgeInsets.zero);
expect(getItemSafeArea('Item 1').minimum, EdgeInsets.zero);
});
testWidgets('Material3 - PopupMenuItem overrides ListTile.titleTextStyle', (WidgetTester tester) async {
final Key popupMenuButtonKey = UniqueKey();
ThemeData theme = ThemeData(useMaterial3: true);
Widget buildMenu() {
return MaterialApp(
theme: theme,
home: Scaffold(
body: Center(
child: PopupMenuButton<String>(
key: popupMenuButtonKey,
child: const Text('button'),
onSelected: (String result) { },
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<String>>[
// Popup menu item with a Text widget.
const PopupMenuItem<String>(
value: '0',
child: Text('Item 0'),
),
// Popup menu item with a ListTile widget.
const PopupMenuItem<String>(
value: '1',
child: ListTile(title: Text('Item 1')),
),
];
},
),
),
),
);
}
await tester.pumpWidget(buildMenu());
// Show the menu.
await tester.tap(find.byKey(popupMenuButtonKey));
await tester.pumpAndSettle();
// Test popup menu item with a Text widget.
expect(_labelStyle(tester, 'Item 0')!.fontSize, 14.0);
expect(_labelStyle(tester, 'Item 0')!.color, theme.colorScheme.onSurface);
// Test popup menu item with a ListTile widget.
expect(_labelStyle(tester, 'Item 1')!.fontSize, 14.0);
expect(_labelStyle(tester, 'Item 1')!.color, theme.colorScheme.onSurface);
// Close the menu.
await tester.tapAt(const Offset(20.0, 20.0));
await tester.pumpAndSettle();
// Test custom text theme.
const TextStyle customTextStyle = TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic,
);
theme = theme.copyWith(
textTheme: const TextTheme(labelLarge: customTextStyle),
);
await tester.pumpWidget(buildMenu());
// Show the menu.
await tester.tap(find.byKey(popupMenuButtonKey));
await tester.pumpAndSettle();
// Test popup menu item with a Text widget with custom text theme.
expect(_labelStyle(tester, 'Item 0')!.fontSize, customTextStyle.fontSize);
expect(_labelStyle(tester, 'Item 0')!.fontWeight, customTextStyle.fontWeight);
expect(_labelStyle(tester, 'Item 0')!.fontStyle, customTextStyle.fontStyle);
// Test popup menu item with a ListTile widget with custom text theme.
expect(_labelStyle(tester, 'Item 1')!.fontSize, customTextStyle.fontSize);
expect(_labelStyle(tester, 'Item 1')!.fontWeight, customTextStyle.fontWeight);
expect(_labelStyle(tester, 'Item 1')!.fontStyle, customTextStyle.fontStyle);
});
testWidgets('Material2 - PopupMenuItem overrides ListTile.titleTextStyle', (WidgetTester tester) async {
final Key popupMenuButtonKey = UniqueKey();
ThemeData theme = ThemeData(useMaterial3: false);
Widget buildMenu() {
return MaterialApp(
theme: theme,
home: Scaffold(
body: Center(
child: PopupMenuButton<String>(
key: popupMenuButtonKey,
child: const Text('button'),
onSelected: (String result) { },
itemBuilder: (BuildContext context) {
return <PopupMenuEntry<String>>[
// Popup menu item with a Text widget.
const PopupMenuItem<String>(
value: '0',
child: Text('Item 0'),
),
// Popup menu item with a ListTile widget.
const PopupMenuItem<String>(
value: '1',
child: ListTile(title: Text('Item 1')),
),
];
},
),
),
),
);
}
await tester.pumpWidget(buildMenu());
// Show the menu.
await tester.tap(find.byKey(popupMenuButtonKey));
await tester.pumpAndSettle();
// Test popup menu item with a Text widget.
expect(_labelStyle(tester, 'Item 0')!.fontSize, 16.0);
expect(_labelStyle(tester, 'Item 0')!.color, theme.textTheme.subtitle1!.color);
// Test popup menu item with a ListTile widget.
expect(_labelStyle(tester, 'Item 1')!.fontSize, 16.0);
expect(_labelStyle(tester, 'Item 1')!.color, theme.textTheme.subtitle1!.color);
// Close the menu.
await tester.tapAt(const Offset(20.0, 20.0));
await tester.pumpAndSettle();
// Test custom text theme.
const TextStyle customTextStyle = TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
fontStyle: FontStyle.italic,
);
theme = theme.copyWith(
textTheme: const TextTheme(subtitle1: customTextStyle),
);
await tester.pumpWidget(buildMenu());
// Show the menu.
await tester.tap(find.byKey(popupMenuButtonKey));
await tester.pumpAndSettle();
// Test popup menu item with a Text widget with custom text style.
expect(_labelStyle(tester, 'Item 0')!.fontSize, customTextStyle.fontSize);
expect(_labelStyle(tester, 'Item 0')!.fontWeight, customTextStyle.fontWeight);
expect(_labelStyle(tester, 'Item 0')!.fontStyle, customTextStyle.fontStyle);
// Test popup menu item with a ListTile widget with custom text style.
expect(_labelStyle(tester, 'Item 1')!.fontSize, customTextStyle.fontSize);
expect(_labelStyle(tester, 'Item 1')!.fontWeight, customTextStyle.fontWeight);
expect(_labelStyle(tester, 'Item 1')!.fontStyle, customTextStyle.fontStyle);
});
testWidgets('CheckedPopupMenuItem.onTap callback is called when defined', (WidgetTester tester) async {
int count = 0;
await tester.pumpWidget(
TestApp(
textDirection: TextDirection.ltr,
child: Material(
child: RepaintBoundary(
child: PopupMenuButton<String>(
child: const Text('button'),
itemBuilder: (BuildContext context) {
return <PopupMenuItem<String>>[
CheckedPopupMenuItem<String>(
onTap: () {
count += 1;
},
value: 'item1',
child: const Text('Item with onTap'),
),
const CheckedPopupMenuItem<String>(
value: 'item2',
child: Text('Item without onTap'),
),
];
},
),
),
),
),
);
// Tap a checked menu item with onTap.
await tester.tap(find.text('button'));
await tester.pumpAndSettle();
await tester.tap(find.widgetWithText(CheckedPopupMenuItem<String>, 'Item with onTap'));
await tester.pumpAndSettle();
expect(count, 1);
// Tap a checked menu item without onTap.
await tester.tap(find.text('button'));
await tester.pumpAndSettle();
await tester.tap(find.widgetWithText(CheckedPopupMenuItem<String>, 'Item without onTap'));
await tester.pumpAndSettle();
expect(count, 1);
});
testWidgets('PopupMenuButton uses root navigator if useRootNavigator is true', (WidgetTester tester) async {
final MenuObserver rootObserver = MenuObserver();
final MenuObserver nestedObserver = MenuObserver();
await tester.pumpWidget(
MaterialApp(
navigatorObservers: <NavigatorObserver>[rootObserver],
home: Navigator(
observers: <NavigatorObserver>[nestedObserver],
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<dynamic>(
builder: (BuildContext context) {
return Material(
child: PopupMenuButton<String>(
useRootNavigator: true,
child: const Text('button'),
itemBuilder: (BuildContext context) {
return <PopupMenuItem<String>>[
const CheckedPopupMenuItem<String>(
value: 'item1',
child: Text('item 1'),
),
const CheckedPopupMenuItem<String>(
value: 'item2',
child: Text('item 2'),
),
];
},
),
);
},
);
},
),
),
);
// Open the dialog.
await tester.tap(find.text('button'));
expect(rootObserver.menuCount, 1);
expect(nestedObserver.menuCount, 0);
});
testWidgets('PopupMenuButton does not use root navigator if useRootNavigator is false', (WidgetTester tester) async {
final MenuObserver rootObserver = MenuObserver();
final MenuObserver nestedObserver = MenuObserver();
await tester.pumpWidget(
MaterialApp(
navigatorObservers: <NavigatorObserver>[rootObserver],
home: Navigator(
observers: <NavigatorObserver>[nestedObserver],
onGenerateRoute: (RouteSettings settings) {
return MaterialPageRoute<dynamic>(
builder: (BuildContext context) {
return Material(
child: PopupMenuButton<String>(
child: const Text('button'),
itemBuilder: (BuildContext context) {
return <PopupMenuItem<String>>[
const CheckedPopupMenuItem<String>(
value: 'item1',
child: Text('item 1'),
),
const CheckedPopupMenuItem<String>(
value: 'item2',
child: Text('item 2'),
),
];
},
),
);
},
);
},
),
),
);
// Open the dialog.
await tester.tap(find.text('button'));
expect(rootObserver.menuCount, 0);
expect(nestedObserver.menuCount, 1);
});
testWidgets('Override Popup Menu animation using AnimationStyle', (WidgetTester tester) async {
final Key targetKey = UniqueKey();
Widget buildPopupMenu({ AnimationStyle? animationStyle }) {
return MaterialApp(
home: Material(
child: Center(
child: PopupMenuButton<int>(
key: targetKey,
popUpAnimationStyle: animationStyle,
itemBuilder: (BuildContext context) {
return <PopupMenuItem<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('One'),
),
const PopupMenuItem<int>(
value: 2,
child: Text('Two'),
),
const PopupMenuItem<int>(
value: 3,
child: Text('Three'),
),
];
},
),
),
),
);
}
// Test default animation.
await tester.pumpWidget(buildPopupMenu());
await tester.tap(find.byKey(targetKey));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100)); // Advance the animation by 1/3 of its duration.
expect(tester.getSize(find.byType(Material).last), within(distance: 0.1, from: const Size(112.0, 80.0)));
await tester.pump(const Duration(milliseconds: 100)); // Advance the animation by 2/3 of its duration.
expect(tester.getSize(find.byType(Material).last), within(distance: 0.1, from: const Size(112.0, 160.0)));
await tester.pumpAndSettle(); // Advance the animation to the end.
expect(tester.getSize(find.byType(Material).last), within(distance: 0.1, from: const Size(112.0, 160.0)));
// Tap outside to dismiss the menu.
await tester.tapAt(const Offset(20.0, 20.0));
await tester.pumpAndSettle();
// Override the animation duration.
await tester.pumpWidget(buildPopupMenu(animationStyle: AnimationStyle(duration: Duration.zero)));
await tester.tap(find.byKey(targetKey));
await tester.pump();
await tester.pump(const Duration(milliseconds: 1)); // Advance the animation by 1 millisecond.
expect(tester.getSize(find.byType(Material).last), within(distance: 0.1, from: const Size(112.0, 160.0)));
// Tap outside to dismiss the menu.
await tester.tapAt(const Offset(20.0, 20.0));
await tester.pumpAndSettle();
// Override the animation curve.
await tester.pumpWidget(buildPopupMenu(animationStyle: AnimationStyle(curve: Easing.emphasizedAccelerate)));
await tester.tap(find.byKey(targetKey));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100)); // Advance the animation by 1/3 of its duration.
expect(tester.getSize(find.byType(Material).last), within(distance: 0.1, from: const Size(32.4, 15.4)));
await tester.pump(const Duration(milliseconds: 100)); // Advance the animation by 2/3 of its duration.
expect(tester.getSize(find.byType(Material).last), within(distance: 0.1, from: const Size(112.0, 72.2)));
await tester.pumpAndSettle(); // Advance the animation to the end.
expect(tester.getSize(find.byType(Material).last), within(distance: 0.1, from: const Size(112.0, 160.0)));
});
testWidgets('PopupMenuButton scrolls initial value/selected value to visible', (WidgetTester tester) async {
const int length = 50;
const int selectedValue = length - 1;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Align(
alignment: Alignment.bottomCenter,
child: PopupMenuButton<int>(
itemBuilder: (BuildContext context) {
return List<PopupMenuEntry<int>>.generate(length, (int index) {
return PopupMenuItem<int>(value: index, child: Text('item #$index'));
});
},
popUpAnimationStyle: AnimationStyle.noAnimation,
initialValue: selectedValue,
child: const Text('click here'),
),
),
),
),
);
await tester.tap(find.text('click here'));
await tester.pump();
// Set up finder and verify basic widget structure.
final Finder item49 = find.text('item #49');
expect(item49, findsOneWidget);
// The initially selected menu item should be positioned on screen.
final RenderBox initialItem = tester.renderObject<RenderBox>(item49);
final Rect initialItemBounds = initialItem.localToGlobal(Offset.zero) & initialItem.size;
final Size windowSize = tester.view.physicalSize / tester.view.devicePixelRatio;
expect(initialItemBounds.bottomRight.dy, lessThanOrEqualTo(windowSize.height));
// Select item 20.
final Finder item20 = find.text('item #20');
await tester.scrollUntilVisible(item20, 500);
expect(item20, findsOneWidget);
await tester.tap(item20);
await tester.pump();
// Open menu again.
await tester.tap(find.text('click here'));
await tester.pump();
expect(item20, findsOneWidget);
// The selected menu item should be positioned on screen.
final RenderBox selectedItem = tester.renderObject<RenderBox>(item20);
final Rect selectedItemBounds = selectedItem.localToGlobal(Offset.zero) & selectedItem.size;
expect(selectedItemBounds.bottomRight.dy, lessThanOrEqualTo(windowSize.height));
});
testWidgets('PopupMenuButton properly positions a constrained-size popup', (WidgetTester tester) async {
final Size windowSize = tester.view.physicalSize / tester.view.devicePixelRatio;
const int length = 50;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Padding(
padding: const EdgeInsets.all(50),
child: Align(
alignment: Alignment.bottomCenter,
child: PopupMenuButton<int>(
itemBuilder: (BuildContext context) {
return List<PopupMenuEntry<int>>.generate(length, (int index) {
return PopupMenuItem<int>(value: index, child: Text('item #$index'));
});
},
constraints: BoxConstraints(maxHeight: windowSize.height / 3),
popUpAnimationStyle: AnimationStyle.noAnimation,
initialValue: length - 1,
child: const Text('click here'),
),
),
),
),
),
);
await tester.tap(find.text('click here'));
await tester.pump();
// Set up finders and verify basic widget structure
final Finder findButton = find.byType(PopupMenuButton<int>);
final Finder findLastItem = find.text('item #49');
final Finder findListBody = find.byType(ListBody);
final Finder findListViewport = find.ancestor(
of: findListBody,
matching: find.byType(SingleChildScrollView),
);
expect(findButton, findsOne);
expect(findLastItem, findsOne);
expect(findListBody, findsOne);
expect(findListViewport, findsOne);
// The button and the list viewport should overlap
final RenderBox button = tester.renderObject<RenderBox>(findButton);
final Rect buttonBounds = button.localToGlobal(Offset.zero) & button.size;
final RenderBox listViewport = tester.renderObject<RenderBox>(findListViewport);
final Rect listViewportBounds = listViewport.localToGlobal(Offset.zero) & listViewport.size;
expect(listViewportBounds.topLeft.dy, lessThanOrEqualTo(windowSize.height));
expect(listViewportBounds.bottomRight.dy, lessThanOrEqualTo(windowSize.height));
expect(listViewportBounds, overlaps(buttonBounds));
});
testWidgets('PopupMenuButton honors style', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: PopupMenuButton<int>(
style: const ButtonStyle(
iconColor: MaterialStatePropertyAll<Color>(Colors.red),
),
itemBuilder: (BuildContext context) {
return <PopupMenuItem<int>>[
const PopupMenuItem<int>(
value: 1,
child: Text('One'),
),
];
},
),
),
),
);
final RichText iconText = tester.firstWidget(find.descendant(
of: find.byType(PopupMenuButton<int>),
matching: find.byType(RichText),
));
expect(iconText.text.style?.color, Colors.red);
});
}
Matcher overlaps(Rect other) => OverlapsMatcher(other);
class OverlapsMatcher extends Matcher {
OverlapsMatcher(this.other);
final Rect other;
@override
Description describe(Description description) {
return description.add('<Rect that overlaps with $other>');
}
@override
bool matches(Object? item, Map<dynamic, dynamic> matchState) => item is Rect && item.overlaps(other);
@override
Description describeMismatch(dynamic item, Description mismatchDescription,
Map<dynamic, dynamic> matchState, bool verbose) {
return mismatchDescription.add('does not overlap');
}
}
class TestApp extends StatelessWidget {
const TestApp({
super.key,
required this.textDirection,
this.child,
});
final TextDirection textDirection;
final Widget? child;
@override
Widget build(BuildContext context) {
return Localizations(
locale: const Locale('en', 'US'),
delegates: const <LocalizationsDelegate<dynamic>>[
DefaultWidgetsLocalizations.delegate,
DefaultMaterialLocalizations.delegate,
],
child: MediaQuery(
data: MediaQueryData.fromView(View.of(context)),
child: Directionality(
textDirection: textDirection,
child: Navigator(
onGenerateRoute: (RouteSettings settings) {
assert(settings.name == '/');
return MaterialPageRoute<void>(
settings: settings,
builder: (BuildContext context) => Material(
child: child,
),
);
},
),
),
),
);
}
}
class MenuObserver extends NavigatorObserver {
int menuCount = 0;
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) {
if (route.toString().contains('_PopupMenuRoute')) {
menuCount++;
}
super.didPush(route, previousRoute);
}
}
class _ClosureNavigatorObserver extends NavigatorObserver {
_ClosureNavigatorObserver({required this.onDidChange});
final void Function(Route<dynamic> newRoute) onDidChange;
@override
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) => onDidChange(route);
@override
void didPop(Route<dynamic> route, Route<dynamic>? previousRoute) => onDidChange(previousRoute!);
@override
void didRemove(Route<dynamic> route, Route<dynamic>? previousRoute) => onDidChange(previousRoute!);
@override
void didReplace({Route<dynamic>? newRoute, Route<dynamic>? oldRoute}) => onDidChange(newRoute!);
}
TextStyle? _labelStyle(WidgetTester tester, String label) {
return tester.widget<RichText>(find.descendant(
of: find.text(label),
matching: find.byType(RichText),
)).text.style;
}
TextStyle? _iconStyle(WidgetTester tester, IconData icon) {
return tester.widget<RichText>(find.descendant(
of: find.byIcon(icon),
matching: find.byType(RichText),
)).text.style;
}
| flutter/packages/flutter/test/material/popup_menu_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/popup_menu_test.dart",
"repo_id": "flutter",
"token_count": 72644
} | 666 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('SearchBarThemeData copyWith, ==, hashCode basics', () {
expect(const SearchBarThemeData(), const SearchBarThemeData().copyWith());
expect(const SearchBarThemeData().hashCode, const SearchBarThemeData()
.copyWith()
.hashCode);
});
test('SearchBarThemeData lerp special cases', () {
expect(SearchBarThemeData.lerp(null, null, 0), null);
const SearchBarThemeData data = SearchBarThemeData();
expect(identical(SearchBarThemeData.lerp(data, data, 0.5), data), true);
});
test('SearchBarThemeData defaults', () {
const SearchBarThemeData themeData = SearchBarThemeData();
expect(themeData.elevation, null);
expect(themeData.backgroundColor, null);
expect(themeData.shadowColor, null);
expect(themeData.surfaceTintColor, null);
expect(themeData.overlayColor, null);
expect(themeData.side, null);
expect(themeData.shape, null);
expect(themeData.padding, null);
expect(themeData.textStyle, null);
expect(themeData.hintStyle, null);
expect(themeData.constraints, null);
expect(themeData.textCapitalization, null);
const SearchBarTheme theme = SearchBarTheme(data: SearchBarThemeData(), child: SizedBox());
expect(theme.data.elevation, null);
expect(theme.data.backgroundColor, null);
expect(theme.data.shadowColor, null);
expect(theme.data.surfaceTintColor, null);
expect(theme.data.overlayColor, null);
expect(theme.data.side, null);
expect(theme.data.shape, null);
expect(theme.data.padding, null);
expect(theme.data.textStyle, null);
expect(theme.data.hintStyle, null);
expect(theme.data.constraints, null);
expect(theme.data.textCapitalization, null);
});
testWidgets('Default SearchBarThemeData debugFillProperties', (WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const SearchBarThemeData().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('SearchBarThemeData implements debugFillProperties', (
WidgetTester tester) async {
final DiagnosticPropertiesBuilder builder = DiagnosticPropertiesBuilder();
const SearchBarThemeData(
elevation: MaterialStatePropertyAll<double>(3.0),
backgroundColor: MaterialStatePropertyAll<Color>(Color(0xfffffff1)),
shadowColor: MaterialStatePropertyAll<Color>(Color(0xfffffff2)),
surfaceTintColor: MaterialStatePropertyAll<Color>(Color(0xfffffff3)),
overlayColor: MaterialStatePropertyAll<Color>(Color(0xfffffff4)),
side: MaterialStatePropertyAll<BorderSide>(BorderSide(width: 2.0, color: Color(0xfffffff5))),
shape: MaterialStatePropertyAll<OutlinedBorder>(StadiumBorder()),
padding: MaterialStatePropertyAll<EdgeInsets>(EdgeInsets.all(16.0)),
textStyle: MaterialStatePropertyAll<TextStyle>(TextStyle(fontSize: 24.0)),
hintStyle: MaterialStatePropertyAll<TextStyle>(TextStyle(fontSize: 16.0)),
constraints: BoxConstraints(minWidth: 350, maxWidth: 850),
textCapitalization: TextCapitalization.characters,
).debugFillProperties(builder);
final List<String> description = builder.properties
.where((DiagnosticsNode node) => !node.isFiltered(DiagnosticLevel.info))
.map((DiagnosticsNode node) => node.toString())
.toList();
expect(description[0], 'elevation: WidgetStatePropertyAll(3.0)');
expect(description[1], 'backgroundColor: WidgetStatePropertyAll(Color(0xfffffff1))');
expect(description[2], 'shadowColor: WidgetStatePropertyAll(Color(0xfffffff2))');
expect(description[3], 'surfaceTintColor: WidgetStatePropertyAll(Color(0xfffffff3))');
expect(description[4], 'overlayColor: WidgetStatePropertyAll(Color(0xfffffff4))');
expect(description[5], 'side: WidgetStatePropertyAll(BorderSide(color: Color(0xfffffff5), width: 2.0))');
expect(description[6], 'shape: WidgetStatePropertyAll(StadiumBorder(BorderSide(width: 0.0, style: none)))');
expect(description[7], 'padding: WidgetStatePropertyAll(EdgeInsets.all(16.0))');
expect(description[8], 'textStyle: WidgetStatePropertyAll(TextStyle(inherit: true, size: 24.0))');
expect(description[9], 'hintStyle: WidgetStatePropertyAll(TextStyle(inherit: true, size: 16.0))');
expect(description[10], 'constraints: BoxConstraints(350.0<=w<=850.0, 0.0<=h<=Infinity)');
expect(description[11], 'textCapitalization: TextCapitalization.characters');
});
group('[Theme, SearchBarTheme, SearchBar properties overrides]', () {
const double elevationValue = 5.0;
const Color backgroundColorValue = Color(0xff000001);
const Color shadowColorValue = Color(0xff000001);
const Color surfaceTintColorValue = Color(0xff000001);
const Color overlayColorValue = Color(0xff000001);
const BorderSide sideValue = BorderSide(color: Color(0xff000004), width: 2.0);
const OutlinedBorder shapeValue = RoundedRectangleBorder(side: sideValue, borderRadius: BorderRadius.all(Radius.circular(2.0)));
const EdgeInsets paddingValue = EdgeInsets.symmetric(horizontal: 16.0);
const TextStyle textStyleValue = TextStyle(color: Color(0xff000005), fontSize: 20.0);
const TextStyle hintStyleValue = TextStyle(color: Color(0xff000006), fontSize: 18.0);
const MaterialStateProperty<double?> elevation = MaterialStatePropertyAll<double>(elevationValue);
const MaterialStateProperty<Color?> backgroundColor = MaterialStatePropertyAll<Color>(backgroundColorValue);
const MaterialStateProperty<Color?> shadowColor = MaterialStatePropertyAll<Color>(shadowColorValue);
const MaterialStateProperty<Color?> surfaceTintColor = MaterialStatePropertyAll<Color>(surfaceTintColorValue);
const MaterialStateProperty<Color?> overlayColor = MaterialStatePropertyAll<Color>(overlayColorValue);
const MaterialStateProperty<BorderSide?> side = MaterialStatePropertyAll<BorderSide>(sideValue);
const MaterialStateProperty<OutlinedBorder?> shape = MaterialStatePropertyAll<OutlinedBorder>(shapeValue);
const MaterialStateProperty<EdgeInsetsGeometry?> padding = MaterialStatePropertyAll<EdgeInsets>(paddingValue);
const MaterialStateProperty<TextStyle?> textStyle = MaterialStatePropertyAll<TextStyle>(textStyleValue);
const MaterialStateProperty<TextStyle?> hintStyle = MaterialStatePropertyAll<TextStyle>(hintStyleValue);
const BoxConstraints constraints = BoxConstraints(minWidth: 250.0, maxWidth: 300.0, minHeight: 80.0);
const TextCapitalization textCapitalization = TextCapitalization.words;
const SearchBarThemeData searchBarTheme = SearchBarThemeData(
elevation: elevation,
backgroundColor: backgroundColor,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
overlayColor: overlayColor,
side: side,
shape: shape,
padding: padding,
textStyle: textStyle,
hintStyle: hintStyle,
constraints: constraints,
textCapitalization: textCapitalization,
);
Widget buildFrame({
bool useSearchBarProperties = false,
SearchBarThemeData? searchBarThemeData,
SearchBarThemeData? overallTheme
}) {
final Widget child = Builder(
builder: (BuildContext context) {
if (!useSearchBarProperties) {
return const SearchBar(
hintText: 'hint',
leading: Icon(Icons.search),
trailing: <Widget>[ Icon(Icons.menu)],
);
}
return const SearchBar(
hintText: 'hint',
leading: Icon(Icons.search),
trailing: <Widget>[ Icon(Icons.menu)],
elevation: elevation,
backgroundColor: backgroundColor,
shadowColor: shadowColor,
surfaceTintColor: surfaceTintColor,
overlayColor: overlayColor,
side: side,
shape: shape,
padding: padding,
textStyle: textStyle,
hintStyle: hintStyle,
constraints: constraints,
textCapitalization: textCapitalization,
);
},
);
return MaterialApp(
theme: ThemeData.from(
colorScheme: const ColorScheme.light(), useMaterial3: true)
.copyWith(
searchBarTheme: overallTheme,
),
home: Scaffold(
body: Center(
// If the SearchBarThemeData widget is present, it's used
// instead of the Theme's ThemeData.searchBarTheme.
child: searchBarThemeData == null ? child : SearchBarTheme(
data: searchBarThemeData,
child: child,
),
),
),
);
}
final Finder findMaterial = find.descendant(
of: find.byType(SearchBar),
matching: find.byType(Material),
);
final Finder findInkWell = find.descendant(
of: find.byType(SearchBar),
matching: find.byType(InkWell),
);
const Set<MaterialState> hovered = <MaterialState>{ MaterialState.hovered};
const Set<MaterialState> focused = <MaterialState>{ MaterialState.focused};
const Set<MaterialState> pressed = <MaterialState>{ MaterialState.pressed};
Future<void> checkSearchBar(WidgetTester tester) async {
final Material material = tester.widget<Material>(findMaterial);
final InkWell inkWell = tester.widget<InkWell>(findInkWell);
expect(material.elevation, elevationValue);
expect(material.color, backgroundColorValue);
expect(material.shadowColor, shadowColorValue);
expect(material.surfaceTintColor, surfaceTintColorValue);
expect(material.shape, shapeValue);
expect(inkWell.overlayColor!.resolve(hovered), overlayColor.resolve(hovered));
expect(inkWell.overlayColor!.resolve(focused), overlayColor.resolve(focused));
expect(inkWell.overlayColor!.resolve(pressed), overlayColor.resolve(pressed));
expect(inkWell.customBorder, shapeValue);
expect(tester.getSize(find.byType(SearchBar)), const Size(300.0, 80.0));
final Text hintText = tester.widget(find.text('hint'));
expect(hintText.style?.color, hintStyleValue.color);
expect(hintText.style?.fontSize, hintStyleValue.fontSize);
await tester.enterText(find.byType(TextField), 'input');
final EditableText inputText = tester.widget(find.text('input'));
expect(inputText.style.color, textStyleValue.color);
expect(inputText.style.fontSize, textStyleValue.fontSize);
expect(inputText.textCapitalization, textCapitalization);
final Rect barRect = tester.getRect(find.byType(SearchBar));
final Rect leadingRect = tester.getRect(find.byIcon(Icons.search));
final Rect textFieldRect = tester.getRect(find.byType(TextField));
final Rect trailingRect = tester.getRect(find.byIcon(Icons.menu));
expect(barRect.left, leadingRect.left - 16.0);
expect(leadingRect.right, textFieldRect.left - 16.0);
expect(textFieldRect.right, trailingRect.left - 16.0);
expect(trailingRect.right, barRect.right - 16.0);
}
testWidgets('SearchBar properties overrides defaults', (WidgetTester tester) async {
await tester.pumpWidget(buildFrame(useSearchBarProperties: true));
await tester.pumpAndSettle(); // allow the animations to finish
checkSearchBar(tester);
});
testWidgets('SearchBar theme data overrides defaults', (WidgetTester tester) async {
await tester.pumpWidget(buildFrame(searchBarThemeData: searchBarTheme));
await tester.pumpAndSettle();
checkSearchBar(tester);
});
testWidgets('Overall Theme SearchBar theme overrides defaults', (WidgetTester tester) async {
await tester.pumpWidget(buildFrame(overallTheme: searchBarTheme));
await tester.pumpAndSettle();
checkSearchBar(tester);
});
// Same as the previous tests with empty SearchBarThemeData's instead of null.
testWidgets('SearchBar properties overrides defaults, empty theme and overall theme', (WidgetTester tester) async {
await tester.pumpWidget(buildFrame(useSearchBarProperties: true,
searchBarThemeData: const SearchBarThemeData(),
overallTheme: const SearchBarThemeData()));
await tester.pumpAndSettle(); // allow the animations to finish
checkSearchBar(tester);
});
testWidgets('SearchBar theme overrides defaults and overall theme', (WidgetTester tester) async {
await tester.pumpWidget(buildFrame(searchBarThemeData: searchBarTheme,
overallTheme: const SearchBarThemeData()));
await tester.pumpAndSettle(); // allow the animations to finish
checkSearchBar(tester);
});
testWidgets('Overall Theme SearchBar theme overrides defaults and null theme', (WidgetTester tester) async {
await tester.pumpWidget(buildFrame(overallTheme: searchBarTheme));
await tester.pumpAndSettle(); // allow the animations to finish
checkSearchBar(tester);
});
});
}
| flutter/packages/flutter/test/material/search_bar_theme_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/search_bar_theme_test.dart",
"repo_id": "flutter",
"token_count": 4720
} | 667 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file is run as part of a reduced test set in CI on Mac and Windows
// machines.
@Tags(<String>['reduced-test-set'])
library;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
const String _tab1Text = 'tab 1';
const String _tab2Text = 'tab 2';
const String _tab3Text = 'tab 3';
final Key _painterKey = UniqueKey();
const List<Tab> _tabs = <Tab>[
Tab(text: _tab1Text, icon: Icon(Icons.looks_one)),
Tab(text: _tab2Text, icon: Icon(Icons.looks_two)),
Tab(text: _tab3Text, icon: Icon(Icons.looks_3)),
];
final List<SizedBox> _sizedTabs = <SizedBox>[
SizedBox(key: UniqueKey(), width: 100.0, height: 50.0),
SizedBox(key: UniqueKey(), width: 100.0, height: 50.0),
];
Widget buildTabBar({
TabBarTheme? tabBarTheme,
bool secondaryTabBar = false,
List<Widget> tabs = _tabs,
bool isScrollable = false,
bool useMaterial3 = false,
}) {
final TabController controller = TabController(
length: tabs.length,
vsync: const TestVSync(),
);
addTearDown(controller.dispose);
if (secondaryTabBar) {
return MaterialApp(
theme: ThemeData(tabBarTheme: tabBarTheme, useMaterial3: useMaterial3),
home: Scaffold(
body: RepaintBoundary(
key: _painterKey,
child: TabBar.secondary(
tabs: tabs,
isScrollable: isScrollable,
controller: controller,
),
),
),
);
}
return MaterialApp(
theme: ThemeData(tabBarTheme: tabBarTheme, useMaterial3: useMaterial3),
home: Scaffold(
body: RepaintBoundary(
key: _painterKey,
child: TabBar(
tabs: tabs,
isScrollable: isScrollable,
controller: controller,
),
),
),
);
}
RenderParagraph _getIcon(WidgetTester tester, IconData icon) {
return tester.renderObject<RenderParagraph>(
find.descendant(of: find.byIcon(icon), matching: find.byType(RichText)),
);
}
RenderParagraph _getText(WidgetTester tester, String text) {
return tester.renderObject<RenderParagraph>(find.text(text));
}
void main() {
test('TabBarTheme copyWith, ==, hashCode, defaults', () {
expect(const TabBarTheme(), const TabBarTheme().copyWith());
expect(const TabBarTheme().hashCode, const TabBarTheme().copyWith().hashCode);
expect(const TabBarTheme().indicator, null);
expect(const TabBarTheme().indicatorColor, null);
expect(const TabBarTheme().indicatorSize, null);
expect(const TabBarTheme().dividerColor, null);
expect(const TabBarTheme().dividerHeight, null);
expect(const TabBarTheme().labelColor, null);
expect(const TabBarTheme().labelPadding, null);
expect(const TabBarTheme().labelStyle, null);
expect(const TabBarTheme().unselectedLabelColor, null);
expect(const TabBarTheme().unselectedLabelStyle, null);
expect(const TabBarTheme().overlayColor, null);
expect(const TabBarTheme().splashFactory, null);
expect(const TabBarTheme().mouseCursor, null);
expect(const TabBarTheme().tabAlignment, null);
});
test('TabBarTheme lerp special cases', () {
const TabBarTheme theme = TabBarTheme();
expect(identical(TabBarTheme.lerp(theme, theme, 0.5), theme), true);
});
testWidgets('Tab bar defaults (primary)', (WidgetTester tester) async {
// Test default label color and label styles.
await tester.pumpWidget(buildTabBar(useMaterial3: true));
final ThemeData theme = ThemeData(useMaterial3: true);
final RenderParagraph selectedLabel = _getText(tester, _tab1Text);
expect(selectedLabel.text.style!.fontFamily, equals(theme.textTheme.titleSmall!.fontFamily));
expect(selectedLabel.text.style!.fontSize, equals(14.0));
expect(selectedLabel.text.style!.color, equals(theme.colorScheme.primary));
final RenderParagraph unselectedLabel = _getText(tester, _tab2Text);
expect(unselectedLabel.text.style!.fontFamily, equals(theme.textTheme.titleSmall!.fontFamily));
expect(unselectedLabel.text.style!.fontSize, equals(14.0));
expect(unselectedLabel.text.style!.color, equals(theme.colorScheme.onSurfaceVariant));
// Test default labelPadding.
await tester.pumpWidget(buildTabBar(tabs: _sizedTabs, isScrollable: true));
const double indicatorWeight = 2.0;
final Rect tabBar = tester.getRect(find.byType(TabBar));
final Rect tabOneRect = tester.getRect(find.byKey(_sizedTabs[0].key!));
final Rect tabTwoRect = tester.getRect(find.byKey(_sizedTabs[1].key!));
const double tabStartOffset = 52.0;
// Verify tabOne coordinates.
expect(tabOneRect.left, equals(kTabLabelPadding.left + tabStartOffset));
expect(tabOneRect.top, equals(kTabLabelPadding.top));
expect(tabOneRect.bottom, equals(tabBar.bottom - kTabLabelPadding.bottom - indicatorWeight));
// Verify tabTwo coordinates.
final double tabTwoRight = tabStartOffset + kTabLabelPadding.horizontal + tabOneRect.width
+ kTabLabelPadding.left + tabTwoRect.width;
expect(tabTwoRect.right, tabTwoRight);
expect(tabTwoRect.top, equals(kTabLabelPadding.top));
expect(tabTwoRect.bottom, equals(tabBar.bottom - kTabLabelPadding.bottom - indicatorWeight));
// Verify tabOne and tabTwo are separated by right padding of tabOne and left padding of tabTwo.
expect(tabOneRect.right, equals(tabTwoRect.left - kTabLabelPadding.left - kTabLabelPadding.right));
// Test default indicator & divider color.
final RenderBox tabBarBox = tester.firstRenderObject<RenderBox>(find.byType(TabBar));
expect(
tabBarBox,
paints
..line(
color: theme.colorScheme.outlineVariant,
strokeWidth: 1.0,
)
..rrect(color: theme.colorScheme.primary),
);
});
testWidgets('Tab bar defaults (secondary)', (WidgetTester tester) async {
// Test default label color and label styles.
await tester.pumpWidget(buildTabBar(secondaryTabBar: true, useMaterial3: true));
final ThemeData theme = ThemeData(useMaterial3: true);
final RenderParagraph selectedLabel = _getText(tester, _tab1Text);
expect(selectedLabel.text.style!.fontFamily, equals(theme.textTheme.titleSmall!.fontFamily));
expect(selectedLabel.text.style!.fontSize, equals(14.0));
expect(selectedLabel.text.style!.color, equals(theme.colorScheme.onSurface));
final RenderParagraph unselectedLabel = _getText(tester, _tab2Text);
expect(unselectedLabel.text.style!.fontFamily, equals(theme.textTheme.titleSmall!.fontFamily));
expect(unselectedLabel.text.style!.fontSize, equals(14.0));
expect(unselectedLabel.text.style!.color, equals(theme.colorScheme.onSurfaceVariant));
// Test default labelPadding.
await tester.pumpWidget(buildTabBar(
secondaryTabBar: true,
tabs: _sizedTabs,
isScrollable: true,
useMaterial3: true,
));
const double indicatorWeight = 2.0;
final Rect tabBar = tester.getRect(find.byType(TabBar));
final Rect tabOneRect = tester.getRect(find.byKey(_sizedTabs[0].key!));
final Rect tabTwoRect = tester.getRect(find.byKey(_sizedTabs[1].key!));
const double tabStartOffset = 52.0;
// Verify tabOne coordinates.
expect(tabOneRect.left, equals(kTabLabelPadding.left + tabStartOffset));
expect(tabOneRect.top, equals(kTabLabelPadding.top));
expect(tabOneRect.bottom, equals(tabBar.bottom - kTabLabelPadding.bottom - indicatorWeight));
// Verify tabTwo coordinates.
final double tabTwoRight = tabStartOffset + kTabLabelPadding.horizontal + tabOneRect.width
+ kTabLabelPadding.left + tabTwoRect.width;
expect(tabTwoRect.right, tabTwoRight);
expect(tabTwoRect.top, equals(kTabLabelPadding.top));
expect(tabTwoRect.bottom, equals(tabBar.bottom - kTabLabelPadding.bottom - indicatorWeight));
// Verify tabOne and tabTwo are separated by right padding of tabOne and left padding of tabTwo.
expect(tabOneRect.right, equals(tabTwoRect.left - kTabLabelPadding.left - kTabLabelPadding.right));
// Test default indicator & divider color.
final RenderBox tabBarBox = tester.firstRenderObject<RenderBox>(find.byType(TabBar));
expect(
tabBarBox,
paints
..line(
color: theme.colorScheme.outlineVariant,
strokeWidth: 1.0,
)
..line(color: theme.colorScheme.primary),
);
});
testWidgets('Tab bar theme overrides label color (selected)', (WidgetTester tester) async {
const Color labelColor = Colors.black;
const TabBarTheme tabBarTheme = TabBarTheme(labelColor: labelColor);
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme));
final RenderParagraph tabLabel = _getText(tester, _tab1Text);
expect(tabLabel.text.style!.color, equals(labelColor));
final RenderParagraph tabIcon = _getIcon(tester, Icons.looks_one);
expect(tabIcon.text.style!.color, equals(labelColor));
});
testWidgets('Tab bar theme overrides label padding', (WidgetTester tester) async {
const double topPadding = 10.0;
const double bottomPadding = 7.0;
const double rightPadding = 13.0;
const double leftPadding = 16.0;
const double indicatorWeight = 2.0; // default value
const EdgeInsetsGeometry labelPadding = EdgeInsets.fromLTRB(
leftPadding, topPadding, rightPadding, bottomPadding,
);
const TabBarTheme tabBarTheme = TabBarTheme(labelPadding: labelPadding);
await tester.pumpWidget(buildTabBar(
tabBarTheme: tabBarTheme,
tabs: _sizedTabs,
isScrollable: true,
));
final Rect tabBar = tester.getRect(find.byType(TabBar));
final Rect tabOneRect = tester.getRect(find.byKey(_sizedTabs[0].key!));
final Rect tabTwoRect = tester.getRect(find.byKey(_sizedTabs[1].key!));
// verify coordinates of tabOne
expect(tabOneRect.left, equals(leftPadding));
expect(tabOneRect.top, equals(topPadding));
expect(tabOneRect.bottom, equals(tabBar.bottom - bottomPadding - indicatorWeight));
// verify coordinates of tabTwo
expect(tabTwoRect.right, equals(tabBar.width - rightPadding));
expect(tabTwoRect.top, equals(topPadding));
expect(tabTwoRect.bottom, equals(tabBar.bottom - bottomPadding - indicatorWeight));
// verify tabOne and tabTwo are separated by right padding of tabOne and left padding of tabTwo
expect(tabOneRect.right, equals(tabTwoRect.left - leftPadding - rightPadding));
});
testWidgets('Tab bar theme overrides label styles', (WidgetTester tester) async {
const TextStyle labelStyle = TextStyle(fontFamily: 'foobar');
const TextStyle unselectedLabelStyle = TextStyle(fontFamily: 'baz');
const TabBarTheme tabBarTheme = TabBarTheme(
labelStyle: labelStyle,
unselectedLabelStyle: unselectedLabelStyle,
);
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme));
final RenderParagraph selectedLabel = _getText(tester, _tab1Text);
expect(selectedLabel.text.style!.fontFamily, equals(labelStyle.fontFamily));
final RenderParagraph unselectedLabel = _getText(tester, _tab2Text);
expect(unselectedLabel.text.style!.fontFamily, equals(unselectedLabelStyle.fontFamily));
});
testWidgets('Tab bar theme with just label style specified', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/28784
const TextStyle labelStyle = TextStyle(fontFamily: 'foobar');
const TabBarTheme tabBarTheme = TabBarTheme(
labelStyle: labelStyle,
);
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme));
final RenderParagraph selectedLabel = _getText(tester, _tab1Text);
expect(selectedLabel.text.style!.fontFamily, equals(labelStyle.fontFamily));
final RenderParagraph unselectedLabel = _getText(tester, _tab2Text);
expect(unselectedLabel.text.style!.fontFamily, equals('Roboto'));
expect(unselectedLabel.text.style!.fontSize, equals(14.0));
expect(unselectedLabel.text.style!.color, equals(Colors.white.withAlpha(0xB2)));
});
testWidgets('Tab bar label styles override theme label styles', (WidgetTester tester) async {
const TextStyle labelStyle = TextStyle(fontFamily: '1');
const TextStyle unselectedLabelStyle = TextStyle(fontFamily: '2');
const TextStyle themeLabelStyle = TextStyle(fontFamily: '3');
const TextStyle themeUnselectedLabelStyle = TextStyle(fontFamily: '4');
const TabBarTheme tabBarTheme = TabBarTheme(
labelStyle: themeLabelStyle,
unselectedLabelStyle: themeUnselectedLabelStyle,
);
final TabController controller = TabController(
length: _tabs.length,
vsync: const TestVSync(),
);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(tabBarTheme: tabBarTheme),
home: Scaffold(
body: TabBar(
tabs: _tabs,
controller: controller,
labelStyle: labelStyle,
unselectedLabelStyle: unselectedLabelStyle,
),
),
),
);
final RenderParagraph selectedLabel = _getText(tester, _tab1Text);
expect(selectedLabel.text.style!.fontFamily, equals(labelStyle.fontFamily));
final RenderParagraph unselectedLabel = _getText(tester, _tab2Text);
expect(unselectedLabel.text.style!.fontFamily, equals(unselectedLabelStyle.fontFamily));
});
testWidgets('Material2 - Tab bar label padding overrides theme label padding', (WidgetTester tester) async {
const double verticalPadding = 10.0;
const double horizontalPadding = 10.0;
const EdgeInsetsGeometry labelPadding = EdgeInsets.symmetric(
vertical: verticalPadding,
horizontal: horizontalPadding,
);
const double verticalThemePadding = 20.0;
const double horizontalThemePadding = 20.0;
const EdgeInsetsGeometry themeLabelPadding = EdgeInsets.symmetric(
vertical: verticalThemePadding,
horizontal: horizontalThemePadding,
);
const double indicatorWeight = 2.0; // default value
const TabBarTheme tabBarTheme = TabBarTheme(labelPadding: themeLabelPadding);
final TabController controller = TabController(
length: _sizedTabs.length,
vsync: const TestVSync(),
);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(tabBarTheme: tabBarTheme, useMaterial3: false),
home: Scaffold(body:
RepaintBoundary(
key: _painterKey,
child: TabBar(
tabs: _sizedTabs,
isScrollable: true,
controller: controller,
labelPadding: labelPadding,
),
),
),
),
);
final Rect tabBar = tester.getRect(find.byType(TabBar));
final Rect tabOneRect = tester.getRect(find.byKey(_sizedTabs[0].key!));
final Rect tabTwoRect = tester.getRect(find.byKey(_sizedTabs[1].key!));
// verify coordinates of tabOne
expect(tabOneRect.left, equals(horizontalPadding));
expect(tabOneRect.top, equals(verticalPadding));
expect(tabOneRect.bottom, equals(tabBar.bottom - verticalPadding - indicatorWeight));
// verify coordinates of tabTwo
expect(tabTwoRect.right, equals(tabBar.width - horizontalPadding));
expect(tabTwoRect.top, equals(verticalPadding));
expect(tabTwoRect.bottom, equals(tabBar.bottom - verticalPadding - indicatorWeight));
// verify tabOne and tabTwo are separated by 2x horizontalPadding
expect(tabOneRect.right, equals(tabTwoRect.left - (2 * horizontalPadding)));
});
testWidgets('Material3 - Tab bar label padding overrides theme label padding', (WidgetTester tester) async {
const double tabStartOffset = 52.0;
const double verticalPadding = 10.0;
const double horizontalPadding = 10.0;
const EdgeInsetsGeometry labelPadding = EdgeInsets.symmetric(
vertical: verticalPadding,
horizontal: horizontalPadding,
);
const double verticalThemePadding = 20.0;
const double horizontalThemePadding = 20.0;
const EdgeInsetsGeometry themeLabelPadding = EdgeInsets.symmetric(
vertical: verticalThemePadding,
horizontal: horizontalThemePadding,
);
const double indicatorWeight = 2.0; // default value
const TabBarTheme tabBarTheme = TabBarTheme(labelPadding: themeLabelPadding);
final TabController controller = TabController(
length: _sizedTabs.length,
vsync: const TestVSync(),
);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(tabBarTheme: tabBarTheme, useMaterial3: true),
home: Scaffold(body:
RepaintBoundary(
key: _painterKey,
child: TabBar(
tabs: _sizedTabs,
isScrollable: true,
controller: controller,
labelPadding: labelPadding,
),
),
),
),
);
final Rect tabBar = tester.getRect(find.byType(TabBar));
final Rect tabOneRect = tester.getRect(find.byKey(_sizedTabs[0].key!));
final Rect tabTwoRect = tester.getRect(find.byKey(_sizedTabs[1].key!));
// verify coordinates of tabOne
expect(tabOneRect.left, equals(horizontalPadding + tabStartOffset));
expect(tabOneRect.top, equals(verticalPadding));
expect(tabOneRect.bottom, equals(tabBar.bottom - verticalPadding - indicatorWeight));
// verify coordinates of tabTwo
expect(tabTwoRect.right, equals(tabStartOffset + horizontalThemePadding + tabOneRect.width + tabTwoRect.width + (horizontalThemePadding / 2)));
expect(tabTwoRect.top, equals(verticalPadding));
expect(tabTwoRect.bottom, equals(tabBar.bottom - verticalPadding - indicatorWeight));
// verify tabOne and tabTwo are separated by 2x horizontalPadding
expect(tabOneRect.right, equals(tabTwoRect.left - (2 * horizontalPadding)));
});
testWidgets('Tab bar theme overrides label color (unselected)', (WidgetTester tester) async {
const Color unselectedLabelColor = Colors.black;
const TabBarTheme tabBarTheme = TabBarTheme(unselectedLabelColor: unselectedLabelColor);
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme));
final RenderParagraph textRenderObject = tester.renderObject<RenderParagraph>(find.text(_tab2Text));
expect(textRenderObject.text.style!.color, equals(unselectedLabelColor));
final RenderParagraph iconRenderObject = _getIcon(tester, Icons.looks_two);
expect(iconRenderObject.text.style!.color, equals(unselectedLabelColor));
});
testWidgets('Tab bar default tab indicator size (primary)', (WidgetTester tester) async {
await tester.pumpWidget(buildTabBar(useMaterial3: true, isScrollable: true));
await expectLater(
find.byKey(_painterKey),
matchesGoldenFile('tab_bar.default.tab_indicator_size.png'),
);
});
testWidgets('Tab bar default tab indicator size (secondary)', (WidgetTester tester) async {
await tester.pumpWidget(buildTabBar(useMaterial3: true, isScrollable: true));
await expectLater(
find.byKey(_painterKey),
matchesGoldenFile('tab_bar_secondary.default.tab_indicator_size.png'),
);
});
testWidgets('Tab bar theme overrides tab indicator size (tab)', (WidgetTester tester) async {
const TabBarTheme tabBarTheme = TabBarTheme(indicatorSize: TabBarIndicatorSize.tab);
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme));
await expectLater(
find.byKey(_painterKey),
matchesGoldenFile('tab_bar_theme.tab_indicator_size_tab.png'),
);
});
testWidgets('Tab bar theme overrides tab indicator size (label)', (WidgetTester tester) async {
const TabBarTheme tabBarTheme = TabBarTheme(indicatorSize: TabBarIndicatorSize.label);
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme));
await expectLater(
find.byKey(_painterKey),
matchesGoldenFile('tab_bar_theme.tab_indicator_size_label.png'),
);
});
testWidgets('Tab bar theme overrides tab mouse cursor', (WidgetTester tester) async {
const TabBarTheme tabBarTheme = TabBarTheme(mouseCursor: MaterialStateMouseCursor.textable);
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme));
final Offset tabBar = tester.getCenter(
find.ancestor(of: find.text('tab 1'),matching: find.byType(TabBar)),
);
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer();
await gesture.moveTo(tabBar);
await tester.pumpAndSettle();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
});
testWidgets('Tab bar theme - custom tab indicator', (WidgetTester tester) async {
final TabBarTheme tabBarTheme = TabBarTheme(
indicator: BoxDecoration(
border: Border.all(),
),
);
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme));
await expectLater(
find.byKey(_painterKey),
matchesGoldenFile('tab_bar_theme.custom_tab_indicator.png'),
);
});
testWidgets('Tab bar theme - beveled rect indicator', (WidgetTester tester) async {
const TabBarTheme tabBarTheme = TabBarTheme(
indicator: ShapeDecoration(
shape: BeveledRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20.0))),
color: Colors.black,
),
);
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme));
await expectLater(
find.byKey(_painterKey),
matchesGoldenFile('tab_bar_theme.beveled_rect_indicator.png'),
);
});
testWidgets('TabAlignment.fill from TabBarTheme only supports non-scrollable tab bar', (WidgetTester tester) async {
const TabBarTheme tabBarTheme = TabBarTheme(tabAlignment: TabAlignment.fill);
// Test TabAlignment.fill from TabBarTheme with non-scrollable tab bar.
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme));
expect(tester.takeException(), isNull);
// Test TabAlignment.fill from TabBarTheme with scrollable tab bar.
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme, isScrollable: true));
expect(tester.takeException(), isAssertionError);
});
testWidgets(
'TabAlignment.start & TabAlignment.startOffset from TabBarTheme only supports scrollable tab bar',
(WidgetTester tester) async {
TabBarTheme tabBarTheme = const TabBarTheme(tabAlignment: TabAlignment.start);
// Test TabAlignment.start from TabBarTheme with scrollable tab bar.
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme, isScrollable: true));
expect(tester.takeException(), isNull);
// Test TabAlignment.start from TabBarTheme with non-scrollable tab bar.
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme));
expect(tester.takeException(), isAssertionError);
tabBarTheme = const TabBarTheme(tabAlignment: TabAlignment.startOffset);
// Test TabAlignment.startOffset from TabBarTheme with scrollable tab bar.
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme, isScrollable: true));
expect(tester.takeException(), isNull);
// Test TabAlignment.startOffset from TabBarTheme with non-scrollable tab bar.
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme));
expect(tester.takeException(), isAssertionError);
});
testWidgets('TabBarTheme.indicatorSize provides correct tab indicator (primary)', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
tabBarTheme: const TabBarTheme(indicatorSize: TabBarIndicatorSize.tab),
useMaterial3: true,
);
final List<Widget> tabs = List<Widget>.generate(4, (int index) {
return Tab(text: 'Tab $index');
});
final TabController controller = TabController(
vsync: const TestVSync(),
length: tabs.length,
);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
body: Container(
alignment: Alignment.topLeft,
child: TabBar(
controller: controller,
tabs: tabs,
),
),
),
),
);
final RenderBox tabBarBox = tester.firstRenderObject<RenderBox>(find.byType(TabBar));
expect(tabBarBox.size.height, 48.0);
const double indicatorWeight = 2.0;
const double indicatorY = 48 - (indicatorWeight / 2.0);
const double indicatorLeft = indicatorWeight / 2.0;
const double indicatorRight = 200.0 - (indicatorWeight / 2.0);
expect(
tabBarBox,
paints
// Divider.
..line(
color: theme.colorScheme.outlineVariant,
strokeWidth: 1.0,
)
// Tab indicator.
..line(
color: theme.colorScheme.primary,
strokeWidth: indicatorWeight,
p1: const Offset(indicatorLeft, indicatorY),
p2: const Offset(indicatorRight, indicatorY),
),
);
});
testWidgets('TabBarTheme.indicatorSize provides correct tab indicator (secondary)', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
tabBarTheme: const TabBarTheme(indicatorSize: TabBarIndicatorSize.label),
useMaterial3: true,
);
final List<Widget> tabs = List<Widget>.generate(4, (int index) {
return Tab(text: 'Tab $index');
});
final TabController controller = TabController(
vsync: const TestVSync(),
length: tabs.length,
);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
body: Container(
alignment: Alignment.topLeft,
child: TabBar.secondary(
controller: controller,
tabs: tabs,
),
),
),
),
);
final RenderBox tabBarBox = tester.firstRenderObject<RenderBox>(find.byType(TabBar));
expect(tabBarBox.size.height, 48.0);
const double indicatorWeight = 2.0;
const double indicatorY = 48 - (indicatorWeight / 2.0);
expect(
tabBarBox,
paints
// Divider.
..line(
color: theme.colorScheme.outlineVariant,
strokeWidth: 1.0,
)
// Tab indicator
..line(
color: theme.colorScheme.primary,
strokeWidth: indicatorWeight,
p1: const Offset(65.75, indicatorY),
p2: const Offset(134.25, indicatorY),
),
);
});
testWidgets('TabBar divider can use TabBarTheme.dividerColor & TabBarTheme.dividerHeight', (WidgetTester tester) async {
const Color dividerColor = Color(0xff00ff00);
const double dividerHeight = 10.0;
final TabController controller = TabController(
length: 3,
vsync: const TestVSync(),
);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
tabBarTheme: const TabBarTheme(
dividerColor: dividerColor,
dividerHeight: dividerHeight,
),
useMaterial3: true,
),
home: Scaffold(
appBar: AppBar(
bottom: TabBar(
controller: controller,
tabs: const <Widget>[
Tab(text: 'Tab 1'),
Tab(text: 'Tab 2'),
Tab(text: 'Tab 3'),
],
),
),
),
),
);
final RenderBox tabBarBox = tester.firstRenderObject<RenderBox>(find.byType(TabBar));
// Test divider color.
expect(tabBarBox, paints..line(color: dividerColor, strokeWidth: dividerHeight));
});
testWidgets('dividerColor & dividerHeight overrides TabBarTheme.dividerColor', (WidgetTester tester) async {
const Color dividerColor = Color(0xff0000ff);
const double dividerHeight = 8.0;
final TabController controller = TabController(
length: 3,
vsync: const TestVSync(),
);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
useMaterial3: true,
tabBarTheme: const TabBarTheme(
dividerColor: Colors.pink,
dividerHeight: 5.0,
),
),
home: Scaffold(
appBar: AppBar(
bottom: TabBar(
dividerColor: dividerColor,
dividerHeight: dividerHeight,
controller: controller,
tabs: const <Widget>[
Tab(text: 'Tab 1'),
Tab(text: 'Tab 2'),
Tab(text: 'Tab 3'),
],
),
),
),
),
);
final RenderBox tabBarBox = tester.firstRenderObject<RenderBox>(find.byType(TabBar));
// Test divider color.
expect(tabBarBox, paints..line(color: dividerColor, strokeWidth: dividerHeight));
});
testWidgets('TabBar respects TabBarTheme.tabAlignment', (WidgetTester tester) async {
final TabController controller1 = TabController(
length: 2,
vsync: const TestVSync(),
);
addTearDown(controller1.dispose);
// Test non-scrollable tab bar.
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
tabBarTheme: const TabBarTheme(tabAlignment: TabAlignment.center),
useMaterial3: true,
),
home: Scaffold(
appBar: AppBar(
bottom: TabBar(
controller: controller1,
tabs: const <Widget>[
Tab(text: 'Tab 1'),
Tab(text: 'Tab 3'),
],
),
),
),
),
);
const double availableWidth = 800.0;
Rect tabOneRect = tester.getRect(find.byType(Tab).first);
Rect tabTwoRect = tester.getRect(find.byType(Tab).last);
double tabOneLeft = (availableWidth / 2) - tabOneRect.width - kTabLabelPadding.left;
expect(tabOneRect.left, equals(tabOneLeft));
double tabTwoRight = (availableWidth / 2) + tabTwoRect.width + kTabLabelPadding.right;
expect(tabTwoRect.right, equals(tabTwoRight));
final TabController controller2 = TabController(
length: 2,
vsync: const TestVSync(),
);
addTearDown(controller2.dispose);
// Test scrollable tab bar.
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
tabBarTheme: const TabBarTheme(tabAlignment: TabAlignment.start),
useMaterial3: true,
),
home: Scaffold(
appBar: AppBar(
bottom: TabBar(
isScrollable: true,
controller: controller2,
tabs: const <Widget>[
Tab(text: 'Tab 1'),
Tab(text: 'Tab 3'),
],
),
),
),
),
);
await tester.pumpAndSettle();
tabOneRect = tester.getRect(find.byType(Tab).first);
tabTwoRect = tester.getRect(find.byType(Tab).last);
tabOneLeft = kTabLabelPadding.left;
expect(tabOneRect.left, equals(tabOneLeft));
tabTwoRight = kTabLabelPadding.horizontal + tabOneRect.width + kTabLabelPadding.left + tabTwoRect.width;
expect(tabTwoRect.right, equals(tabTwoRight));
});
testWidgets('TabBar.tabAlignment overrides TabBarTheme.tabAlignment', (WidgetTester tester) async {
final TabController controller1 = TabController(
length: 2,
vsync: const TestVSync(),
);
addTearDown(controller1.dispose);
/// Test non-scrollable tab bar.
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
tabBarTheme: const TabBarTheme(tabAlignment: TabAlignment.fill),
useMaterial3: true,
),
home: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabAlignment: TabAlignment.center,
controller: controller1,
tabs: const <Widget>[
Tab(text: 'Tab 1'),
Tab(text: 'Tab 3'),
],
),
),
),
),
);
const double availableWidth = 800.0;
Rect tabOneRect = tester.getRect(find.byType(Tab).first);
Rect tabTwoRect = tester.getRect(find.byType(Tab).last);
double tabOneLeft = (availableWidth / 2) - tabOneRect.width - kTabLabelPadding.left;
expect(tabOneRect.left, equals(tabOneLeft));
double tabTwoRight = (availableWidth / 2) + tabTwoRect.width + kTabLabelPadding.right;
expect(tabTwoRect.right, equals(tabTwoRight));
final TabController controller2 = TabController(
length: 2,
vsync: const TestVSync(),
);
addTearDown(controller2.dispose);
/// Test scrollable tab bar.
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
tabBarTheme: const TabBarTheme(tabAlignment: TabAlignment.center),
useMaterial3: true,
),
home: Scaffold(
appBar: AppBar(
bottom: TabBar(
isScrollable: true,
tabAlignment: TabAlignment.start,
controller: controller2,
tabs: const <Widget>[
Tab(text: 'Tab 1'),
Tab(text: 'Tab 3'),
],
),
),
),
),
);
await tester.pumpAndSettle();
tabOneRect = tester.getRect(find.byType(Tab).first);
tabTwoRect = tester.getRect(find.byType(Tab).last);
tabOneLeft = kTabLabelPadding.left;
expect(tabOneRect.left, equals(tabOneLeft));
tabTwoRight = kTabLabelPadding.horizontal + tabOneRect.width + kTabLabelPadding.left + tabTwoRect.width;
expect(tabTwoRect.right, equals(tabTwoRight));
});
testWidgets(
'TabBar labels use colors from TabBarTheme.labelStyle & TabBarTheme.unselectedLabelStyle',
(WidgetTester tester) async {
const TextStyle labelStyle = TextStyle(
color: Color(0xff0000ff),
fontStyle: FontStyle.italic,
);
const TextStyle unselectedLabelStyle = TextStyle(
color: Color(0x950000ff),
fontStyle: FontStyle.italic,
);
const TabBarTheme tabBarTheme = TabBarTheme(
labelStyle: labelStyle,
unselectedLabelStyle: unselectedLabelStyle,
);
// Test tab bar with TabBarTheme labelStyle & unselectedLabelStyle.
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme));
final IconThemeData selectedTabIcon = IconTheme.of(tester.element(find.text(_tab1Text)));
final IconThemeData unselectedTabIcon = IconTheme.of(tester.element(find.text(_tab2Text)));
final TextStyle selectedTextStyle = tester.renderObject<RenderParagraph>(find.text(_tab1Text))
.text.style!;
final TextStyle unselectedTextStyle = tester.renderObject<RenderParagraph>(find.text(_tab2Text))
.text.style!;
// Selected tab should use labelStyle color.
expect(selectedTabIcon.color, labelStyle.color);
expect(selectedTextStyle.color, labelStyle.color);
expect(selectedTextStyle.fontStyle, labelStyle.fontStyle);
// Unselected tab should use unselectedLabelStyle color.
expect(unselectedTabIcon.color, unselectedLabelStyle.color);
expect(unselectedTextStyle.color, unselectedLabelStyle.color);
expect(unselectedTextStyle.fontStyle, unselectedLabelStyle.fontStyle);
});
testWidgets(
"TabBarTheme's labelColor & unselectedLabelColor override labelStyle & unselectedLabelStyle colors",
(WidgetTester tester) async {
const Color labelColor = Color(0xfff00000);
const Color unselectedLabelColor = Color(0x95ff0000);
const TextStyle labelStyle = TextStyle(
color: Color(0xff0000ff),
fontStyle: FontStyle.italic,
);
const TextStyle unselectedLabelStyle = TextStyle(
color: Color(0x950000ff),
fontStyle: FontStyle.italic,
);
TabBarTheme tabBarTheme = const TabBarTheme(
labelStyle: labelStyle,
unselectedLabelStyle: unselectedLabelStyle,
);
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme));
// Test tab bar with TabBarTheme labelStyle & unselectedLabelStyle.
await tester.pumpWidget(buildTabBar());
IconThemeData selectedTabIcon = IconTheme.of(tester.element(find.text(_tab1Text)));
IconThemeData unselectedTabIcon = IconTheme.of(tester.element(find.text(_tab2Text)));
TextStyle selectedTextStyle = tester.renderObject<RenderParagraph>(find.text(_tab1Text))
.text.style!;
TextStyle unselectedTextStyle = tester.renderObject<RenderParagraph>(find.text(_tab2Text))
.text.style!;
// Selected tab should use the labelStyle color.
expect(selectedTabIcon.color, labelStyle.color);
expect(selectedTextStyle.color, labelStyle.color);
expect(selectedTextStyle.fontStyle, labelStyle.fontStyle);
// Unselected tab should use the unselectedLabelStyle color.
expect(unselectedTabIcon.color, unselectedLabelStyle.color);
expect(unselectedTextStyle.color, unselectedLabelStyle.color);
expect(unselectedTextStyle.fontStyle, unselectedLabelStyle.fontStyle);
// Update the TabBarTheme with labelColor & unselectedLabelColor.
tabBarTheme = const TabBarTheme(
labelColor: labelColor,
unselectedLabelColor: unselectedLabelColor,
labelStyle: labelStyle,
unselectedLabelStyle: unselectedLabelStyle,
);
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme));
await tester.pumpAndSettle();
selectedTabIcon = IconTheme.of(tester.element(find.text(_tab1Text)));
unselectedTabIcon = IconTheme.of(tester.element(find.text(_tab2Text)));
selectedTextStyle = tester.renderObject<RenderParagraph>(find.text(_tab1Text)).text.style!;
unselectedTextStyle = tester.renderObject<RenderParagraph>(find.text(_tab2Text)).text.style!;
// Selected tab should use the labelColor.
expect(selectedTabIcon.color, labelColor);
expect(selectedTextStyle.color, labelColor);
expect(selectedTextStyle.fontStyle, labelStyle.fontStyle);
// Unselected tab should use the unselectedLabelColor.
expect(unselectedTabIcon.color, unselectedLabelColor);
expect(unselectedTextStyle.color, unselectedLabelColor);
expect(unselectedTextStyle.fontStyle, unselectedLabelStyle.fontStyle);
});
testWidgets(
"TabBarTheme's labelColor & unselectedLabelColor override TabBar.labelStyle & TabBar.unselectedLabelStyle colors",
(WidgetTester tester) async {
const Color labelColor = Color(0xfff00000);
const Color unselectedLabelColor = Color(0x95ff0000);
const TextStyle labelStyle = TextStyle(
color: Color(0xff0000ff),
fontStyle: FontStyle.italic,
);
const TextStyle unselectedLabelStyle = TextStyle(
color: Color(0x950000ff),
fontStyle: FontStyle.italic,
);
Widget buildTabBar({TabBarTheme? tabBarTheme}) {
return MaterialApp(
theme: ThemeData(tabBarTheme: tabBarTheme),
home: const Material(
child: DefaultTabController(
length: 2,
child: TabBar(
labelStyle: labelStyle,
unselectedLabelStyle: unselectedLabelStyle,
tabs: <Widget>[
Tab(text: _tab1Text),
Tab(text: _tab2Text),
],
),
),
),
);
}
// Test tab bar with [TabBar.labelStyle] & [TabBar.unselectedLabelStyle].
await tester.pumpWidget(buildTabBar());
IconThemeData selectedTabIcon = IconTheme.of(tester.element(find.text(_tab1Text)));
IconThemeData unselectedTabIcon = IconTheme.of(tester.element(find.text(_tab2Text)));
TextStyle selectedTextStyle = tester.renderObject<RenderParagraph>(find.text(_tab1Text))
.text.style!;
TextStyle unselectedTextStyle = tester.renderObject<RenderParagraph>(find.text(_tab2Text))
.text.style!;
// Selected tab should use the [TabBar.labelStyle] color.
expect(selectedTabIcon.color, labelStyle.color);
expect(selectedTextStyle.color, labelStyle.color);
expect(selectedTextStyle.fontStyle, labelStyle.fontStyle);
// Unselected tab should use the [TabBar.unselectedLabelStyle] color.
expect(unselectedTabIcon.color, unselectedLabelStyle.color);
expect(unselectedTextStyle.color, unselectedLabelStyle.color);
expect(unselectedTextStyle.fontStyle, unselectedLabelStyle.fontStyle);
// Add TabBarTheme with labelColor & unselectedLabelColor.
await tester.pumpWidget(buildTabBar(tabBarTheme: const TabBarTheme(
labelColor: labelColor,
unselectedLabelColor: unselectedLabelColor,
)));
await tester.pumpAndSettle();
selectedTabIcon = IconTheme.of(tester.element(find.text(_tab1Text)));
unselectedTabIcon = IconTheme.of(tester.element(find.text(_tab2Text)));
selectedTextStyle = tester.renderObject<RenderParagraph>(find.text(_tab1Text)).text.style!;
unselectedTextStyle = tester.renderObject<RenderParagraph>(find.text(_tab2Text)).text.style!;
// Selected tab should use the [TabBarTheme.labelColor].
expect(selectedTabIcon.color, labelColor);
expect(selectedTextStyle.color, labelColor);
expect(selectedTextStyle.fontStyle, labelStyle.fontStyle);
// Unselected tab should use the [TabBarTheme.unselectedLabelColor].
expect(unselectedTabIcon.color, unselectedLabelColor);
expect(unselectedTextStyle.color, unselectedLabelColor);
expect(unselectedTextStyle.fontStyle, unselectedLabelStyle.fontStyle);
});
group('Material 2', () {
// These tests are only relevant for Material 2. Once Material 2
// support is deprecated and the APIs are removed, these tests
// can be deleted.
testWidgets('Tab bar defaults (primary)', (WidgetTester tester) async {
// Test default label color and label styles.
await tester.pumpWidget(buildTabBar());
final ThemeData theme = ThemeData(useMaterial3: false);
final RenderParagraph selectedLabel = _getText(tester, _tab1Text);
expect(selectedLabel.text.style!.fontFamily, equals('Roboto'));
expect(selectedLabel.text.style!.fontSize, equals(14.0));
expect(selectedLabel.text.style!.color, equals(Colors.white));
final RenderParagraph unselectedLabel = _getText(tester, _tab2Text);
expect(unselectedLabel.text.style!.fontFamily, equals('Roboto'));
expect(unselectedLabel.text.style!.fontSize, equals(14.0));
expect(unselectedLabel.text.style!.color, equals(Colors.white.withAlpha(0xB2)));
// Test default labelPadding.
await tester.pumpWidget(buildTabBar(tabs: _sizedTabs, isScrollable: true));
const double indicatorWeight = 2.0;
final Rect tabBar = tester.getRect(find.byType(TabBar));
final Rect tabOneRect = tester.getRect(find.byKey(_sizedTabs[0].key!));
final Rect tabTwoRect = tester.getRect(find.byKey(_sizedTabs[1].key!));
// Verify tabOne coordinates.
expect(tabOneRect.left, equals(kTabLabelPadding.left));
expect(tabOneRect.top, equals(kTabLabelPadding.top));
expect(tabOneRect.bottom, equals(tabBar.bottom - kTabLabelPadding.bottom - indicatorWeight));
// Verify tabTwo coordinates.
expect(tabTwoRect.right, equals(tabBar.width - kTabLabelPadding.right));
expect(tabTwoRect.top, equals(kTabLabelPadding.top));
expect(tabTwoRect.bottom, equals(tabBar.bottom - kTabLabelPadding.bottom - indicatorWeight));
// Verify tabOne and tabTwo is separated by right padding of tabOne and left padding of tabTwo.
expect(tabOneRect.right, equals(tabTwoRect.left - kTabLabelPadding.left - kTabLabelPadding.right));
// Test default indicator color.
final RenderBox tabBarBox = tester.firstRenderObject<RenderBox>(find.byType(TabBar));
expect(tabBarBox, paints..line(color: theme.indicatorColor));
});
testWidgets('Tab bar defaults (secondary)', (WidgetTester tester) async {
// Test default label color and label styles.
await tester.pumpWidget(buildTabBar(secondaryTabBar: true));
final ThemeData theme = ThemeData(useMaterial3: false);
final RenderParagraph selectedLabel = _getText(tester, _tab1Text);
expect(selectedLabel.text.style!.fontFamily, equals('Roboto'));
expect(selectedLabel.text.style!.fontSize, equals(14.0));
expect(selectedLabel.text.style!.color, equals(Colors.white));
final RenderParagraph unselectedLabel = _getText(tester, _tab2Text);
expect(unselectedLabel.text.style!.fontFamily, equals('Roboto'));
expect(unselectedLabel.text.style!.fontSize, equals(14.0));
expect(unselectedLabel.text.style!.color, equals(Colors.white.withAlpha(0xB2)));
// Test default labelPadding.
await tester.pumpWidget(buildTabBar(tabs: _sizedTabs, isScrollable: true));
const double indicatorWeight = 2.0;
final Rect tabBar = tester.getRect(find.byType(TabBar));
final Rect tabOneRect = tester.getRect(find.byKey(_sizedTabs[0].key!));
final Rect tabTwoRect = tester.getRect(find.byKey(_sizedTabs[1].key!));
// Verify tabOne coordinates.
expect(tabOneRect.left, equals(kTabLabelPadding.left));
expect(tabOneRect.top, equals(kTabLabelPadding.top));
expect(tabOneRect.bottom, equals(tabBar.bottom - kTabLabelPadding.bottom - indicatorWeight));
// Verify tabTwo coordinates.
expect(tabTwoRect.right, equals(tabBar.width - kTabLabelPadding.right));
expect(tabTwoRect.top, equals(kTabLabelPadding.top));
expect(tabTwoRect.bottom, equals(tabBar.bottom - kTabLabelPadding.bottom - indicatorWeight));
// Verify tabOne and tabTwo are separated by right padding of tabOne and left padding of tabTwo.
expect(tabOneRect.right, equals(tabTwoRect.left - kTabLabelPadding.left - kTabLabelPadding.right));
// Test default indicator color.
final RenderBox tabBarBox = tester.firstRenderObject<RenderBox>(find.byType(TabBar));
expect(tabBarBox, paints..line(color: theme.indicatorColor));
});
testWidgets('Tab bar default tab indicator size', (WidgetTester tester) async {
await tester.pumpWidget(buildTabBar());
await expectLater(
find.byKey(_painterKey),
matchesGoldenFile('tab_bar.m2.default.tab_indicator_size.png'),
);
});
testWidgets('TabBarTheme.indicatorSize provides correct tab indicator (primary)', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
tabBarTheme: const TabBarTheme(indicatorSize: TabBarIndicatorSize.tab),
useMaterial3: false,
);
final List<Widget> tabs = List<Widget>.generate(4, (int index) {
return Tab(text: 'Tab $index');
});
final TabController controller = TabController(
vsync: const TestVSync(),
length: tabs.length,
);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
body: Container(
alignment: Alignment.topLeft,
child: TabBar(
controller: controller,
tabs: tabs,
),
),
),
),
);
final RenderBox tabBarBox = tester.firstRenderObject<RenderBox>(find.byType(TabBar));
expect(tabBarBox.size.height, 48.0);
const double indicatorWeight = 2.0;
const double indicatorY = 48 - (indicatorWeight / 2.0);
const double indicatorLeft = indicatorWeight / 2.0;
const double indicatorRight = 200.0 - (indicatorWeight / 2.0);
expect(
tabBarBox,
paints
// Tab indicator
..line(
color: theme.indicatorColor,
strokeWidth: indicatorWeight,
p1: const Offset(indicatorLeft, indicatorY),
p2: const Offset(indicatorRight, indicatorY),
),
);
});
testWidgets('TabBarTheme.indicatorSize provides correct tab indicator (secondary)', (WidgetTester tester) async {
final ThemeData theme = ThemeData(
tabBarTheme: const TabBarTheme(indicatorSize: TabBarIndicatorSize.label),
useMaterial3: false,
);
final List<Widget> tabs = List<Widget>.generate(4, (int index) {
return Tab(text: 'Tab $index');
});
final TabController controller = TabController(
vsync: const TestVSync(),
length: tabs.length,
);
addTearDown(controller.dispose);
await tester.pumpWidget(
MaterialApp(
theme: theme,
home: Scaffold(
body: Container(
alignment: Alignment.topLeft,
child: TabBar.secondary(
controller: controller,
tabs: tabs,
),
),
),
),
);
final RenderBox tabBarBox = tester.firstRenderObject<RenderBox>(find.byType(TabBar));
expect(tabBarBox.size.height, 48.0);
const double indicatorWeight = 2.0;
const double indicatorY = 48 - (indicatorWeight / 2.0);
expect(
tabBarBox,
paints
// Tab indicator
..line(
color: theme.indicatorColor,
strokeWidth: indicatorWeight,
p1: const Offset(66.0, indicatorY),
p2: const Offset(134.0, indicatorY),
),
);
});
testWidgets('TabBar respects TabBarTheme.tabAlignment', (WidgetTester tester) async {
final TabController controller = TabController(
length: 2,
vsync: const TestVSync(),
);
addTearDown(controller.dispose);
// Test non-scrollable tab bar.
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
tabBarTheme: const TabBarTheme(tabAlignment: TabAlignment.center),
useMaterial3: false,
),
home: Scaffold(
appBar: AppBar(
bottom: TabBar(
controller: controller,
tabs: const <Widget>[
Tab(text: 'Tab 1'),
Tab(text: 'Tab 3'),
],
),
),
),
),
);
final Rect tabOneRect = tester.getRect(find.byType(Tab).first);
final Rect tabTwoRect = tester.getRect(find.byType(Tab).last);
final double tabOneLeft = (800 / 2) - tabOneRect.width - kTabLabelPadding.left;
expect(tabOneRect.left, equals(tabOneLeft));
final double tabTwoRight = (800 / 2) + tabTwoRect.width + kTabLabelPadding.right;
expect(tabTwoRect.right, equals(tabTwoRight));
});
testWidgets('TabBar.tabAlignment overrides TabBarTheme.tabAlignment', (WidgetTester tester) async {
final TabController controller = TabController(
length: 2,
vsync: const TestVSync(),
);
addTearDown(controller.dispose);
// Test non-scrollable tab bar.
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
tabBarTheme: const TabBarTheme(tabAlignment: TabAlignment.fill),
useMaterial3: false,
),
home: Scaffold(
appBar: AppBar(
bottom: TabBar(
tabAlignment: TabAlignment.center,
controller: controller,
tabs: const <Widget>[
Tab(text: 'Tab 1'),
Tab(text: 'Tab 3'),
],
),
),
),
),
);
final Rect tabOneRect = tester.getRect(find.byType(Tab).first);
final Rect tabTwoRect = tester.getRect(find.byType(Tab).last);
final double tabOneLeft = (800 / 2) - tabOneRect.width - kTabLabelPadding.left;
expect(tabOneRect.left, equals(tabOneLeft));
final double tabTwoRight = (800 / 2) + tabTwoRect.width + kTabLabelPadding.right;
expect(tabTwoRect.right, equals(tabTwoRight));
});
});
testWidgets('Material3 - TabBar indicator respects TabBarTheme.indicatorColor', (WidgetTester tester) async {
final List<Widget> tabs = List<Widget>.generate(4, (int index) {
return Tab(text: 'Tab $index');
});
final TabController controller = TabController(
vsync: const TestVSync(),
length: tabs.length,
);
addTearDown(controller.dispose);
const Color tabBarThemeIndicatorColor = Color(0xffff0000);
Widget buildTabBar({ required ThemeData theme }) {
return MaterialApp(
theme: theme,
home: Material(
child: Container(
alignment: Alignment.topLeft,
child: TabBar(
controller: controller,
tabs: tabs,
),
),
),
);
}
await tester.pumpWidget(buildTabBar(theme: ThemeData(useMaterial3: true)));
RenderBox tabBarBox = tester.firstRenderObject<RenderBox>(find.byType(TabBar));
expect(tabBarBox,paints..rrect(color: ThemeData(useMaterial3: true).colorScheme.primary));
await tester.pumpWidget(buildTabBar(theme: ThemeData(
useMaterial3: true,
tabBarTheme: const TabBarTheme(indicatorColor: tabBarThemeIndicatorColor)
)));
await tester.pumpAndSettle();
tabBarBox = tester.firstRenderObject<RenderBox>(find.byType(TabBar));
expect(tabBarBox,paints..rrect(color: tabBarThemeIndicatorColor));
});
testWidgets('Material2 - TabBar indicator respects TabBarTheme.indicatorColor', (WidgetTester tester) async {
final List<Widget> tabs = List<Widget>.generate(4, (int index) {
return Tab(text: 'Tab $index');
});
final TabController controller = TabController(
vsync: const TestVSync(),
length: tabs.length,
);
addTearDown(controller.dispose);
const Color themeIndicatorColor = Color(0xffff0000);
const Color tabBarThemeIndicatorColor = Color(0xffffff00);
Widget buildTabBar({ Color? themeIndicatorColor, Color? tabBarThemeIndicatorColor }) {
return MaterialApp(
theme: ThemeData(
indicatorColor: themeIndicatorColor,
tabBarTheme: TabBarTheme(indicatorColor: tabBarThemeIndicatorColor),
useMaterial3: false,
),
home: Material(
child: Container(
alignment: Alignment.topLeft,
child: TabBar(
controller: controller,
tabs: tabs,
),
),
),
);
}
await tester.pumpWidget(buildTabBar(themeIndicatorColor: themeIndicatorColor));
RenderBox tabBarBox = tester.firstRenderObject<RenderBox>(find.byType(TabBar));
expect(tabBarBox,paints..line(color: themeIndicatorColor));
await tester.pumpWidget(buildTabBar(tabBarThemeIndicatorColor: tabBarThemeIndicatorColor));
await tester.pumpAndSettle();
tabBarBox = tester.firstRenderObject<RenderBox>(find.byType(TabBar));
expect(tabBarBox,paints..line(color: tabBarThemeIndicatorColor));
});
testWidgets('TabBarTheme.labelColor resolves material states', (WidgetTester tester) async {
const Color selectedColor = Color(0xff00ff00);
const Color unselectedColor = Color(0xffff0000);
final MaterialStateColor labelColor = MaterialStateColor.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return selectedColor;
}
return unselectedColor;
});
final TabBarTheme tabBarTheme = TabBarTheme(labelColor: labelColor);
// Test labelColor correctly resolves material states.
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme));
final IconThemeData selectedTabIcon = IconTheme.of(tester.element(find.text(_tab1Text)));
final IconThemeData unselectedTabIcon = IconTheme.of(tester.element(find.text(_tab2Text)));
final TextStyle selectedTextStyle = tester.renderObject<RenderParagraph>(find.text(_tab1Text)).text.style!;
final TextStyle unselectedTextStyle = tester.renderObject<RenderParagraph>(find.text(_tab2Text)).text.style!;
expect(selectedTabIcon.color, selectedColor);
expect(unselectedTabIcon.color, unselectedColor);
expect(selectedTextStyle.color, selectedColor);
expect(unselectedTextStyle.color, unselectedColor);
});
testWidgets('TabBarTheme.labelColor & TabBarTheme.unselectedLabelColor override material state TabBarTheme.labelColor',
(WidgetTester tester) async {
const Color selectedStateColor = Color(0xff00ff00);
const Color unselectedStateColor = Color(0xffff0000);
final MaterialStateColor labelColor = MaterialStateColor.resolveWith((Set<MaterialState> states) {
if (states.contains(MaterialState.selected)) {
return selectedStateColor;
}
return unselectedStateColor;
});
const Color selectedColor = Color(0xff00ffff);
const Color unselectedColor = Color(0xffff12ff);
TabBarTheme tabBarTheme = TabBarTheme(labelColor: labelColor);
// Test material state label color.
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme));
IconThemeData selectedTabIcon = IconTheme.of(tester.element(find.text(_tab1Text)));
IconThemeData unselectedTabIcon = IconTheme.of(tester.element(find.text(_tab2Text)));
TextStyle selectedTextStyle = tester.renderObject<RenderParagraph>(find.text(_tab1Text)).text.style!;
TextStyle unselectedTextStyle = tester.renderObject<RenderParagraph>(find.text(_tab2Text)).text.style!;
expect(selectedTabIcon.color, selectedStateColor);
expect(unselectedTabIcon.color, unselectedStateColor);
expect(selectedTextStyle.color, selectedStateColor);
expect(unselectedTextStyle.color, unselectedStateColor);
// Test labelColor & unselectedLabelColor override material state labelColor.
tabBarTheme = const TabBarTheme(
labelColor: selectedColor,
unselectedLabelColor: unselectedColor,
);
await tester.pumpWidget(buildTabBar(tabBarTheme: tabBarTheme));
await tester.pumpAndSettle();
selectedTabIcon = IconTheme.of(tester.element(find.text(_tab1Text)));
unselectedTabIcon = IconTheme.of(tester.element(find.text(_tab2Text)));
selectedTextStyle = tester.renderObject<RenderParagraph>(find.text(_tab1Text)).text.style!;
unselectedTextStyle = tester.renderObject<RenderParagraph>(find.text(_tab2Text)).text.style!;
expect(selectedTabIcon.color, selectedColor);
expect(unselectedTabIcon.color, unselectedColor);
expect(selectedTextStyle.color, selectedColor);
expect(unselectedTextStyle.color, unselectedColor);
});
}
| flutter/packages/flutter/test/material/tab_bar_theme_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/tab_bar_theme_test.dart",
"repo_id": "flutter",
"token_count": 22619
} | 668 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import '../widgets/editable_text_utils.dart' show textOffsetToPosition;
const double _kToolbarContentDistance = 8.0;
// A custom text selection menu that just displays a single custom button.
class _CustomMaterialTextSelectionControls extends MaterialTextSelectionControls {
@override
Widget buildToolbar(
BuildContext context,
Rect globalEditableRegion,
double textLineHeight,
Offset selectionMidpoint,
List<TextSelectionPoint> endpoints,
TextSelectionDelegate delegate,
ValueListenable<ClipboardStatus>? clipboardStatus,
Offset? lastSecondaryTapDownPosition,
) {
final TextSelectionPoint startTextSelectionPoint = endpoints[0];
final TextSelectionPoint endTextSelectionPoint = endpoints.length > 1
? endpoints[1]
: endpoints[0];
final Offset anchorAbove = Offset(
globalEditableRegion.left + selectionMidpoint.dx,
globalEditableRegion.top + startTextSelectionPoint.point.dy - textLineHeight - _kToolbarContentDistance,
);
final Offset anchorBelow = Offset(
globalEditableRegion.left + selectionMidpoint.dx,
globalEditableRegion.top + endTextSelectionPoint.point.dy + TextSelectionToolbar.kToolbarContentDistanceBelow,
);
return TextSelectionToolbar(
anchorAbove: anchorAbove,
anchorBelow: anchorBelow,
children: <Widget>[
TextSelectionToolbarTextButton(
padding: TextSelectionToolbarTextButton.getPadding(0, 1),
onPressed: () {},
child: const Text('Custom button'),
),
],
);
}
}
class TestBox extends SizedBox {
const TestBox({super.key}) : super(width: itemWidth, height: itemHeight);
static const double itemHeight = 44.0;
static const double itemWidth = 100.0;
}
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
// Find by a runtimeType String, including private types.
Finder findPrivate(String type) {
return find.descendant(
of: find.byType(MaterialApp),
matching: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == type),
);
}
// Finding TextSelectionToolbar won't give you the position as the user sees
// it because it's a full-sized Stack at the top level. This method finds the
// visible part of the toolbar for use in measurements.
Finder findToolbar() => findPrivate('_TextSelectionToolbarOverflowable');
Finder findOverflowButton() => findPrivate('_TextSelectionToolbarOverflowButton');
testWidgets('puts children in an overflow menu if they overflow', (WidgetTester tester) async {
late StateSetter setState;
final List<Widget> children = List<Widget>.generate(7, (int i) => const TestBox());
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: StatefulBuilder(
builder: (BuildContext context, StateSetter setter) {
setState = setter;
return TextSelectionToolbar(
anchorAbove: const Offset(50.0, 100.0),
anchorBelow: const Offset(50.0, 200.0),
children: children,
);
},
),
),
),
);
// All children fit on the screen, so they are all rendered.
expect(find.byType(TestBox), findsNWidgets(children.length));
expect(findOverflowButton(), findsNothing);
// Adding one more child makes the children overflow.
setState(() {
children.add(
const TestBox(),
);
});
await tester.pumpAndSettle();
expect(find.byType(TestBox), findsNWidgets(children.length - 1));
expect(findOverflowButton(), findsOneWidget);
// Tap the overflow button to show the overflow menu.
await tester.tap(findOverflowButton());
await tester.pumpAndSettle();
expect(find.byType(TestBox), findsNWidgets(1));
expect(findOverflowButton(), findsOneWidget);
// Tap the overflow button again to hide the overflow menu.
await tester.tap(findOverflowButton());
await tester.pumpAndSettle();
expect(find.byType(TestBox), findsNWidgets(children.length - 1));
expect(findOverflowButton(), findsOneWidget);
});
testWidgets('positions itself at anchorAbove if it fits', (WidgetTester tester) async {
late StateSetter setState;
const double height = 44.0;
const double anchorBelowY = 500.0;
double anchorAboveY = 0.0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: StatefulBuilder(
builder: (BuildContext context, StateSetter setter) {
setState = setter;
return TextSelectionToolbar(
anchorAbove: Offset(50.0, anchorAboveY),
anchorBelow: const Offset(50.0, anchorBelowY),
children: <Widget>[
Container(color: Colors.red, width: 50.0, height: height),
Container(color: Colors.green, width: 50.0, height: height),
Container(color: Colors.blue, width: 50.0, height: height),
],
);
},
),
),
),
);
// When the toolbar doesn't fit above aboveAnchor, it positions itself below
// belowAnchor.
double toolbarY = tester.getTopLeft(findToolbar()).dy;
expect(toolbarY, equals(anchorBelowY + TextSelectionToolbar.kToolbarContentDistanceBelow));
// Even when it barely doesn't fit.
setState(() {
anchorAboveY = 60.0;
});
await tester.pump();
toolbarY = tester.getTopLeft(findToolbar()).dy;
expect(toolbarY, equals(anchorBelowY + TextSelectionToolbar.kToolbarContentDistanceBelow));
// When it does fit above aboveAnchor, it positions itself there.
setState(() {
anchorAboveY = 70.0;
});
await tester.pump();
toolbarY = tester.getTopLeft(findToolbar()).dy;
expect(toolbarY, equals(anchorAboveY - height - _kToolbarContentDistance));
});
testWidgets('can create and use a custom toolbar', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: SelectableText(
'Select me custom menu',
selectionControls: _CustomMaterialTextSelectionControls(),
),
),
),
),
);
// The selection menu is not initially shown.
expect(find.text('Custom button'), findsNothing);
// Long press on "custom" to select it.
final Offset customPos = textOffsetToPosition(tester, 11);
final TestGesture gesture = await tester.startGesture(customPos, pointer: 7);
await tester.pump(const Duration(seconds: 2));
await gesture.up();
await tester.pump();
// The custom selection menu is shown.
expect(find.text('Custom button'), findsOneWidget);
expect(find.text('Cut'), findsNothing);
expect(find.text('Copy'), findsNothing);
expect(find.text('Paste'), findsNothing);
expect(find.text('Select all'), findsNothing);
}, skip: kIsWeb); // [intended] We don't show the toolbar on the web.
for (final ColorScheme colorScheme in <ColorScheme>[ThemeData.light().colorScheme, ThemeData.dark().colorScheme]) {
testWidgets('default background color', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
colorScheme: colorScheme,
),
home: Scaffold(
body: Center(
child: TextSelectionToolbar(
anchorAbove: Offset.zero,
anchorBelow: Offset.zero,
children: <Widget>[
TextSelectionToolbarTextButton(
padding: TextSelectionToolbarTextButton.getPadding(0, 1),
onPressed: () {},
child: const Text('Custom button'),
),
],
),
),
),
),
);
Finder findToolbarContainer() {
return find.descendant(
of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_TextSelectionToolbarContainer'),
matching: find.byType(Material),
);
}
expect(findToolbarContainer(), findsAtLeastNWidgets(1));
final Material toolbarContainer = tester.widget(findToolbarContainer().first);
expect(
toolbarContainer.color,
// The default colors are hardcoded and don't take the default value of
// the theme's surface color.
switch (colorScheme.brightness) {
Brightness.light => const Color(0xffffffff),
Brightness.dark => const Color(0xff424242),
},
);
});
testWidgets('custom background color', (WidgetTester tester) async {
const Color customBackgroundColor = Colors.red;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
colorScheme: colorScheme.copyWith(
surface: customBackgroundColor,
),
),
home: Scaffold(
body: Center(
child: TextSelectionToolbar(
anchorAbove: Offset.zero,
anchorBelow: Offset.zero,
children: <Widget>[
TextSelectionToolbarTextButton(
padding: TextSelectionToolbarTextButton.getPadding(0, 1),
onPressed: () {},
child: const Text('Custom button'),
),
],
),
),
),
),
);
Finder findToolbarContainer() {
return find.descendant(
of: find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_TextSelectionToolbarContainer'),
matching: find.byType(Material),
);
}
expect(findToolbarContainer(), findsAtLeastNWidgets(1));
final Material toolbarContainer = tester.widget(findToolbarContainer().first);
expect(
toolbarContainer.color,
customBackgroundColor,
);
});
}
testWidgets('Overflowed menu expands children horizontally', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/144089.
late StateSetter setState;
final List<Widget> children = List<Widget>.generate(7, (int i) => const TestBox());
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: StatefulBuilder(
builder: (BuildContext context, StateSetter setter) {
setState = setter;
return TextSelectionToolbar(
anchorAbove: const Offset(50.0, 100.0),
anchorBelow: const Offset(50.0, 200.0),
children: children,
);
},
),
),
),
);
// All children fit on the screen, so they are all rendered.
expect(find.byType(TestBox), findsNWidgets(children.length));
expect(findOverflowButton(), findsNothing);
const String short = 'Short';
const String medium = 'Medium length';
const String long = 'Long label in the overflow menu';
// Adding several children makes the menu overflow.
setState(() {
children.addAll(const <Text>[
Text(short),
Text(medium),
Text(long),
]);
});
await tester.pumpAndSettle();
expect(findOverflowButton(), findsOneWidget);
// Tap the overflow button to show the overflow menu.
await tester.tap(findOverflowButton());
await tester.pumpAndSettle();
expect(find.byType(TestBox), findsNothing);
expect(find.byType(Text), findsNWidgets(3));
expect(findOverflowButton(), findsOneWidget);
Finder findToolbarContainer() {
return find.byWidgetPredicate((Widget w) => '${w.runtimeType}' == '_TextSelectionToolbarContainer');
}
expect(findToolbarContainer(), findsAtLeastNWidgets(1));
// Buttons have their width set to the container width.
final double overflowMenuWidth = tester.getRect(findToolbarContainer()).width;
expect(tester.getRect(find.text(long)).width, overflowMenuWidth);
expect(tester.getRect(find.text(medium)).width, overflowMenuWidth);
expect(tester.getRect(find.text(short)).width, overflowMenuWidth);
});
}
| flutter/packages/flutter/test/material/text_selection_toolbar_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/text_selection_toolbar_test.dart",
"repo_id": "flutter",
"token_count": 5012
} | 669 |
// 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() {
testWidgets('Slider value indicator', (WidgetTester tester) async {
await _buildValueIndicatorStaticSlider(
tester,
value: 0,
useMaterial3: true,
);
await _pressStartThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_m3_start_text_scale_1_width_0.png'),
);
await _buildValueIndicatorStaticSlider(
tester,
value: 0.5,
useMaterial3: true,
);
await _pressMiddleThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_m3_middle_text_scale_1_width_0.png'),
);
await _buildValueIndicatorStaticSlider(
tester,
value: 1,
useMaterial3: true,
);
await _pressEndThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_m3_end_text_scale_1_width_0.png'),
);
});
testWidgets('Slider value indicator wide text', (WidgetTester tester) async {
await _buildValueIndicatorStaticSlider(
tester,
value: 0,
decimalCount: 5,
useMaterial3: true,
);
await _pressStartThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_m3_start_text_scale_1_width_5.png'),
);
await _buildValueIndicatorStaticSlider(
tester,
value: 0.5,
decimalCount: 5,
useMaterial3: true,
);
await _pressMiddleThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_m3_middle_text_scale_1_width_5.png'),
);
await _buildValueIndicatorStaticSlider(
tester,
value: 1,
decimalCount: 5,
useMaterial3: true,
);
await _pressEndThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_m3_end_text_scale_1_width_5.png'),
);
});
testWidgets('Slider value indicator large text scale', (WidgetTester tester) async {
await _buildValueIndicatorStaticSlider(
tester,
value: 0,
textScale: 3,
useMaterial3: true,
);
await _pressStartThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_m3_start_text_scale_4_width_0.png'),
);
await _buildValueIndicatorStaticSlider(
tester,
value: 0.5,
textScale: 3,
useMaterial3: true,
);
await _pressMiddleThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_m3_middle_text_scale_4_width_0.png'),
);
await _buildValueIndicatorStaticSlider(
tester,
value: 1,
textScale: 3,
useMaterial3: true,
);
await _pressEndThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_m3_end_text_scale_4_width_0.png'),
);
});
testWidgets('Slider value indicator large text scale and wide text',
(WidgetTester tester) async {
await _buildValueIndicatorStaticSlider(
tester,
value: 0,
textScale: 3,
decimalCount: 5,
useMaterial3: true,
);
await _pressStartThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_m3_start_text_scale_4_width_5.png'),
);
await _buildValueIndicatorStaticSlider(
tester,
value: 0.5,
textScale: 3,
decimalCount: 5,
useMaterial3: true,
);
await _pressMiddleThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_m3_middle_text_scale_4_width_5.png'),
);
await _buildValueIndicatorStaticSlider(
tester,
value: 1,
textScale: 3,
decimalCount: 5,
useMaterial3: true,
);
await _pressEndThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_m3_end_text_scale_4_width_5.png'),
);
});
group('Material 2', () {
// These tests are only relevant for Material 2. Once Material 2
// support is deprecated and the APIs are removed, these tests
// can be deleted.
testWidgets('Slider value indicator', (WidgetTester tester) async {
await _buildValueIndicatorStaticSlider(
tester,
value: 0,
);
await _pressStartThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_start_text_scale_1_width_0.png'),
);
await _buildValueIndicatorStaticSlider(
tester,
value: 0.5,
);
await _pressMiddleThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_middle_text_scale_1_width_0.png'),
);
await _buildValueIndicatorStaticSlider(
tester,
value: 1,
);
await _pressEndThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_end_text_scale_1_width_0.png'),
);
});
testWidgets('Slider value indicator wide text', (WidgetTester tester) async {
await _buildValueIndicatorStaticSlider(
tester,
value: 0,
decimalCount: 5,
);
await _pressStartThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_start_text_scale_1_width_5.png'),
);
await _buildValueIndicatorStaticSlider(
tester,
value: 0.5,
decimalCount: 5,
);
await _pressMiddleThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_middle_text_scale_1_width_5.png'),
);
await _buildValueIndicatorStaticSlider(
tester,
value: 1,
decimalCount: 5,
);
await _pressEndThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_end_text_scale_1_width_5.png'),
);
});
testWidgets('Slider value indicator large text scale', (WidgetTester tester) async {
await _buildValueIndicatorStaticSlider(
tester,
value: 0,
textScale: 3,
);
await _pressStartThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_start_text_scale_4_width_0.png'),
);
await _buildValueIndicatorStaticSlider(
tester,
value: 0.5,
textScale: 3,
);
await _pressMiddleThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_middle_text_scale_4_width_0.png'),
);
await _buildValueIndicatorStaticSlider(
tester,
value: 1,
textScale: 3,
);
await _pressEndThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_end_text_scale_4_width_0.png'),
);
});
testWidgets('Slider value indicator large text scale and wide text',
(WidgetTester tester) async {
await _buildValueIndicatorStaticSlider(
tester,
value: 0,
textScale: 3,
decimalCount: 5,
);
await _pressStartThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_start_text_scale_4_width_5.png'),
);
await _buildValueIndicatorStaticSlider(
tester,
value: 0.5,
textScale: 3,
decimalCount: 5,
);
await _pressMiddleThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_middle_text_scale_4_width_5.png'),
);
await _buildValueIndicatorStaticSlider(
tester,
value: 1,
textScale: 3,
decimalCount: 5,
);
await _pressEndThumb(tester);
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('slider_end_text_scale_4_width_5.png'),
);
});
});
}
Future<void> _pressStartThumb(WidgetTester tester) async {
final Offset bottomLeft = tester.getBottomLeft(find.byType(Slider));
final Offset topLeft = tester.getTopLeft(find.byType(Slider));
final Offset left = (bottomLeft + topLeft) / 2;
final Offset start = left + const Offset(24, 0);
final TestGesture gesture = await tester.startGesture(start);
await tester.pumpAndSettle();
addTearDown(()async {
// Finish gesture to release resources.
await gesture.up();
await tester.pumpAndSettle();
});
}
Future<void> _pressMiddleThumb(WidgetTester tester) async {
await tester.press(find.byType(Slider));
await tester.pumpAndSettle();
}
Future<void> _pressEndThumb(WidgetTester tester) async {
final Offset bottomRight = tester.getBottomRight(find.byType(Slider));
final Offset topRight = tester.getTopRight(find.byType(Slider));
final Offset right = (bottomRight + topRight) / 2;
final Offset start = right - const Offset(24, 0);
final TestGesture gesture = await tester.startGesture(start);
await tester.pumpAndSettle();
addTearDown(()async {
// Finish gesture to release resources.
await gesture.up();
await tester.pumpAndSettle();
});
}
Future<void> _buildValueIndicatorStaticSlider(
WidgetTester tester, {
required double value,
double textScale = 1.0,
int decimalCount = 0,
bool useMaterial3 = false,
}) async {
await tester.pumpWidget(
MaterialApp(
debugShowCheckedModeBanner: false, // https://github.com/flutter/flutter/issues/143616
theme: ThemeData(useMaterial3: useMaterial3),
home: Scaffold(
body: Builder(
builder: (BuildContext context) {
return Center(
child: MediaQuery.withClampedTextScaling(
minScaleFactor: textScale,
maxScaleFactor: textScale,
child: SliderTheme(
data: Theme.of(context).sliderTheme.copyWith(
showValueIndicator: ShowValueIndicator.always,
),
child: Slider(
value: value,
label: value.toStringAsFixed(decimalCount),
onChanged: (double newValue) {},
),
),
),
);
},
),
),
),
);
}
| flutter/packages/flutter/test/material/value_indicating_slider_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/material/value_indicating_slider_test.dart",
"repo_id": "flutter",
"token_count": 4658
} | 670 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
const double _doubleColorPrecision = 0.01;
void main() {
test('HSVColor control test', () {
const HSVColor color = HSVColor.fromAHSV(0.7, 28.0, 0.3, 0.6);
expect(color, hasOneLineDescription);
expect(color.hashCode, equals(const HSVColor.fromAHSV(0.7, 28.0, 0.3, 0.6).hashCode));
expect(color.withAlpha(0.8), const HSVColor.fromAHSV(0.8, 28.0, 0.3, 0.6));
expect(color.withHue(123.0), const HSVColor.fromAHSV(0.7, 123.0, 0.3, 0.6));
expect(color.withSaturation(0.9), const HSVColor.fromAHSV(0.7, 28.0, 0.9, 0.6));
expect(color.withValue(0.1), const HSVColor.fromAHSV(0.7, 28.0, 0.3, 0.1));
expect(color.toColor(), const Color(0xb399816b));
final HSVColor result = HSVColor.lerp(color, const HSVColor.fromAHSV(0.3, 128.0, 0.7, 0.2), 0.25)!;
expect(result.alpha, moreOrLessEquals(0.6));
expect(result.hue, moreOrLessEquals(53.0));
expect(result.saturation, greaterThan(0.3999));
expect(result.saturation, lessThan(0.4001));
expect(result.value, moreOrLessEquals(0.5));
});
test('HSVColor hue sweep test', () {
final List<Color> output = <Color>[];
for (double hue = 0.0; hue <= 360.0; hue += 36.0) {
final HSVColor hsvColor = HSVColor.fromAHSV(1.0, hue, 1.0, 1.0);
final Color color = hsvColor.toColor();
output.add(color);
if (hue != 360.0) {
// Check that it's reversible.
expect(
HSVColor.fromColor(color),
within<HSVColor>(distance: _doubleColorPrecision, from: hsvColor),
);
}
}
final List<Color> expectedColors = <Color>[
const Color(0xffff0000),
const Color(0xffff9900),
const Color(0xffccff00),
const Color(0xff33ff00),
const Color(0xff00ff66),
const Color(0xff00ffff),
const Color(0xff0066ff),
const Color(0xff3300ff),
const Color(0xffcc00ff),
const Color(0xffff0099),
const Color(0xffff0000),
];
expect(output, equals(expectedColors));
});
test('HSVColor saturation sweep test', () {
final List<Color> output = <Color>[];
for (double saturation = 0.0; saturation < 1.0; saturation += 0.1) {
final HSVColor hslColor = HSVColor.fromAHSV(1.0, 0.0, saturation, 1.0);
final Color color = hslColor.toColor();
output.add(color);
// Check that it's reversible.
expect(
HSVColor.fromColor(color),
within<HSVColor>(distance: _doubleColorPrecision, from: hslColor),
);
}
final List<Color> expectedColors = <Color>[
const Color(0xffffffff),
const Color(0xffffe6e6),
const Color(0xffffcccc),
const Color(0xffffb3b3),
const Color(0xffff9999),
const Color(0xffff8080),
const Color(0xffff6666),
const Color(0xffff4d4d),
const Color(0xffff3333),
const Color(0xffff1a1a),
const Color(0xffff0000),
];
expect(output, equals(expectedColors));
});
test('HSVColor value sweep test', () {
final List<Color> output = <Color>[];
for (double value = 0.0; value < 1.0; value += 0.1) {
final HSVColor hsvColor = HSVColor.fromAHSV(1.0, 0.0, 1.0, value);
final Color color = hsvColor.toColor();
output.add(color);
// Check that it's reversible. Discontinuities at the ends for saturation,
// so we skip those.
if (value >= _doubleColorPrecision && value <= (1.0 - _doubleColorPrecision)) {
expect(
HSVColor.fromColor(color),
within<HSVColor>(distance: _doubleColorPrecision, from: hsvColor),
);
}
// output.add(HSVColor.fromAHSV(1.0, 0.0, 1.0, value).toColor());
}
final List<Color> expectedColors = <Color>[
const Color(0xff000000),
const Color(0xff1a0000),
const Color(0xff330000),
const Color(0xff4d0000),
const Color(0xff660000),
const Color(0xff800000),
const Color(0xff990000),
const Color(0xffb30000),
const Color(0xffcc0000),
const Color(0xffe50000),
const Color(0xffff0000),
];
expect(output, equals(expectedColors));
});
test('HSVColor.lerp identical a,b', () {
expect(HSVColor.lerp(null, null, 0), null);
const HSVColor color = HSVColor.fromAHSV(1.0, 0.0, 1.0, 1.0);
expect(identical(HSVColor.lerp(color, color, 0.5), color), true);
});
test('HSVColor lerps hue correctly.', () {
final List<Color> output = <Color>[];
const HSVColor startColor = HSVColor.fromAHSV(1.0, 0.0, 1.0, 1.0);
const HSVColor endColor = HSVColor.fromAHSV(1.0, 360.0, 1.0, 1.0);
for (double t = -0.5; t < 1.5; t += 0.1) {
output.add(HSVColor.lerp(startColor, endColor, t)!.toColor());
}
final List<Color> expectedColors = <Color>[
const Color(0xff00ffff),
const Color(0xff0066ff),
const Color(0xff3300ff),
const Color(0xffcc00ff),
const Color(0xffff0099),
const Color(0xffff0000),
const Color(0xffff9900),
const Color(0xffccff00),
const Color(0xff33ff00),
const Color(0xff00ff66),
const Color(0xff00ffff),
const Color(0xff0066ff),
const Color(0xff3300ff),
const Color(0xffcc00ff),
const Color(0xffff0099),
const Color(0xffff0000),
const Color(0xffff9900),
const Color(0xffccff00),
const Color(0xff33ff00),
const Color(0xff00ff66),
];
expect(output, equals(expectedColors));
});
test('HSVColor lerps saturation correctly.', () {
final List<Color> output = <Color>[];
const HSVColor startColor = HSVColor.fromAHSV(1.0, 0.0, 0.0, 1.0);
const HSVColor endColor = HSVColor.fromAHSV(1.0, 0.0, 1.0, 1.0);
for (double t = -0.1; t < 1.1; t += 0.1) {
output.add(HSVColor.lerp(startColor, endColor, t)!.toColor());
}
final List<Color> expectedColors = <Color>[
const Color(0xffffffff),
const Color(0xffffffff),
const Color(0xffffe6e6),
const Color(0xffffcccc),
const Color(0xffffb3b3),
const Color(0xffff9999),
const Color(0xffff8080),
const Color(0xffff6666),
const Color(0xffff4d4d),
const Color(0xffff3333),
const Color(0xffff1a1a),
const Color(0xffff0000),
const Color(0xffff0000),
];
expect(output, equals(expectedColors));
});
test('HSVColor lerps value correctly.', () {
final List<Color> output = <Color>[];
const HSVColor startColor = HSVColor.fromAHSV(1.0, 0.0, 1.0, 0.0);
const HSVColor endColor = HSVColor.fromAHSV(1.0, 0.0, 1.0, 1.0);
for (double t = -0.1; t < 1.1; t += 0.1) {
output.add(HSVColor.lerp(startColor, endColor, t)!.toColor());
}
final List<Color> expectedColors = <Color>[
const Color(0xff000000),
const Color(0xff000000),
const Color(0xff1a0000),
const Color(0xff330000),
const Color(0xff4d0000),
const Color(0xff660000),
const Color(0xff800000),
const Color(0xff990000),
const Color(0xffb30000),
const Color(0xffcc0000),
const Color(0xffe50000),
const Color(0xffff0000),
const Color(0xffff0000),
];
expect(output, equals(expectedColors));
});
test('HSLColor control test', () {
const HSLColor color = HSLColor.fromAHSL(0.7, 28.0, 0.3, 0.6);
expect(color, hasOneLineDescription);
expect(color.hashCode, equals(const HSLColor.fromAHSL(0.7, 28.0, 0.3, 0.6).hashCode));
expect(color.withAlpha(0.8), const HSLColor.fromAHSL(0.8, 28.0, 0.3, 0.6));
expect(color.withHue(123.0), const HSLColor.fromAHSL(0.7, 123.0, 0.3, 0.6));
expect(color.withSaturation(0.9), const HSLColor.fromAHSL(0.7, 28.0, 0.9, 0.6));
expect(color.withLightness(0.1), const HSLColor.fromAHSL(0.7, 28.0, 0.3, 0.1));
expect(color.toColor(), const Color(0xb3b8977a));
final HSLColor result = HSLColor.lerp(color, const HSLColor.fromAHSL(0.3, 128.0, 0.7, 0.2), 0.25)!;
expect(result.alpha, moreOrLessEquals(0.6));
expect(result.hue, moreOrLessEquals(53.0));
expect(result.saturation, greaterThan(0.3999));
expect(result.saturation, lessThan(0.4001));
expect(result.lightness, moreOrLessEquals(0.5));
});
test('HSLColor hue sweep test', () {
final List<Color> output = <Color>[];
for (double hue = 0.0; hue <= 360.0; hue += 36.0) {
final HSLColor hslColor = HSLColor.fromAHSL(1.0, hue, 0.5, 0.5);
final Color color = hslColor.toColor();
output.add(color);
if (hue != 360.0) {
// Check that it's reversible.
expect(
HSLColor.fromColor(color),
within<HSLColor>(distance: _doubleColorPrecision, from: hslColor),
);
}
}
final List<Color> expectedColors = <Color>[
const Color(0xffbf4040),
const Color(0xffbf8c40),
const Color(0xffa6bf40),
const Color(0xff59bf40),
const Color(0xff40bf73),
const Color(0xff40bfbf),
const Color(0xff4073bf),
const Color(0xff5940bf),
const Color(0xffa640bf),
const Color(0xffbf408c),
const Color(0xffbf4040),
];
expect(output, equals(expectedColors));
});
test('HSLColor saturation sweep test', () {
final List<Color> output = <Color>[];
for (double saturation = 0.0; saturation < 1.0; saturation += 0.1) {
final HSLColor hslColor = HSLColor.fromAHSL(1.0, 0.0, saturation, 0.5);
final Color color = hslColor.toColor();
output.add(color);
// Check that it's reversible.
expect(
HSLColor.fromColor(color),
within<HSLColor>(distance: _doubleColorPrecision, from: hslColor),
);
}
final List<Color> expectedColors = <Color>[
const Color(0xff808080),
const Color(0xff8c7373),
const Color(0xff996666),
const Color(0xffa65959),
const Color(0xffb34d4d),
const Color(0xffbf4040),
const Color(0xffcc3333),
const Color(0xffd92626),
const Color(0xffe51a1a),
const Color(0xfff20d0d),
const Color(0xffff0000),
];
expect(output, equals(expectedColors));
});
test('HSLColor lightness sweep test', () {
final List<Color> output = <Color>[];
for (double lightness = 0.0; lightness < 1.0; lightness += 0.1) {
final HSLColor hslColor = HSLColor.fromAHSL(1.0, 0.0, 0.5, lightness);
final Color color = hslColor.toColor();
output.add(color);
// Check that it's reversible. Discontinuities at the ends for saturation,
// so we skip those.
if (lightness >= _doubleColorPrecision && lightness <= (1.0 - _doubleColorPrecision)) {
expect(
HSLColor.fromColor(color),
within<HSLColor>(distance: _doubleColorPrecision, from: hslColor),
);
}
}
final List<Color> expectedColors = <Color>[
const Color(0xff000000),
const Color(0xff260d0d),
const Color(0xff4d1a1a),
const Color(0xff732626),
const Color(0xff993333),
const Color(0xffbf4040),
const Color(0xffcc6666),
const Color(0xffd98c8c),
const Color(0xffe6b3b3),
const Color(0xfff2d9d9),
const Color(0xffffffff),
];
expect(output, equals(expectedColors));
});
test('HSLColor.lerp identical a,b', () {
expect(HSLColor.lerp(null, null, 0), null);
const HSLColor color = HSLColor.fromAHSL(1.0, 0.0, 0.5, 0.5);
expect(identical(HSLColor.lerp(color, color, 0.5), color), true);
});
test('HSLColor lerps hue correctly.', () {
final List<Color> output = <Color>[];
const HSLColor startColor = HSLColor.fromAHSL(1.0, 0.0, 0.5, 0.5);
const HSLColor endColor = HSLColor.fromAHSL(1.0, 360.0, 0.5, 0.5);
for (double t = -0.5; t < 1.5; t += 0.1) {
output.add(HSLColor.lerp(startColor, endColor, t)!.toColor());
}
final List<Color> expectedColors = <Color>[
const Color(0xff40bfbf),
const Color(0xff4073bf),
const Color(0xff5940bf),
const Color(0xffa640bf),
const Color(0xffbf408c),
const Color(0xffbf4040),
const Color(0xffbf8c40),
const Color(0xffa6bf40),
const Color(0xff59bf40),
const Color(0xff40bf73),
const Color(0xff40bfbf),
const Color(0xff4073bf),
const Color(0xff5940bf),
const Color(0xffa640bf),
const Color(0xffbf408c),
const Color(0xffbf4040),
const Color(0xffbf8c40),
const Color(0xffa6bf40),
const Color(0xff59bf40),
const Color(0xff40bf73),
];
expect(output, equals(expectedColors));
});
test('HSLColor lerps saturation correctly.', () {
final List<Color> output = <Color>[];
const HSLColor startColor = HSLColor.fromAHSL(1.0, 0.0, 0.0, 0.5);
const HSLColor endColor = HSLColor.fromAHSL(1.0, 0.0, 1.0, 0.5);
for (double t = -0.1; t < 1.1; t += 0.1) {
output.add(HSLColor.lerp(startColor, endColor, t)!.toColor());
}
final List<Color> expectedColors = <Color>[
const Color(0xff808080),
const Color(0xff808080),
const Color(0xff8c7373),
const Color(0xff996666),
const Color(0xffa65959),
const Color(0xffb34d4d),
const Color(0xffbf4040),
const Color(0xffcc3333),
const Color(0xffd92626),
const Color(0xffe51a1a),
const Color(0xfff20d0d),
const Color(0xffff0000),
const Color(0xffff0000),
];
expect(output, equals(expectedColors));
});
test('HSLColor lerps lightness correctly.', () {
final List<Color> output = <Color>[];
const HSLColor startColor = HSLColor.fromAHSL(1.0, 0.0, 0.5, 0.0);
const HSLColor endColor = HSLColor.fromAHSL(1.0, 0.0, 0.5, 1.0);
for (double t = -0.1; t < 1.1; t += 0.1) {
output.add(HSLColor.lerp(startColor, endColor, t)!.toColor());
}
final List<Color> expectedColors = <Color>[
const Color(0xff000000),
const Color(0xff000000),
const Color(0xff260d0d),
const Color(0xff4d1a1a),
const Color(0xff732626),
const Color(0xff993333),
const Color(0xffbf4040),
const Color(0xffcc6666),
const Color(0xffd98c8c),
const Color(0xffe6b3b3),
const Color(0xfff2d9d9),
const Color(0xffffffff),
const Color(0xffffffff),
];
expect(output, equals(expectedColors));
});
test('ColorSwatch test', () {
final int color = nonconst(0xFF027223);
final ColorSwatch<String> greens1 = ColorSwatch<String>(
color,
const <String, Color>{
'2259 C': Color(0xFF027223),
'2273 C': Color(0xFF257226),
'2426 XGC': Color(0xFF00932F),
'7732 XGC': Color(0xFF007940),
},
);
final ColorSwatch<String> greens2 = ColorSwatch<String>(
color,
const <String, Color>{
'2259 C': Color(0xFF027223),
'2273 C': Color(0xFF257226),
'2426 XGC': Color(0xFF00932F),
'7732 XGC': Color(0xFF007940),
},
);
expect(greens1, greens2);
expect(greens1.hashCode, greens2.hashCode);
expect(greens1['2259 C'], const Color(0xFF027223));
expect(greens1.value, 0xFF027223);
});
test('ColorSwatch.lerp', () {
const ColorSwatch<int> swatchA = ColorSwatch<int>(0x00000000, <int, Color>{1: Color(0x00000000)});
const ColorSwatch<int> swatchB = ColorSwatch<int>(0xFFFFFFFF, <int, Color>{1: Color(0xFFFFFFFF)});
expect(
ColorSwatch.lerp(swatchA, swatchB, 0.0),
const ColorSwatch<int>(0x00000000, <int, Color>{1: Color(0x00000000)}),
);
expect(
ColorSwatch.lerp(swatchA, swatchB, 0.5),
const ColorSwatch<int>(0x7F7F7F7F, <int, Color>{1: Color(0x7F7F7F7F)}),
);
expect(
ColorSwatch.lerp(swatchA, swatchB, 1.0),
const ColorSwatch<int>(0xFFFFFFFF, <int, Color>{1: Color(0xFFFFFFFF)}),
);
expect(
ColorSwatch.lerp(swatchA, swatchB, -0.1),
const ColorSwatch<int>(0x00000000, <int, Color>{1: Color(0x00000000)}),
);
expect(
ColorSwatch.lerp(swatchA, swatchB, 1.1),
const ColorSwatch<int>(0xFFFFFFFF, <int, Color>{1: Color(0xFFFFFFFF)}),
);
});
test('ColorSwatch.lerp identical a,b', () {
expect(ColorSwatch.lerp<Object?>(null, null, 0), null);
const ColorSwatch<int> color = ColorSwatch<int>(0x00000000, <int, Color>{1: Color(0x00000000)});
expect(identical(ColorSwatch.lerp(color, color, 0.5), color), true);
});
test('ColorDiagnosticsProperty includes valueProperties in JSON', () {
ColorProperty property = ColorProperty('foo', const Color.fromARGB(10, 20, 30, 40));
final Map<String, Object> valueProperties = property.toJsonMap(const DiagnosticsSerializationDelegate())['valueProperties']! as Map<String, Object>;
expect(valueProperties['alpha'], 10);
expect(valueProperties['red'], 20);
expect(valueProperties['green'], 30);
expect(valueProperties['blue'], 40);
property = ColorProperty('foo', null);
final Map<String, Object?> json = property.toJsonMap(const DiagnosticsSerializationDelegate());
expect(json.containsKey('valueProperties'), isFalse);
});
test('MaterialColor swatch comparison', () {
const Map<int, MaterialColor> sampleMap = <int, MaterialColor>{
0: Colors.lightBlue,
1: Colors.deepOrange,
2: Colors.blueGrey,
};
const MaterialColor first = MaterialColor(0, sampleMap);
const MaterialColor second = MaterialColor(0, sampleMap);
const MaterialColor third = MaterialColor(0, <int, MaterialColor>{
0: Colors.lightBlue,
1: Colors.deepOrange,
2: Colors.blueGrey,
});
expect(first == second, true);
expect(first == third, true);
});
}
| flutter/packages/flutter/test/painting/colors_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/colors_test.dart",
"repo_id": "flutter",
"token_count": 7826
} | 671 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/painting.dart';
import 'package:flutter_test/flutter_test.dart';
import '../image_data.dart';
import 'painting_utils.dart';
void main() {
final PaintingBindingSpy binding = PaintingBindingSpy();
test('Image decoder control test', () async {
expect(binding.instantiateImageCodecCalledCount, 0);
final ui.Image image = await decodeImageFromList(Uint8List.fromList(kTransparentImage));
expect(image, isNotNull);
expect(image.width, 1);
expect(image.height, 1);
expect(binding.instantiateImageCodecCalledCount, 1);
});
}
| flutter/packages/flutter/test/painting/image_decoder_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/image_decoder_test.dart",
"repo_id": "flutter",
"token_count": 267
} | 672 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/painting.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
class PaintingBindingSpy extends BindingBase with SchedulerBinding, ServicesBinding, PaintingBinding {
int counter = 0;
int get instantiateImageCodecCalledCount => counter;
@override
Future<ui.Codec> instantiateImageCodecWithSize(ui.ImmutableBuffer buffer, { ui.TargetImageSizeCallback? getTargetSize }) {
counter++;
return ui.instantiateImageCodecWithSize(buffer, getTargetSize: getTargetSize);
}
@override
// ignore: must_call_super
void initLicenses() {
// Do not include any licenses, because we're a test, and the LICENSE file
// doesn't get generated for tests.
}
}
| flutter/packages/flutter/test/painting/painting_utils.dart/0 | {
"file_path": "flutter/packages/flutter/test/painting/painting_utils.dart",
"repo_id": "flutter",
"token_count": 298
} | 673 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/physics.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('Gravity simulation 1', () {
expect(GravitySimulation(9.81, 10.0, 0.0, 0.0), hasOneLineDescription);
expect(GravitySimulation(9.81, 10.0, 0.0, 0.0).x(10.0), moreOrLessEquals(50.0 * 9.81 + 10.0));
});
test('Gravity simulation 2', () {
final GravitySimulation gravity = GravitySimulation(-10, 0.0, 6.0, 10.0);
expect(gravity.x(0.0), equals(0.0));
expect(gravity.dx(0.0), equals(10.0));
expect(gravity.isDone(0.0), isFalse);
expect(gravity.x(1.0), equals(5.0));
expect(gravity.dx(1.0), equals(0.0));
expect(gravity.isDone(0.2), isFalse);
expect(gravity.x(2.0), equals(0.0));
expect(gravity.dx(2.0), equals(-10.0));
expect(gravity.isDone(2.0), isFalse);
expect(gravity.x(3.0), equals(-15.0));
expect(gravity.dx(3.0), equals(-20.0));
expect(gravity.isDone(3.0), isTrue);
});
}
| flutter/packages/flutter/test/physics/gravity_simulation_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/physics/gravity_simulation_test.dart",
"repo_id": "flutter",
"token_count": 453
} | 674 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('overflow indicator is not shown when not overflowing', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(
child: UnconstrainedBox(
child: SizedBox(width: 200.0, height: 200.0),
),
),
);
expect(find.byType(UnconstrainedBox), isNot(paints..rect()));
});
testWidgets('overflow indicator is shown when overflowing', (WidgetTester tester) async {
const UnconstrainedBox box = UnconstrainedBox(
child: SizedBox(width: 200.0, height: 200.0),
);
await tester.pumpWidget(
const Center(
child: SizedBox(
height: 100.0,
child: box,
),
),
);
final dynamic exception = tester.takeException();
expect(exception, isFlutterError);
// ignore: avoid_dynamic_calls
expect(exception.diagnostics.first.level, DiagnosticLevel.summary);
// ignore: avoid_dynamic_calls
expect(exception.diagnostics.first.toString(), startsWith('A RenderConstraintsTransformBox overflowed by '));
expect(find.byType(UnconstrainedBox), paints..rect());
await tester.pumpWidget(
const Center(
child: SizedBox(
height: 100.0,
child: box,
),
),
);
// Doesn't throw the exception a second time, because we didn't reset
// overflowReportNeeded.
expect(tester.takeException(), isNull);
expect(find.byType(UnconstrainedBox), paints..rect());
});
testWidgets('overflow indicator is not shown when constraint size is zero.', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(
child: SizedBox(
height: 0.0,
child: UnconstrainedBox(
child: SizedBox(width: 200.0, height: 200.0),
),
),
),
);
expect(find.byType(UnconstrainedBox), isNot(paints..rect()));
});
}
| flutter/packages/flutter/test/rendering/debug_overflow_indicator_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/debug_overflow_indicator_test.dart",
"repo_id": "flutter",
"token_count": 854
} | 675 |
// 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';
// TODO(hansmuller): when https://github.com/flutter/flutter/issues/17700
// is fixed, these tests should be updated to use a real font (not Ahem).
void main() {
testWidgets(
'Material2 - RichText TextSpan styles with different locales',
(WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
supportedLocales: const <Locale>[
Locale('en', 'US'),
Locale('ja'),
Locale('zh'),
],
home: Builder(
builder: (BuildContext context) {
const String character = '骨';
final TextStyle style = Theme.of(context).textTheme.displayMedium!;
return Scaffold(
body: Container(
padding: const EdgeInsets.all(48.0),
alignment: Alignment.center,
child: RepaintBoundary(
// Expected result can be seen here:
// https://user-images.githubusercontent.com/1377460/40503473-faad6f34-5f42-11e8-972b-d83b727c9d0e.png
child: RichText(
text: TextSpan(
children: <TextSpan>[
TextSpan(text: character, style: style.copyWith(locale: const Locale('ja'))),
TextSpan(text: character, style: style.copyWith(locale: const Locale('zh'))),
],
),
),
),
),
);
},
),
),
);
await expectLater(
find.byType(RichText),
matchesGoldenFile('m2_localized_fonts.rich_text.styled_text_span.png'),
);
},
);
testWidgets(
'Material3 - RichText TextSpan styles with different locales',
(WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: true),
supportedLocales: const <Locale>[
Locale('en', 'US'),
Locale('ja'),
Locale('zh'),
],
home: Builder(
builder: (BuildContext context) {
const String character = '骨';
final TextStyle style = Theme.of(context).textTheme.displayMedium!;
return Scaffold(
body: Container(
padding: const EdgeInsets.all(48.0),
alignment: Alignment.center,
child: RepaintBoundary(
// Expected result can be seen here:
// https://user-images.githubusercontent.com/1377460/40503473-faad6f34-5f42-11e8-972b-d83b727c9d0e.png
child: RichText(
text: TextSpan(
children: <TextSpan>[
TextSpan(text: character, style: style.copyWith(locale: const Locale('ja'))),
TextSpan(text: character, style: style.copyWith(locale: const Locale('zh'))),
],
),
),
),
),
);
},
),
),
);
await expectLater(
find.byType(RichText),
matchesGoldenFile('m3_localized_fonts.rich_text.styled_text_span.png'),
);
},
);
testWidgets(
'Material2 - Text with locale-specific glyphs, ambient locale',
(WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
supportedLocales: const <Locale>[
Locale('en', 'US'),
Locale('ja'),
Locale('zh'),
],
home: Builder(
builder: (BuildContext context) {
const String character = '骨';
final TextStyle style = Theme.of(context).textTheme.displayMedium!;
return Scaffold(
body: Container(
padding: const EdgeInsets.all(48.0),
alignment: Alignment.center,
child: RepaintBoundary(
// Expected result can be seen here:
// https://user-images.githubusercontent.com/1377460/40503473-faad6f34-5f42-11e8-972b-d83b727c9d0e.png
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Localizations.override(
context: context,
locale: const Locale('ja'),
child: Text(character, style: style),
),
Localizations.override(
context: context,
locale: const Locale('zh'),
child: Text(character, style: style),
),
],
),
),
),
);
},
),
),
);
await expectLater(
find.byType(Row),
matchesGoldenFile('localized_fonts.text_ambient_locale.chars.png'),
);
},
);
testWidgets(
'Material3 - Text with locale-specific glyphs, ambient locale',
(WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: true),
supportedLocales: const <Locale>[
Locale('en', 'US'),
Locale('ja'),
Locale('zh'),
],
home: Builder(
builder: (BuildContext context) {
const String character = '骨';
final TextStyle style = Theme.of(context).textTheme.displayMedium!;
return Scaffold(
body: Container(
padding: const EdgeInsets.all(48.0),
alignment: Alignment.center,
child: RepaintBoundary(
// Expected result can be seen here:
// https://user-images.githubusercontent.com/1377460/40503473-faad6f34-5f42-11e8-972b-d83b727c9d0e.png
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Localizations.override(
context: context,
locale: const Locale('ja'),
child: Text(character, style: style),
),
Localizations.override(
context: context,
locale: const Locale('zh'),
child: Text(character, style: style),
),
],
),
),
),
);
},
),
),
);
await expectLater(
find.byType(Row),
matchesGoldenFile('m3_localized_fonts.text_ambient_locale.chars.png'),
);
},
);
testWidgets(
'Material2 - Text with locale-specific glyphs, explicit locale',
(WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
supportedLocales: const <Locale>[
Locale('en', 'US'),
Locale('ja'),
Locale('zh'),
],
home: Builder(
builder: (BuildContext context) {
const String character = '骨';
final TextStyle style = Theme.of(context).textTheme.displayMedium!;
return Scaffold(
body: Container(
padding: const EdgeInsets.all(48.0),
alignment: Alignment.center,
child: RepaintBoundary(
// Expected result can be seen here:
// https://user-images.githubusercontent.com/1377460/40503473-faad6f34-5f42-11e8-972b-d83b727c9d0e.png
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(character, style: style, locale: const Locale('ja')),
Text(character, style: style, locale: const Locale('zh')),
],
),
),
),
);
},
),
),
);
await expectLater(
find.byType(Row),
matchesGoldenFile('m2_localized_fonts.text_explicit_locale.chars.png'),
);
},
);
testWidgets(
'Material3 - Text with locale-specific glyphs, explicit locale',
(WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: true),
supportedLocales: const <Locale>[
Locale('en', 'US'),
Locale('ja'),
Locale('zh'),
],
home: Builder(
builder: (BuildContext context) {
const String character = '骨';
final TextStyle style = Theme.of(context).textTheme.displayMedium!;
return Scaffold(
body: Container(
padding: const EdgeInsets.all(48.0),
alignment: Alignment.center,
child: RepaintBoundary(
// Expected result can be seen here:
// https://user-images.githubusercontent.com/1377460/40503473-faad6f34-5f42-11e8-972b-d83b727c9d0e.png
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Text(character, style: style, locale: const Locale('ja')),
Text(character, style: style, locale: const Locale('zh')),
],
),
),
),
);
},
),
),
);
await expectLater(
find.byType(Row),
matchesGoldenFile('m3_localized_fonts.text_explicit_locale.chars.png'),
);
},
);
}
| flutter/packages/flutter/test/rendering/localized_fonts_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/localized_fonts_test.dart",
"repo_id": "flutter",
"token_count": 5853
} | 676 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
FlutterError.presentError = (FlutterErrorDetails details) {
// Make tests fail on FlutterErrors.
throw details.exception;
};
test('onNeedVisualUpdate takes precedence over manifold', () {
final TestPipelineManifold manifold = TestPipelineManifold();
int rootOnNeedVisualUpdateCallCount = 0;
final TestRenderObject rootRenderObject = TestRenderObject();
final PipelineOwner root = PipelineOwner(
onNeedVisualUpdate: () {
rootOnNeedVisualUpdateCallCount += 1;
},
);
root.rootNode = rootRenderObject;
rootRenderObject.scheduleInitialLayout();
int child1OnNeedVisualUpdateCallCount = 0;
final TestRenderObject child1RenderObject = TestRenderObject();
final PipelineOwner child1 = PipelineOwner(
onNeedVisualUpdate: () {
child1OnNeedVisualUpdateCallCount += 1;
},
);
child1.rootNode = child1RenderObject;
child1RenderObject.scheduleInitialLayout();
final TestRenderObject child2RenderObject = TestRenderObject();
final PipelineOwner child2 = PipelineOwner();
child2.rootNode = child2RenderObject;
child2RenderObject.scheduleInitialLayout();
root.adoptChild(child1);
root.adoptChild(child2);
root.attach(manifold);
root.flushLayout();
manifold.requestVisualUpdateCount = 0;
rootRenderObject.markNeedsLayout();
expect(manifold.requestVisualUpdateCount, 0);
expect(rootOnNeedVisualUpdateCallCount, 1);
expect(child1OnNeedVisualUpdateCallCount, 0);
child1RenderObject.markNeedsLayout();
expect(manifold.requestVisualUpdateCount, 0);
expect(rootOnNeedVisualUpdateCallCount, 1);
expect(child1OnNeedVisualUpdateCallCount, 1);
child2RenderObject.markNeedsLayout();
expect(manifold.requestVisualUpdateCount, 1);
expect(rootOnNeedVisualUpdateCallCount, 1);
expect(child1OnNeedVisualUpdateCallCount, 1);
});
test("parent's render objects are laid out before child's render objects", () {
final TestPipelineManifold manifold = TestPipelineManifold();
final List<String> log = <String>[];
final TestRenderObject rootRenderObject = TestRenderObject(
onLayout: () {
log.add('layout parent');
},
);
final PipelineOwner root = PipelineOwner();
root.rootNode = rootRenderObject;
rootRenderObject.scheduleInitialLayout();
final TestRenderObject childRenderObject = TestRenderObject(
onLayout: () {
log.add('layout child');
},
);
final PipelineOwner child = PipelineOwner();
child.rootNode = childRenderObject;
childRenderObject.scheduleInitialLayout();
root.adoptChild(child);
root.attach(manifold);
expect(log, isEmpty);
root.flushLayout();
expect(log, <String>['layout parent', 'layout child']);
});
test("child cannot dirty parent's render object during flushLayout", () {
final TestPipelineManifold manifold = TestPipelineManifold();
final TestRenderObject rootRenderObject = TestRenderObject();
final PipelineOwner root = PipelineOwner();
root.rootNode = rootRenderObject;
rootRenderObject.scheduleInitialLayout();
bool childLayoutExecuted = false;
final TestRenderObject childRenderObject = TestRenderObject(
onLayout: () {
childLayoutExecuted = true;
expect(() => rootRenderObject.markNeedsLayout(), throwsFlutterError);
},
);
final PipelineOwner child = PipelineOwner();
child.rootNode = childRenderObject;
childRenderObject.scheduleInitialLayout();
root.adoptChild(child);
root.attach(manifold);
root.flushLayout();
expect(childLayoutExecuted, isTrue);
});
test('updates compositing bits on children', () {
final TestPipelineManifold manifold = TestPipelineManifold();
final TestRenderObject rootRenderObject = TestRenderObject();
final PipelineOwner root = PipelineOwner();
root.rootNode = rootRenderObject;
rootRenderObject.markNeedsCompositingBitsUpdate();
final TestRenderObject childRenderObject = TestRenderObject();
final PipelineOwner child = PipelineOwner();
child.rootNode = childRenderObject;
childRenderObject.markNeedsCompositingBitsUpdate();
root.adoptChild(child);
root.attach(manifold);
expect(() => rootRenderObject.needsCompositing, throwsAssertionError);
expect(() => childRenderObject.needsCompositing, throwsAssertionError);
root.flushCompositingBits();
expect(rootRenderObject.needsCompositing, isTrue);
expect(childRenderObject.needsCompositing, isTrue);
});
test("parent's render objects are painted before child's render objects", () {
final TestPipelineManifold manifold = TestPipelineManifold();
final List<String> log = <String>[];
final TestRenderObject rootRenderObject = TestRenderObject(
onPaint: () {
log.add('paint parent');
},
);
final PipelineOwner root = PipelineOwner();
root.rootNode = rootRenderObject;
final OffsetLayer rootLayer = OffsetLayer();
rootLayer.attach(rootRenderObject);
rootRenderObject.scheduleInitialLayout();
rootRenderObject.scheduleInitialPaint(rootLayer);
final TestRenderObject childRenderObject = TestRenderObject(
onPaint: () {
log.add('paint child');
},
);
final PipelineOwner child = PipelineOwner();
child.rootNode = childRenderObject;
final OffsetLayer childLayer = OffsetLayer();
childLayer.attach(childRenderObject);
childRenderObject.scheduleInitialLayout();
childRenderObject.scheduleInitialPaint(childLayer);
root.adoptChild(child);
root.attach(manifold);
root.flushLayout(); // Can't paint with invalid layout.
expect(log, isEmpty);
root.flushPaint();
expect(log, <String>['paint parent', 'paint child']);
});
test("child paint cannot dirty parent's render object", () {
final TestPipelineManifold manifold = TestPipelineManifold();
final TestRenderObject rootRenderObject = TestRenderObject();
final PipelineOwner root = PipelineOwner();
root.rootNode = rootRenderObject;
final OffsetLayer rootLayer = OffsetLayer();
rootLayer.attach(rootRenderObject);
rootRenderObject.scheduleInitialLayout();
rootRenderObject.scheduleInitialPaint(rootLayer);
bool childPaintExecuted = false;
final TestRenderObject childRenderObject = TestRenderObject(
onPaint: () {
childPaintExecuted = true;
expect(() => rootRenderObject.markNeedsPaint(), throwsAssertionError);
},
);
final PipelineOwner child = PipelineOwner();
child.rootNode = childRenderObject;
final OffsetLayer childLayer = OffsetLayer();
childLayer.attach(childRenderObject);
childRenderObject.scheduleInitialLayout();
childRenderObject.scheduleInitialPaint(childLayer);
root.adoptChild(child);
root.attach(manifold);
root.flushLayout(); // Can't paint with invalid layout.
root.flushPaint();
expect(childPaintExecuted, isTrue);
});
test("parent's render objects do semantics before child's render objects", () {
final TestPipelineManifold manifold = TestPipelineManifold()
..semanticsEnabled = true;
final List<String> log = <String>[];
final TestRenderObject rootRenderObject = TestRenderObject(
onSemantics: () {
log.add('semantics parent');
},
);
final PipelineOwner root = PipelineOwner(
onSemanticsOwnerCreated: () {
rootRenderObject.scheduleInitialSemantics();
},
onSemanticsUpdate: (SemanticsUpdate update) { },
);
root.rootNode = rootRenderObject;
final TestRenderObject childRenderObject = TestRenderObject(
onSemantics: () {
log.add('semantics child');
},
);
final PipelineOwner child = PipelineOwner(
onSemanticsOwnerCreated: () {
childRenderObject.scheduleInitialSemantics();
},
onSemanticsUpdate: (SemanticsUpdate update) { },
);
child.rootNode = childRenderObject;
root.adoptChild(child);
root.attach(manifold);
log.clear();
rootRenderObject.markNeedsSemanticsUpdate();
childRenderObject.markNeedsSemanticsUpdate();
root.flushSemantics();
expect(log, <String>['semantics parent', 'semantics child']);
});
test("child cannot mark parent's render object dirty during flushSemantics", () {
final TestPipelineManifold manifold = TestPipelineManifold()
..semanticsEnabled = true;
final TestRenderObject rootRenderObject = TestRenderObject();
final PipelineOwner root = PipelineOwner(
onSemanticsOwnerCreated: () {
rootRenderObject.scheduleInitialSemantics();
},
onSemanticsUpdate: (SemanticsUpdate update) { },
);
root.rootNode = rootRenderObject;
bool childSemanticsCalled = false;
final TestRenderObject childRenderObject = TestRenderObject(
onSemantics: () {
childSemanticsCalled = true;
rootRenderObject.markNeedsSemanticsUpdate();
},
);
final PipelineOwner child = PipelineOwner(
onSemanticsOwnerCreated: () {
childRenderObject.scheduleInitialSemantics();
},
onSemanticsUpdate: (SemanticsUpdate update) { },
);
child.rootNode = childRenderObject;
root.adoptChild(child);
root.attach(manifold);
rootRenderObject.markNeedsSemanticsUpdate();
childRenderObject.markNeedsSemanticsUpdate();
root.flushSemantics();
expect(childSemanticsCalled, isTrue);
});
test('when manifold enables semantics all PipelineOwners in tree create SemanticsOwner', () {
final TestPipelineManifold manifold = TestPipelineManifold();
int rootOnSemanticsOwnerCreatedCount = 0;
int rootOnSemanticsOwnerDisposed = 0;
final PipelineOwner root = PipelineOwner(
onSemanticsOwnerCreated: () {
rootOnSemanticsOwnerCreatedCount++;
},
onSemanticsUpdate: (SemanticsUpdate update) { },
onSemanticsOwnerDisposed: () {
rootOnSemanticsOwnerDisposed++;
},
);
int childOnSemanticsOwnerCreatedCount = 0;
int childOnSemanticsOwnerDisposed = 0;
final PipelineOwner child = PipelineOwner(
onSemanticsOwnerCreated: () {
childOnSemanticsOwnerCreatedCount++;
},
onSemanticsUpdate: (SemanticsUpdate update) { },
onSemanticsOwnerDisposed: () {
childOnSemanticsOwnerDisposed++;
},
);
root.adoptChild(child);
root.attach(manifold);
expect(rootOnSemanticsOwnerCreatedCount, 0);
expect(childOnSemanticsOwnerCreatedCount, 0);
expect(rootOnSemanticsOwnerDisposed, 0);
expect(childOnSemanticsOwnerDisposed, 0);
expect(root.semanticsOwner, isNull);
expect(child.semanticsOwner, isNull);
manifold.semanticsEnabled = true;
expect(rootOnSemanticsOwnerCreatedCount, 1);
expect(childOnSemanticsOwnerCreatedCount, 1);
expect(rootOnSemanticsOwnerDisposed, 0);
expect(childOnSemanticsOwnerDisposed, 0);
expect(root.semanticsOwner, isNotNull);
expect(child.semanticsOwner, isNotNull);
manifold.semanticsEnabled = false;
expect(rootOnSemanticsOwnerCreatedCount, 1);
expect(childOnSemanticsOwnerCreatedCount, 1);
expect(rootOnSemanticsOwnerDisposed, 1);
expect(childOnSemanticsOwnerDisposed, 1);
expect(root.semanticsOwner, isNull);
expect(child.semanticsOwner, isNull);
});
test('when manifold enables semantics all PipelineOwners in tree that did not have a SemanticsOwner create one', () {
final TestPipelineManifold manifold = TestPipelineManifold();
int rootOnSemanticsOwnerCreatedCount = 0;
int rootOnSemanticsOwnerDisposed = 0;
final PipelineOwner root = PipelineOwner(
onSemanticsOwnerCreated: () {
rootOnSemanticsOwnerCreatedCount++;
},
onSemanticsUpdate: (SemanticsUpdate update) { },
onSemanticsOwnerDisposed: () {
rootOnSemanticsOwnerDisposed++;
},
);
int childOnSemanticsOwnerCreatedCount = 0;
int childOnSemanticsOwnerDisposed = 0;
final PipelineOwner child = PipelineOwner(
onSemanticsOwnerCreated: () {
childOnSemanticsOwnerCreatedCount++;
},
onSemanticsUpdate: (SemanticsUpdate update) { },
onSemanticsOwnerDisposed: () {
childOnSemanticsOwnerDisposed++;
},
);
root.adoptChild(child);
root.attach(manifold);
final SemanticsHandle childSemantics = child.ensureSemantics();
expect(rootOnSemanticsOwnerCreatedCount, 0);
expect(childOnSemanticsOwnerCreatedCount, 1);
expect(rootOnSemanticsOwnerDisposed, 0);
expect(childOnSemanticsOwnerDisposed, 0);
expect(root.semanticsOwner, isNull);
expect(child.semanticsOwner, isNotNull);
manifold.semanticsEnabled = true;
expect(rootOnSemanticsOwnerCreatedCount, 1);
expect(childOnSemanticsOwnerCreatedCount, 1);
expect(rootOnSemanticsOwnerDisposed, 0);
expect(childOnSemanticsOwnerDisposed, 0);
expect(root.semanticsOwner, isNotNull);
expect(child.semanticsOwner, isNotNull);
manifold.semanticsEnabled = false;
expect(rootOnSemanticsOwnerCreatedCount, 1);
expect(childOnSemanticsOwnerCreatedCount, 1);
expect(rootOnSemanticsOwnerDisposed, 1);
expect(childOnSemanticsOwnerDisposed, 0);
expect(root.semanticsOwner, isNull);
expect(child.semanticsOwner, isNotNull);
childSemantics.dispose();
expect(rootOnSemanticsOwnerCreatedCount, 1);
expect(childOnSemanticsOwnerCreatedCount, 1);
expect(rootOnSemanticsOwnerDisposed, 1);
expect(childOnSemanticsOwnerDisposed, 1);
expect(root.semanticsOwner, isNull);
expect(child.semanticsOwner, isNull);
});
test('PipelineOwner can dispose local handle even when manifold forces semantics to on', () {
final TestPipelineManifold manifold = TestPipelineManifold();
int rootOnSemanticsOwnerCreatedCount = 0;
int rootOnSemanticsOwnerDisposed = 0;
final PipelineOwner root = PipelineOwner(
onSemanticsOwnerCreated: () {
rootOnSemanticsOwnerCreatedCount++;
},
onSemanticsUpdate: (SemanticsUpdate update) { },
onSemanticsOwnerDisposed: () {
rootOnSemanticsOwnerDisposed++;
},
);
int childOnSemanticsOwnerCreatedCount = 0;
int childOnSemanticsOwnerDisposed = 0;
final PipelineOwner child = PipelineOwner(
onSemanticsOwnerCreated: () {
childOnSemanticsOwnerCreatedCount++;
},
onSemanticsUpdate: (SemanticsUpdate update) { },
onSemanticsOwnerDisposed: () {
childOnSemanticsOwnerDisposed++;
},
);
root.adoptChild(child);
root.attach(manifold);
final SemanticsHandle childSemantics = child.ensureSemantics();
expect(rootOnSemanticsOwnerCreatedCount, 0);
expect(childOnSemanticsOwnerCreatedCount, 1);
expect(rootOnSemanticsOwnerDisposed, 0);
expect(childOnSemanticsOwnerDisposed, 0);
expect(root.semanticsOwner, isNull);
expect(child.semanticsOwner, isNotNull);
manifold.semanticsEnabled = true;
expect(rootOnSemanticsOwnerCreatedCount, 1);
expect(childOnSemanticsOwnerCreatedCount, 1);
expect(rootOnSemanticsOwnerDisposed, 0);
expect(childOnSemanticsOwnerDisposed, 0);
expect(root.semanticsOwner, isNotNull);
expect(child.semanticsOwner, isNotNull);
childSemantics.dispose();
expect(rootOnSemanticsOwnerCreatedCount, 1);
expect(childOnSemanticsOwnerCreatedCount, 1);
expect(rootOnSemanticsOwnerDisposed, 0);
expect(childOnSemanticsOwnerDisposed, 0);
expect(root.semanticsOwner, isNotNull);
expect(child.semanticsOwner, isNotNull);
manifold.semanticsEnabled = false;
expect(rootOnSemanticsOwnerCreatedCount, 1);
expect(childOnSemanticsOwnerCreatedCount, 1);
expect(rootOnSemanticsOwnerDisposed, 1);
expect(childOnSemanticsOwnerDisposed, 1);
expect(root.semanticsOwner, isNull);
expect(child.semanticsOwner, isNull);
});
test('can hold on to local handle when manifold turns off semantics', () {
final TestPipelineManifold manifold = TestPipelineManifold();
int rootOnSemanticsOwnerCreatedCount = 0;
int rootOnSemanticsOwnerDisposed = 0;
final PipelineOwner root = PipelineOwner(
onSemanticsOwnerCreated: () {
rootOnSemanticsOwnerCreatedCount++;
},
onSemanticsUpdate: (SemanticsUpdate update) { },
onSemanticsOwnerDisposed: () {
rootOnSemanticsOwnerDisposed++;
},
);
int childOnSemanticsOwnerCreatedCount = 0;
int childOnSemanticsOwnerDisposed = 0;
final PipelineOwner child = PipelineOwner(
onSemanticsOwnerCreated: () {
childOnSemanticsOwnerCreatedCount++;
},
onSemanticsUpdate: (SemanticsUpdate update) { },
onSemanticsOwnerDisposed: () {
childOnSemanticsOwnerDisposed++;
},
);
root.adoptChild(child);
root.attach(manifold);
expect(rootOnSemanticsOwnerCreatedCount, 0);
expect(childOnSemanticsOwnerCreatedCount, 0);
expect(rootOnSemanticsOwnerDisposed, 0);
expect(childOnSemanticsOwnerDisposed, 0);
expect(root.semanticsOwner, isNull);
expect(child.semanticsOwner, isNull);
manifold.semanticsEnabled = true;
expect(rootOnSemanticsOwnerCreatedCount, 1);
expect(childOnSemanticsOwnerCreatedCount, 1);
expect(rootOnSemanticsOwnerDisposed, 0);
expect(childOnSemanticsOwnerDisposed, 0);
expect(root.semanticsOwner, isNotNull);
expect(child.semanticsOwner, isNotNull);
final SemanticsHandle childSemantics = child.ensureSemantics();
expect(rootOnSemanticsOwnerCreatedCount, 1);
expect(childOnSemanticsOwnerCreatedCount, 1);
expect(rootOnSemanticsOwnerDisposed, 0);
expect(childOnSemanticsOwnerDisposed, 0);
expect(root.semanticsOwner, isNotNull);
expect(child.semanticsOwner, isNotNull);
manifold.semanticsEnabled = false;
expect(rootOnSemanticsOwnerCreatedCount, 1);
expect(childOnSemanticsOwnerCreatedCount, 1);
expect(rootOnSemanticsOwnerDisposed, 1);
expect(childOnSemanticsOwnerDisposed, 0);
expect(root.semanticsOwner, isNull);
expect(child.semanticsOwner, isNotNull);
childSemantics.dispose();
expect(rootOnSemanticsOwnerCreatedCount, 1);
expect(childOnSemanticsOwnerCreatedCount, 1);
expect(rootOnSemanticsOwnerDisposed, 1);
expect(childOnSemanticsOwnerDisposed, 1);
expect(root.semanticsOwner, isNull);
expect(child.semanticsOwner, isNull);
});
test('cannot attach when already attached', () {
final TestPipelineManifold manifold = TestPipelineManifold();
final PipelineOwner owner = PipelineOwner();
owner.attach(manifold);
expect(() => owner.attach(manifold), throwsAssertionError);
});
test('attach update semanticsOwner', () {
final TestPipelineManifold manifold = TestPipelineManifold()
..semanticsEnabled = true;
final PipelineOwner owner = PipelineOwner(
onSemanticsUpdate: (_) { },
);
expect(owner.semanticsOwner, isNull);
owner.attach(manifold);
expect(owner.semanticsOwner, isNotNull);
});
test('attach does not request visual update if nothing is dirty', () {
final TestPipelineManifold manifold = TestPipelineManifold();
final TestRenderObject renderObject = TestRenderObject();
final PipelineOwner owner = PipelineOwner();
owner.rootNode = renderObject;
expect(manifold.requestVisualUpdateCount, 0);
owner.attach(manifold);
expect(manifold.requestVisualUpdateCount, 0);
});
test('cannot detach when not attached', () {
final PipelineOwner owner = PipelineOwner();
expect(() => owner.detach(), throwsAssertionError);
});
test('cannot adopt twice', () {
final PipelineOwner root = PipelineOwner();
final PipelineOwner child = PipelineOwner();
root.adoptChild(child);
expect(() => root.adoptChild(child), throwsAssertionError);
});
test('cannot adopt child of other parent', () {
final PipelineOwner root = PipelineOwner();
final PipelineOwner child = PipelineOwner();
final PipelineOwner otherRoot = PipelineOwner();
root.adoptChild(child);
expect(() => otherRoot.adoptChild(child), throwsAssertionError);
});
test('adopting creates semantics owner if necessary', () {
final TestPipelineManifold manifold = TestPipelineManifold();
final PipelineOwner root = PipelineOwner(
onSemanticsUpdate: (_) { },
);
final PipelineOwner child = PipelineOwner(
onSemanticsUpdate: (_) { },
);
final PipelineOwner childOfChild = PipelineOwner(
onSemanticsUpdate: (_) { },
);
root.attach(manifold);
expect(root.semanticsOwner, isNull);
expect(child.semanticsOwner, isNull);
expect(childOfChild.semanticsOwner, isNull);
root.adoptChild(child);
expect(root.semanticsOwner, isNull);
expect(child.semanticsOwner, isNull);
expect(childOfChild.semanticsOwner, isNull);
manifold.semanticsEnabled = true;
expect(root.semanticsOwner, isNotNull);
expect(child.semanticsOwner, isNotNull);
expect(childOfChild.semanticsOwner, isNull);
child.adoptChild(childOfChild);
expect(root.semanticsOwner, isNotNull);
expect(child.semanticsOwner, isNotNull);
expect(childOfChild.semanticsOwner, isNotNull);
});
test('cannot drop unattached child', () {
final PipelineOwner root = PipelineOwner();
final PipelineOwner child = PipelineOwner();
expect(() => root.dropChild(child), throwsAssertionError);
});
test('cannot drop child attached to other parent', () {
final PipelineOwner root = PipelineOwner();
final PipelineOwner child = PipelineOwner();
final PipelineOwner otherRoot = PipelineOwner();
otherRoot.adoptChild(child);
expect(() => root.dropChild(child), throwsAssertionError);
});
test('dropping destroys semantics owner if necessary', () {
final TestPipelineManifold manifold = TestPipelineManifold()
..semanticsEnabled = true;
final PipelineOwner root = PipelineOwner(
onSemanticsUpdate: (_) { },
);
final PipelineOwner child = PipelineOwner(
onSemanticsUpdate: (_) { },
);
final PipelineOwner childOfChild = PipelineOwner(
onSemanticsUpdate: (_) { },
);
root.attach(manifold);
root.adoptChild(child);
child.adoptChild(childOfChild);
expect(root.semanticsOwner, isNotNull);
expect(child.semanticsOwner, isNotNull);
expect(childOfChild.semanticsOwner, isNotNull);
child.dropChild(childOfChild);
expect(root.semanticsOwner, isNotNull);
expect(child.semanticsOwner, isNotNull);
expect(childOfChild.semanticsOwner, isNotNull); // Retained in case we get re-attached.
final SemanticsHandle childSemantics = child.ensureSemantics();
root.dropChild(child);
expect(root.semanticsOwner, isNotNull);
expect(child.semanticsOwner, isNotNull);
expect(childOfChild.semanticsOwner, isNotNull); // Retained in case we get re-attached.
childSemantics.dispose();
expect(root.semanticsOwner, isNotNull);
expect(child.semanticsOwner, isNull);
expect(childOfChild.semanticsOwner, isNotNull);
manifold.semanticsEnabled = false;
expect(root.semanticsOwner, isNull);
expect(childOfChild.semanticsOwner, isNotNull);
root.adoptChild(childOfChild);
expect(root.semanticsOwner, isNull);
expect(childOfChild.semanticsOwner, isNull); // Disposed on re-attachment.
manifold.semanticsEnabled = true;
expect(root.semanticsOwner, isNotNull);
expect(childOfChild.semanticsOwner, isNotNull);
root.dropChild(childOfChild);
expect(root.semanticsOwner, isNotNull);
expect(childOfChild.semanticsOwner, isNotNull);
childOfChild.dispose();
expect(root.semanticsOwner, isNotNull);
expect(childOfChild.semanticsOwner, isNull); // Disposed on dispose.
});
test('can adopt/drop children during own layout', () {
final TestPipelineManifold manifold = TestPipelineManifold();
final PipelineOwner root = PipelineOwner();
final PipelineOwner child1 = PipelineOwner();
final PipelineOwner child2 = PipelineOwner();
final TestRenderObject rootRenderObject = TestRenderObject(
onLayout: () {
child1.dropChild(child2);
root.dropChild(child1);
root.adoptChild(child2);
child2.adoptChild(child1);
},
);
root.rootNode = rootRenderObject;
rootRenderObject.scheduleInitialLayout();
root.adoptChild(child1);
child1.adoptChild(child2);
root.attach(manifold);
expect(_treeWalk(root), <PipelineOwner>[root, child1, child2]);
root.flushLayout();
expect(_treeWalk(root), <PipelineOwner>[root, child2, child1]);
});
test('cannot adopt/drop children during child layout', () {
final TestPipelineManifold manifold = TestPipelineManifold();
final PipelineOwner root = PipelineOwner();
final PipelineOwner child1 = PipelineOwner();
final PipelineOwner child2 = PipelineOwner();
final PipelineOwner child3 = PipelineOwner();
Object? droppingError;
Object? adoptingError;
final TestRenderObject childRenderObject = TestRenderObject(
onLayout: () {
child1.dropChild(child2);
child1.adoptChild(child3);
try {
root.dropChild(child1);
} catch (e) {
droppingError = e;
}
try {
root.adoptChild(child2);
} catch (e) {
adoptingError = e;
}
},
);
child1.rootNode = childRenderObject;
childRenderObject.scheduleInitialLayout();
root.adoptChild(child1);
child1.adoptChild(child2);
root.attach(manifold);
expect(_treeWalk(root), <PipelineOwner>[root, child1, child2]);
root.flushLayout();
expect(adoptingError, isAssertionError.having((AssertionError e) => e.message, 'message', contains('Cannot modify child list after layout.')));
expect(droppingError, isAssertionError.having((AssertionError e) => e.message, 'message', contains('Cannot modify child list after layout.')));
});
test('visitChildren visits all children', () {
final PipelineOwner root = PipelineOwner();
final PipelineOwner child1 = PipelineOwner();
final PipelineOwner child2 = PipelineOwner();
final PipelineOwner child3 = PipelineOwner();
final PipelineOwner childOfChild3 = PipelineOwner();
root.adoptChild(child1);
root.adoptChild(child2);
root.adoptChild(child3);
child3.adoptChild(childOfChild3);
final List<PipelineOwner> children = <PipelineOwner>[];
root.visitChildren((PipelineOwner child) {
children.add(child);
});
expect(children, <PipelineOwner>[child1, child2, child3]);
children.clear();
child3.visitChildren((PipelineOwner child) {
children.add(child);
});
expect(children.single, childOfChild3);
});
test('printing pipeline owner tree smoke test', () {
final PipelineOwner root = PipelineOwner();
final PipelineOwner child1 = PipelineOwner()
..rootNode = FakeRenderView();
final PipelineOwner childOfChild1 = PipelineOwner()
..rootNode = FakeRenderView();
final PipelineOwner child2 = PipelineOwner()
..rootNode = FakeRenderView();
final PipelineOwner childOfChild2 = PipelineOwner()
..rootNode = FakeRenderView();
root.adoptChild(child1);
child1.adoptChild(childOfChild1);
root.adoptChild(child2);
child2.adoptChild(childOfChild2);
expect(root.toStringDeep(), equalsIgnoringHashCodes(
'PipelineOwner#00000\n'
' ├─PipelineOwner#00000\n'
' │ │ rootNode: FakeRenderView#00000 NEEDS-LAYOUT NEEDS-PAINT\n'
' │ │\n'
' │ └─PipelineOwner#00000\n'
' │ rootNode: FakeRenderView#00000 NEEDS-LAYOUT NEEDS-PAINT\n'
' │\n'
' └─PipelineOwner#00000\n'
' │ rootNode: FakeRenderView#00000 NEEDS-LAYOUT NEEDS-PAINT\n'
' │\n'
' └─PipelineOwner#00000\n'
' rootNode: FakeRenderView#00000 NEEDS-LAYOUT NEEDS-PAINT\n'
));
});
}
class TestPipelineManifold extends ChangeNotifier implements PipelineManifold {
int requestVisualUpdateCount = 0;
@override
void requestVisualUpdate() {
requestVisualUpdateCount++;
}
@override
bool get semanticsEnabled => _semanticsEnabled;
bool _semanticsEnabled = false;
set semanticsEnabled(bool value) {
if (value == _semanticsEnabled) {
return;
}
_semanticsEnabled = value;
notifyListeners();
}
}
class TestRenderObject extends RenderObject {
TestRenderObject({this.onLayout, this.onPaint, this.onSemantics});
final VoidCallback? onLayout;
final VoidCallback? onPaint;
final VoidCallback? onSemantics;
@override
bool get isRepaintBoundary => true;
@override
void debugAssertDoesMeetConstraints() { }
@override
Rect get paintBounds => Rect.zero;
@override
void performLayout() {
onLayout?.call();
}
@override
void paint(PaintingContext context, Offset offset) {
onPaint?.call();
}
@override
void describeSemanticsConfiguration(SemanticsConfiguration config) {
onSemantics?.call();
}
@override
void performResize() { }
@override
Rect get semanticBounds => Rect.zero;
}
List<PipelineOwner> _treeWalk(PipelineOwner root) {
final List<PipelineOwner> results = <PipelineOwner>[root];
void visitor(PipelineOwner child) {
results.add(child);
child.visitChildren(visitor);
}
root.visitChildren(visitor);
return results;
}
class FakeRenderView extends RenderBox { }
| flutter/packages/flutter/test/rendering/pipeline_owner_tree_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/pipeline_owner_tree_test.dart",
"repo_id": "flutter",
"token_count": 10221
} | 677 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'rendering_tester.dart';
void main() {
TestRenderingFlutterBinding.ensureInitialized();
test('RenderViewport calculates correct constraints, RenderSliverToBoxAdapter calculates correct geometry', () {
final List<RenderSliver> children = List<RenderSliver>.generate(30, (int index) {
return RenderSliverToBoxAdapter(
child: RenderSizedBox(const Size(400.0, 100.0)),
);
});
// Viewport is 800x600, can show 6 children at a time.
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
cacheExtent: 250.0,
children: children,
);
layout(root);
RenderSliver firstVisible = children[0];
expectSliverConstraints(
sliver: firstVisible,
cacheOrigin: 0.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 600.0 + 250.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: firstVisible,
paintExtent: 100.0,
cacheExtent: 100.0,
visible: true,
);
RenderSliver lastVisible = children[5];
expectSliverConstraints(
sliver: lastVisible,
cacheOrigin: 0.0,
remainingPaintExtent: 100.0,
remainingCacheExtent: 350.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: lastVisible,
paintExtent: 100.0,
cacheExtent: 100.0,
visible: true,
);
RenderSliver firstInCache = children[6];
expectSliverConstraints(
sliver: firstInCache,
cacheOrigin: 0.0,
remainingPaintExtent: 0.0,
remainingCacheExtent: 250.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: firstInCache,
paintExtent: 0.0,
cacheExtent: 100.0,
visible: false,
);
RenderSliver lastInCache = children[8];
expectSliverConstraints(
sliver: lastInCache,
cacheOrigin: 0.0,
remainingPaintExtent: 0.0,
remainingCacheExtent: 50.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: lastInCache,
paintExtent: 0.0,
cacheExtent: 50.0,
visible: false,
);
RenderSliver outsideCache = children[9];
expectSliverConstraints(
sliver: outsideCache,
cacheOrigin: 0.0,
remainingPaintExtent: 0.0,
remainingCacheExtent: 0.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: outsideCache,
paintExtent: 0.0,
cacheExtent: 0.0,
visible: false,
);
// scroll down half a sliver
root.offset = ViewportOffset.fixed(50.0);
pumpFrame();
firstVisible = children[0];
expectSliverConstraints(
sliver: firstVisible,
cacheOrigin: -50.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 50.0 + 600.0 + 250.0,
scrollOffset: 50.0,
);
expectSliverGeometry(
sliver: firstVisible,
paintExtent: 50.0,
cacheExtent: 100.0,
visible: true,
);
lastVisible = children[6];
expectSliverConstraints(
sliver: lastVisible,
cacheOrigin: 0.0,
remainingPaintExtent: 50.0,
remainingCacheExtent: 300.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: lastVisible,
paintExtent: 50.0,
cacheExtent: 100.0,
visible: true,
);
firstInCache = children[7];
expectSliverConstraints(
sliver: firstInCache,
cacheOrigin: 0.0,
remainingPaintExtent: 0.0,
remainingCacheExtent: 200.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: firstInCache,
paintExtent: 0.0,
cacheExtent: 100.0,
visible: false,
);
lastInCache = children[8];
expectSliverConstraints(
sliver: lastInCache,
cacheOrigin: 0.0,
remainingPaintExtent: 0.0,
remainingCacheExtent: 100.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: lastInCache,
paintExtent: 0.0,
cacheExtent: 100.0,
visible: false,
);
outsideCache = children[9];
expectSliverConstraints(
sliver: outsideCache,
cacheOrigin: 0.0,
remainingPaintExtent: 0.0,
remainingCacheExtent: 0.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: outsideCache,
paintExtent: 0.0,
cacheExtent: 0.0,
visible: false,
);
// scroll down 1.5 slivers
root.offset = ViewportOffset.fixed(150.0);
pumpFrame();
RenderSliver firstInPreCache = children[0];
expectSliverConstraints(
sliver: firstInPreCache,
cacheOrigin: -150.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 150.0 + 600.0 + 250.0,
scrollOffset: 150.0,
);
expectSliverGeometry(
sliver: firstInPreCache,
paintExtent: 0.0,
cacheExtent: 100.0,
visible: false,
);
firstVisible = children[1];
expectSliverConstraints(
sliver: firstVisible,
cacheOrigin: -50.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 50.0 + 600.0 + 250.0,
scrollOffset: 50.0,
);
expectSliverGeometry(
sliver: firstVisible,
paintExtent: 50.0,
cacheExtent: 100.0,
visible: true,
);
// scroll down 10 slivers
root.offset = ViewportOffset.fixed(1000.0);
pumpFrame();
final RenderSliver first = children[0];
expectSliverConstraints(
sliver: first,
cacheOrigin: -250.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 250.0 + 600.0 + 250.0,
scrollOffset: 1000.0,
);
expectSliverGeometry(
sliver: first,
paintExtent: 0.0,
cacheExtent: 0.0,
visible: false,
);
firstInPreCache = children[7];
expectSliverConstraints(
sliver: firstInPreCache,
cacheOrigin: -250.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 250.0 + 600.0 + 250.0,
scrollOffset: 300.0,
);
expectSliverGeometry(
sliver: firstInPreCache,
paintExtent: 0.0,
cacheExtent: 50.0,
visible: false,
);
final RenderSliver lastInPreCache = children[9];
expectSliverConstraints(
sliver: lastInPreCache,
cacheOrigin: -100.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 100.0 + 600.0 + 250.0,
scrollOffset: 100.0,
);
expectSliverGeometry(
sliver: lastInPreCache,
paintExtent: 0.0,
cacheExtent: 100.0,
visible: false,
);
firstVisible = children[10];
expectSliverConstraints(
sliver: firstVisible,
cacheOrigin: 0.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 600.0 + 250.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: firstVisible,
paintExtent: 100.0,
cacheExtent: 100.0,
visible: true,
);
});
test('RenderSliverFixedExtentList calculates correct geometry', () {
// Viewport is 800x600, can show 6 full children at a time
final List<RenderBox> children = List<RenderBox>.generate(30, (int index) {
return RenderSizedBox(const Size(400.0, 100.0));
});
final TestRenderSliverBoxChildManager childManager = TestRenderSliverBoxChildManager(
children: children,
);
RenderSliverFixedExtentList inner;
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
cacheExtent: 250.0,
children: <RenderSliver>[
inner = childManager.createRenderSliverFixedExtentList(),
],
);
layout(root);
expectSliverConstraints(
sliver: inner,
cacheOrigin: 0.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 600.0 + 250.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: inner,
paintExtent: 600.0,
cacheExtent: 850.0,
visible: true,
);
expect(children.sublist(0, 9).every((RenderBox r) => r.attached), true);
expect(children.sublist(9, 30).any((RenderBox r) => r.attached), false);
// scroll half an item down
root.offset = ViewportOffset.fixed(50.0);
pumpFrame();
expectSliverConstraints(
sliver: inner,
cacheOrigin: -50.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 50.0 + 600.0 + 250.0,
scrollOffset: 50.0,
);
expectSliverGeometry(
sliver: inner,
paintExtent: 600.0,
cacheExtent: 900.0,
visible: true,
);
expect(children.sublist(0, 9).every((RenderBox r) => r.attached), true);
expect(children.sublist(9, 30).any((RenderBox r) => r.attached), false);
// scroll to the middle
root.offset = ViewportOffset.fixed(1500.0);
pumpFrame();
expectSliverConstraints(
sliver: inner,
cacheOrigin: -250.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 250.0 + 600.0 + 250.0,
scrollOffset: 1500.0,
);
expectSliverGeometry(
sliver: inner,
paintExtent: 600.0,
cacheExtent: 1100.0,
visible: true,
);
expect(children.sublist(0, 12).any((RenderBox r) => r.attached), false);
expect(children.sublist(12, 24).every((RenderBox r) => r.attached), true);
expect(children.sublist(24, 30).any((RenderBox r) => r.attached), false);
// scroll to the end
root.offset = ViewportOffset.fixed(2400.0);
pumpFrame();
expectSliverConstraints(
sliver: inner,
cacheOrigin: -250.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 250.0 + 600.0 + 250.0,
scrollOffset: 2400.0,
);
expectSliverGeometry(
sliver: inner,
paintExtent: 600.0,
cacheExtent: 850.0,
visible: true,
);
expect(children.sublist(0, 21).any((RenderBox r) => r.attached), false);
expect(children.sublist(21, 30).every((RenderBox r) => r.attached), true);
});
test('RenderSliverList calculates correct geometry', () {
// Viewport is 800x600, can show 6 full children at a time
final List<RenderBox> children = List<RenderBox>.generate(30, (int index) {
return RenderSizedBox(const Size(400.0, 100.0));
});
final TestRenderSliverBoxChildManager childManager = TestRenderSliverBoxChildManager(
children: children,
);
RenderSliverList inner;
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
cacheExtent: 250.0,
children: <RenderSliver>[
inner = childManager.createRenderSliverList(),
],
);
layout(root);
expectSliverConstraints(
sliver: inner,
cacheOrigin: 0.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 600.0 + 250.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: inner,
paintExtent: 600.0,
cacheExtent: 850.0,
visible: true,
);
expect(children.sublist(0, 9).every((RenderBox r) => r.attached), true);
expect(children.sublist(9, 30).any((RenderBox r) => r.attached), false);
// scroll half an item down
root.offset = ViewportOffset.fixed(50.0);
pumpFrame();
expectSliverConstraints(
sliver: inner,
cacheOrigin: -50.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 50.0 + 600.0 + 250.0,
scrollOffset: 50.0,
);
expectSliverGeometry(
sliver: inner,
paintExtent: 600.0,
cacheExtent: 900.0,
visible: true,
);
expect(children.sublist(0, 9).every((RenderBox r) => r.attached), true);
expect(children.sublist(9, 30).any((RenderBox r) => r.attached), false);
// scroll to the middle
root.offset = ViewportOffset.fixed(1500.0);
pumpFrame();
expectSliverConstraints(
sliver: inner,
cacheOrigin: -250.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 250.0 + 600.0 + 250.0,
scrollOffset: 1500.0,
);
expectSliverGeometry(
sliver: inner,
paintExtent: 600.0,
cacheExtent: 1100.0,
visible: true,
);
expect(children.sublist(0, 12).any((RenderBox r) => r.attached), false);
expect(children.sublist(12, 24).every((RenderBox r) => r.attached), true);
expect(children.sublist(24, 30).any((RenderBox r) => r.attached), false);
// scroll to the end
root.offset = ViewportOffset.fixed(2400.0);
pumpFrame();
expectSliverConstraints(
sliver: inner,
cacheOrigin: -250.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 250.0 + 600.0 + 250.0,
scrollOffset: 2400.0,
);
expectSliverGeometry(
sliver: inner,
paintExtent: 600.0,
cacheExtent: 850.0,
visible: true,
);
expect(children.sublist(0, 21).any((RenderBox r) => r.attached), false);
expect(children.sublist(21, 30).every((RenderBox r) => r.attached), true);
});
test('RenderSliverGrid calculates correct geometry', () {
// Viewport is 800x600, each grid element is 400x100, giving us space for 12 visible children
final List<RenderBox> children = List<RenderBox>.generate(60, (int index) {
return RenderSizedBox(const Size(400.0, 100.0));
});
final TestRenderSliverBoxChildManager childManager = TestRenderSliverBoxChildManager(
children: children,
);
RenderSliverGrid inner;
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
cacheExtent: 250.0,
children: <RenderSliver>[
inner = childManager.createRenderSliverGrid(),
],
);
layout(root);
expectSliverConstraints(
sliver: inner,
cacheOrigin: 0.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 600.0 + 250.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: inner,
paintExtent: 600.0,
cacheExtent: 850.0,
visible: true,
);
expect(children.sublist(0, 18).every((RenderBox r) => r.attached), true);
expect(children.sublist(18, 60).any((RenderBox r) => r.attached), false);
// scroll half an item down
root.offset = ViewportOffset.fixed(50.0);
pumpFrame();
expectSliverConstraints(
sliver: inner,
cacheOrigin: -50.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 50.0 + 600.0 + 250.0,
scrollOffset: 50.0,
);
expectSliverGeometry(
sliver: inner,
paintExtent: 600.0,
cacheExtent: 900.0,
visible: true,
);
expect(children.sublist(0, 18).every((RenderBox r) => r.attached), true);
expect(children.sublist(18, 60).any((RenderBox r) => r.attached), false);
// scroll to the middle
root.offset = ViewportOffset.fixed(1500.0);
pumpFrame();
expectSliverConstraints(
sliver: inner,
cacheOrigin: -250.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 250.0 + 600.0 + 250.0,
scrollOffset: 1500.0,
);
expectSliverGeometry(
sliver: inner,
paintExtent: 600.0,
cacheExtent: 1100.0,
visible: true,
);
expect(children.sublist(0, 24).any((RenderBox r) => r.attached), false);
expect(children.sublist(24, 48).every((RenderBox r) => r.attached), true);
expect(children.sublist(48, 60).any((RenderBox r) => r.attached), false);
// scroll to the end
root.offset = ViewportOffset.fixed(2400.0);
pumpFrame();
expectSliverConstraints(
sliver: inner,
cacheOrigin: -250.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 250.0 + 600.0 + 250.0,
scrollOffset: 2400.0,
);
expectSliverGeometry(
sliver: inner,
paintExtent: 600.0,
cacheExtent: 850.0,
visible: true,
);
expect(children.sublist(0, 42).any((RenderBox r) => r.attached), false);
expect(children.sublist(42, 60).every((RenderBox r) => r.attached), true);
});
test('RenderSliverPadding calculates correct geometry', () {
// Viewport is 800x600, each item is 100px high with 50px before and after = 200px
final List<RenderSliverToBoxAdapter> adapters = <RenderSliverToBoxAdapter>[];
final List<RenderSliverPadding> paddings = List<RenderSliverPadding>.generate(30, (int index) {
RenderSliverToBoxAdapter adapter;
final RenderSliverPadding padding = RenderSliverPadding(
padding: const EdgeInsets.symmetric(vertical: 50.0),
child: adapter = RenderSliverToBoxAdapter(
child: RenderSizedBox(const Size(400.0, 100.0)),
),
);
adapters.add(adapter);
return padding;
});
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
cacheExtent: 250.0,
children: paddings,
);
layout(root);
RenderSliverPadding firstVisiblePadding = paddings[0];
expectSliverConstraints(
sliver: firstVisiblePadding,
cacheOrigin: 0.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 600.0 + 250.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: firstVisiblePadding,
paintExtent: 200.0,
cacheExtent: 200.0,
visible: true,
);
RenderSliverToBoxAdapter firstVisiblePadded = adapters[0];
expectSliverConstraints(
sliver: firstVisiblePadded,
cacheOrigin: 0.0,
remainingPaintExtent: 550.0,
remainingCacheExtent: 600.0 + 250.0 - 50.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: firstVisiblePadded,
paintExtent: 100.0,
cacheExtent: 100.0,
visible: true,
);
RenderSliverPadding lastVisiblePadding = paddings[2];
expectSliverConstraints(
sliver: lastVisiblePadding,
cacheOrigin: 0.0,
remainingPaintExtent: 200.0,
remainingCacheExtent: 200.0 + 250.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: lastVisiblePadding,
paintExtent: 200.0,
cacheExtent: 200.0,
visible: true,
);
RenderSliverToBoxAdapter lastVisiblePadded = adapters[2];
expectSliverConstraints(
sliver: lastVisiblePadded,
cacheOrigin: 0.0,
remainingPaintExtent: 150.0,
remainingCacheExtent: 200.0 + 250.0 - 50.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: lastVisiblePadded,
paintExtent: 100.0,
cacheExtent: 100.0,
visible: true,
);
final RenderSliverPadding firstCachePadding = paddings[3];
expectSliverConstraints(
sliver: firstCachePadding,
cacheOrigin: 0.0,
remainingPaintExtent: 0.0,
remainingCacheExtent: 250.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: firstCachePadding,
paintExtent: 0.0,
cacheExtent: 200.0,
visible: false,
);
final RenderSliverToBoxAdapter firstCachePadded = adapters[3];
expectSliverConstraints(
sliver: firstCachePadded,
cacheOrigin: 0.0,
remainingPaintExtent: 0.0,
remainingCacheExtent: 250.0 - 50.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: firstCachePadded,
paintExtent: 0.0,
cacheExtent: 100.0,
visible: false,
);
final RenderSliverPadding lastCachePadding = paddings[4];
expectSliverConstraints(
sliver: lastCachePadding,
cacheOrigin: 0.0,
remainingPaintExtent: 0.0,
remainingCacheExtent: 50.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: lastCachePadding,
paintExtent: 0.0,
cacheExtent: 50.0,
visible: false,
);
final RenderSliverToBoxAdapter lastCachePadded = adapters[4];
expectSliverConstraints(
sliver: lastCachePadded,
cacheOrigin: 0.0,
remainingPaintExtent: 0.0,
remainingCacheExtent: 0.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: lastCachePadded,
paintExtent: 0.0,
cacheExtent: 0.0,
visible: false,
);
// scroll first padding off screen
root.offset = ViewportOffset.fixed(50.0);
pumpFrame();
firstVisiblePadding = paddings[0];
expectSliverConstraints(
sliver: firstVisiblePadding,
cacheOrigin: -50.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 50.0 + 600.0 + 250.0,
scrollOffset: 50.0,
);
expectSliverGeometry(
sliver: firstVisiblePadding,
paintExtent: 150.0,
cacheExtent: 200.0,
visible: true,
);
firstVisiblePadded = adapters[0];
expectSliverConstraints(
sliver: firstVisiblePadded,
cacheOrigin: 0.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 600.0 + 250.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: firstVisiblePadded,
paintExtent: 100.0,
cacheExtent: 100.0,
visible: true,
);
// scroll to the end
root.offset = ViewportOffset.fixed(5400.0);
pumpFrame();
final RenderSliverPadding firstPadding = paddings[0];
expectSliverConstraints(
sliver: firstPadding,
cacheOrigin: -250.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 250.0 + 600.0 + 250.0,
scrollOffset: 5400.0,
);
expectSliverGeometry(
sliver: firstPadding,
paintExtent: 0.0,
cacheExtent: 0.0,
visible: false,
);
final RenderSliverToBoxAdapter firstPadded = adapters[0];
expectSliverConstraints(
sliver: firstPadded,
cacheOrigin: -200.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 250.0 + 600.0 + 250.0,
scrollOffset: 5350.0,
);
expectSliverGeometry(
sliver: firstPadded,
paintExtent: 0.0,
cacheExtent: 0.0,
visible: false,
);
final RenderSliverPadding firstPreCachePadding = paddings[25];
expectSliverConstraints(
sliver: firstPreCachePadding,
cacheOrigin: -250.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 250.0 + 600.0 + 250.0,
scrollOffset: 400.0,
);
expectSliverGeometry(
sliver: firstPreCachePadding,
paintExtent: 0.0,
cacheExtent: 50.0,
visible: false,
);
final RenderSliverToBoxAdapter firstPreCachePadded = adapters[25];
expectSliverConstraints(
sliver: firstPreCachePadded,
cacheOrigin: -200.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 250.0 + 600.0 + 250.0,
scrollOffset: 350.0,
);
expectSliverGeometry(
sliver: firstPreCachePadded,
paintExtent: 0.0,
cacheExtent: 0.0,
visible: false,
);
final RenderSliverPadding lastPreCachePadding = paddings[26];
expectSliverConstraints(
sliver: lastPreCachePadding,
cacheOrigin: -200.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 200.0 + 600.0 + 250.0,
scrollOffset: 200.0,
);
expectSliverGeometry(
sliver: lastPreCachePadding,
paintExtent: 0.0,
cacheExtent: 200.0,
visible: false,
);
final RenderSliverToBoxAdapter lastPreCachePadded = adapters[26];
expectSliverConstraints(
sliver: lastPreCachePadded,
cacheOrigin: -150.0,
remainingPaintExtent: 600.0,
remainingCacheExtent: 150.0 + 600.0 + 250.0,
scrollOffset: 150.0,
);
expectSliverGeometry(
sliver: lastPreCachePadded,
paintExtent: 0.0,
cacheExtent: 100.0,
visible: false,
);
lastVisiblePadding = paddings[29];
expectSliverConstraints(
sliver: lastVisiblePadding,
cacheOrigin: 0.0,
remainingPaintExtent: 200.0,
remainingCacheExtent: 200.0 + 250.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: lastVisiblePadding,
paintExtent: 200.0,
cacheExtent: 200.0,
visible: true,
);
lastVisiblePadded = adapters[29];
expectSliverConstraints(
sliver: lastVisiblePadded,
cacheOrigin: 0.0,
remainingPaintExtent: 150.0,
remainingCacheExtent: 150.0 + 250.0,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: lastVisiblePadded,
paintExtent: 100.0,
cacheExtent: 100.0,
visible: true,
);
});
group('RenderSliverFillRemaining calculates correct geometry', () {
test('when initially in view', () {
// Viewport is 800x600
const double viewportHeight = 600;
const double viewportWidth = 800;
const double cacheExtent = 250.0;
const double beginningViewportCacheExtent = viewportHeight + cacheExtent;
const double firstSliverHeight = 400;
const double sliverFillRemainingChildHeight = 100.0;
final List<RenderSliver> slivers = <RenderSliver>[
RenderSliverToBoxAdapter(
child: RenderSizedBox(const Size(400.0, firstSliverHeight)),
),
RenderSliverFillRemaining(
child: RenderSizedBox(const Size(100.0, sliverFillRemainingChildHeight)),
)
];
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
cacheExtent: cacheExtent,
children: slivers,
);
layout(root);
final RenderSliver firstVisibleSliver = slivers[0];
expectSliverConstraints(
sliver: firstVisibleSliver,
cacheOrigin: 0.0,
remainingPaintExtent: viewportHeight,
remainingCacheExtent: beginningViewportCacheExtent,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: firstVisibleSliver,
paintExtent: firstSliverHeight,
cacheExtent: firstSliverHeight,
visible: true,
);
// With RenderSliverFillRemaining:
// * The child has a minExtent and maxExtent of the remaining space of the
// viewportMainAxisExtent or the height of the child - whichever is larger.
// * The sliver has a paintExtent of the child's minExtent/maxExtent or the
// remainingPaintExtent - whichever is smaller.
// * The sliver has a cacheExtent of the child's minExtent/maxExtent or the
// remainingCacheExtent - whichever is smaller.
final RenderSliverSingleBoxAdapter sliverFillRemaining = slivers[1] as RenderSliverSingleBoxAdapter;
const double extentOfChild = viewportHeight - firstSliverHeight;
double remainingPaintExtent = viewportHeight - firstSliverHeight;
double remainingCacheExtent = beginningViewportCacheExtent - firstSliverHeight;
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: extentOfChild,
minHeight: extentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: extentOfChild,
cacheExtent: extentOfChild,
visible: true,
);
// Overscroll
const double scrollOffset = 50;
root.offset = ViewportOffset.fixed(scrollOffset);
pumpFrame();
remainingPaintExtent = viewportHeight - firstSliverHeight + scrollOffset;
remainingCacheExtent = beginningViewportCacheExtent - firstSliverHeight + scrollOffset;
// With RenderSliverFillRemaining, when you overscroll, the extent of the
// child does not change and therefore neither does paintExtent or cacheExtent.
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: extentOfChild,
minHeight: extentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: extentOfChild,
cacheExtent: extentOfChild,
visible: true,
);
});
test('when scrolled into view', () {
// Viewport is 800x600
const double viewportHeight = 600;
const double viewportWidth = 800;
const double cacheExtent = 250.0;
const double beginningViewportCacheExtent = viewportHeight + cacheExtent;
const double firstSliverHeight = beginningViewportCacheExtent;
const double sliverFillRemainingChildHeight = 100.0;
final List<RenderSliver> slivers = <RenderSliver>[
RenderSliverToBoxAdapter(
child: RenderSizedBox(const Size(400.0, firstSliverHeight)),
),
RenderSliverFillRemaining(
child: RenderSizedBox(const Size(100.0, sliverFillRemainingChildHeight)),
)
];
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
cacheExtent: cacheExtent,
children: slivers,
);
layout(root);
final RenderSliver firstVisibleSliver = slivers[0];
expectSliverConstraints(
sliver: firstVisibleSliver,
cacheOrigin: 0.0,
remainingPaintExtent: viewportHeight,
remainingCacheExtent: beginningViewportCacheExtent,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: firstVisibleSliver,
paintExtent: viewportHeight,
cacheExtent: firstSliverHeight,
visible: true,
);
// With RenderSliverFillRemaining:
// * The child has a minExtent and maxExtent of the remaining space of the
// viewportMainAxisExtent or the height of the child - whichever is larger.
// * The sliver has a paintExtent of the child's minExtent/maxExtent or the
// remainingPaintExtent - whichever is smaller.
// * The sliver has a cacheExtent of the child's minExtent/maxExtent or the
// remainingCacheExtent - whichever is smaller.
final RenderSliverSingleBoxAdapter sliverFillRemaining = slivers[1] as RenderSliverSingleBoxAdapter;
const double extentOfChild = sliverFillRemainingChildHeight;
double remainingPaintExtent = 0;
double remainingCacheExtent = 0;
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: extentOfChild,
minHeight: extentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: remainingPaintExtent,
cacheExtent: remainingCacheExtent,
visible: false,
);
// Scroll so RenderSliverFillRemaining is not within viewport, but is
// within remainingCacheExtent.
root.offset = ViewportOffset.fixed(cacheExtent);
pumpFrame();
remainingPaintExtent = 0;
remainingCacheExtent = cacheExtent;
// When within the remainingCacheExtent, the sliver will have a cacheExtent
// of the child's extent.
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: extentOfChild,
minHeight: extentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: remainingPaintExtent,
cacheExtent: extentOfChild,
visible: false,
);
// Scroll so RenderSliverFillRemaining is partially within viewport.
root.offset = ViewportOffset.fixed(cacheExtent + 50);
pumpFrame();
remainingPaintExtent = 50;
remainingCacheExtent = cacheExtent + 50;
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: extentOfChild,
minHeight: extentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: remainingPaintExtent,
cacheExtent: extentOfChild,
visible: true,
);
// Scroll so RenderSliverFillRemaining is completely within viewport.
root.offset = ViewportOffset.fixed(cacheExtent + sliverFillRemainingChildHeight);
pumpFrame();
remainingPaintExtent = sliverFillRemainingChildHeight;
remainingCacheExtent = cacheExtent + sliverFillRemainingChildHeight;
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: extentOfChild,
minHeight: extentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: extentOfChild,
cacheExtent: extentOfChild,
visible: true,
);
// Overscroll
root.offset = ViewportOffset.fixed(cacheExtent + sliverFillRemainingChildHeight + 50);
pumpFrame();
remainingPaintExtent = sliverFillRemainingChildHeight + 50;
remainingCacheExtent = cacheExtent + sliverFillRemainingChildHeight + 50;
// With RenderSliverFillRemaining, when you overscroll, the extent of the
// child does not change and therefore neither does paintExtent or cacheExtent.
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: extentOfChild,
minHeight: extentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: extentOfChild,
cacheExtent: extentOfChild,
visible: true,
);
});
});
group('RenderSliverFillRemainingAndOverscroll calculates correct geometry', () {
test('when initially in view', () {
// Viewport is 800x600
const double viewportHeight = 600;
const double viewportWidth = 800;
const double cacheExtent = 250.0;
const double beginningViewportCacheExtent = viewportHeight + cacheExtent;
const double firstSliverHeight = 400;
const double sliverFillRemainingChildHeight = 100.0;
final List<RenderSliver> slivers = <RenderSliver>[
RenderSliverToBoxAdapter(
child: RenderSizedBox(const Size(400.0, firstSliverHeight)),
),
RenderSliverFillRemainingAndOverscroll(
child: RenderSizedBox(const Size(100.0, sliverFillRemainingChildHeight)),
)
];
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
cacheExtent: cacheExtent,
children: slivers,
);
layout(root);
final RenderSliver firstVisibleSliver = slivers[0];
expectSliverConstraints(
sliver: firstVisibleSliver,
cacheOrigin: 0.0,
remainingPaintExtent: viewportHeight,
remainingCacheExtent: beginningViewportCacheExtent,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: firstVisibleSliver,
paintExtent: firstSliverHeight,
cacheExtent: firstSliverHeight,
visible: true,
);
// With RenderSliverFillRemainingAndOverscroll:
// * The child has a minExtent of the remaining space of the viewportMainAxisExtent
// or the height of the child - whichever is larger.
// * The child has a maxExtent of the remaining space of the viewportMainAxisExtent,
// the height of the child, or the remainingPaintExtent - whichever is larger.
// * The sliver has a paintExtent of the child's maxExtent or the
// remainingPaintExtent - whichever is smaller.
// * The sliver has a cacheExtent of the child's minExtent or the
// remainingCacheExtent - whichever is smaller.
final RenderSliverSingleBoxAdapter sliverFillRemaining = slivers[1] as RenderSliverSingleBoxAdapter;
const double minExtentOfChild = viewportHeight - firstSliverHeight;
double maxExtentOfChild = viewportHeight - firstSliverHeight;
double remainingPaintExtent = viewportHeight - firstSliverHeight;
double remainingCacheExtent = beginningViewportCacheExtent - firstSliverHeight;
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: maxExtentOfChild,
minHeight: minExtentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: maxExtentOfChild,
cacheExtent: minExtentOfChild,
visible: true,
);
// Overscroll
const double scrollOffset = 50;
root.offset = ViewportOffset.fixed(scrollOffset);
pumpFrame();
remainingPaintExtent = viewportHeight - firstSliverHeight + scrollOffset;
remainingCacheExtent = beginningViewportCacheExtent - firstSliverHeight + scrollOffset;
// When you overscroll, the child's maxExtent is the
// remainingPaintExtent, since it's the higher value.
maxExtentOfChild = remainingPaintExtent;
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: maxExtentOfChild,
minHeight: minExtentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: maxExtentOfChild,
cacheExtent: minExtentOfChild,
visible: true,
);
});
test('when scrolled into view', () {
// Viewport is 800x600
const double viewportHeight = 600;
const double viewportWidth = 800;
const double cacheExtent = 250.0;
const double beginningViewportCacheExtent = viewportHeight + cacheExtent;
const double firstSliverHeight = beginningViewportCacheExtent;
const double sliverFillRemainingChildHeight = 100.0;
final List<RenderSliver> slivers = <RenderSliver>[
RenderSliverToBoxAdapter(
child: RenderSizedBox(const Size(400.0, firstSliverHeight)),
),
RenderSliverFillRemainingAndOverscroll(
child: RenderSizedBox(const Size(100.0, sliverFillRemainingChildHeight)),
)
];
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
cacheExtent: cacheExtent,
children: slivers,
);
layout(root);
final RenderSliver firstVisibleSliver = slivers[0];
expectSliverConstraints(
sliver: firstVisibleSliver,
cacheOrigin: 0.0,
remainingPaintExtent: viewportHeight,
remainingCacheExtent: beginningViewportCacheExtent,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: firstVisibleSliver,
paintExtent: viewportHeight,
cacheExtent: firstSliverHeight,
visible: true,
);
// With RenderSliverFillRemainingAndOverscroll:
// * The child has a minExtent of the remaining space of the viewportMainAxisExtent
// or the height of the child - whichever is larger.
// * The child has a maxExtent of the remaining space of the viewportMainAxisExtent,
// the height of the child, or the remainingPaintExtent - whichever is larger.
// * The sliver has a paintExtent of the child's maxExtent or the
// remainingPaintExtent - whichever is smaller.
// * The sliver has a cacheExtent of the child's minExtent or the
// remainingCacheExtent - whichever is smaller.
final RenderSliverSingleBoxAdapter sliverFillRemaining = slivers[1] as RenderSliverSingleBoxAdapter;
const double minExtentOfChild = sliverFillRemainingChildHeight;
double maxExtentOfChild = sliverFillRemainingChildHeight;
double remainingPaintExtent = 0;
double remainingCacheExtent = 0;
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: maxExtentOfChild,
minHeight: minExtentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: remainingPaintExtent,
cacheExtent: remainingCacheExtent,
visible: false,
);
// Scroll so RenderSliverFillRemainingAndOverscroll is not within viewport,
// but is within remainingCacheExtent.
root.offset = ViewportOffset.fixed(cacheExtent);
pumpFrame();
remainingPaintExtent = 0;
remainingCacheExtent = cacheExtent;
// When within the remainingCacheExtent, the sliver will have a cacheExtent
// of the child's minExtent.
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: maxExtentOfChild,
minHeight: minExtentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: remainingPaintExtent,
cacheExtent: minExtentOfChild,
visible: false,
);
// Scroll so RenderSliverFillRemainingAndOverscroll is partially within
// the viewport.
root.offset = ViewportOffset.fixed(cacheExtent + 50);
pumpFrame();
remainingPaintExtent = 50;
remainingCacheExtent = cacheExtent + 50;
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: maxExtentOfChild,
minHeight: minExtentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: remainingPaintExtent,
cacheExtent: minExtentOfChild,
visible: true,
);
// Scroll so RenderSliverFillRemainingAndOverscroll is completely within
// the viewport.
root.offset = ViewportOffset.fixed(cacheExtent + sliverFillRemainingChildHeight);
pumpFrame();
remainingPaintExtent = sliverFillRemainingChildHeight;
remainingCacheExtent = cacheExtent + sliverFillRemainingChildHeight;
// When completely in view, the slivers's paintExtent is the child's
// maxExtentOfChild, since it's the smaller value.
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: maxExtentOfChild,
minHeight: minExtentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: maxExtentOfChild,
cacheExtent: minExtentOfChild,
visible: true,
);
// Overscroll
root.offset = ViewportOffset.fixed(cacheExtent + sliverFillRemainingChildHeight + 50);
pumpFrame();
remainingPaintExtent = sliverFillRemainingChildHeight + 50;
remainingCacheExtent = cacheExtent + sliverFillRemainingChildHeight + 50;
// When you overscroll, the child's maxExtent is the remainingPaintExtent,
// since it's the higher value.
maxExtentOfChild = remainingPaintExtent;
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: maxExtentOfChild,
minHeight: minExtentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: maxExtentOfChild,
cacheExtent: minExtentOfChild,
visible: true,
);
});
});
group('RenderSliverFillRemainingWithScrollable calculates correct geometry', () {
test('when initially in view', () {
// Viewport is 800x600
const double viewportHeight = 600;
const double viewportWidth = 800;
const double cacheExtent = 250.0;
const double beginningViewportCacheExtent = viewportHeight + cacheExtent;
const double firstSliverHeight = 400;
const double sliverFillRemainingChildHeight = 100.0;
final List<RenderSliver> slivers = <RenderSliver>[
RenderSliverToBoxAdapter(
child: RenderSizedBox(const Size(400.0, firstSliverHeight)),
),
RenderSliverFillRemainingWithScrollable(
child: RenderSizedBox(const Size(100.0, sliverFillRemainingChildHeight)),
)
];
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
cacheExtent: cacheExtent,
children: slivers,
);
layout(root);
final RenderSliver firstVisibleSliver = slivers[0];
expectSliverConstraints(
sliver: firstVisibleSliver,
cacheOrigin: 0.0,
remainingPaintExtent: viewportHeight,
remainingCacheExtent: beginningViewportCacheExtent,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: firstVisibleSliver,
paintExtent: firstSliverHeight,
cacheExtent: firstSliverHeight,
visible: true,
);
// With RenderSliverFillRemainingWithScrollable:
// * The child has a minExtent of the remainingPaintExtent.
// * If not within the viewport but within the cacheExtent, the child has
// a maxExtent of the sliver's cacheExtent. Otherwise, the child has a
// maxExtent of the remainingPaintExtent
// * The sliver has a paintExtent of the child's minExtent or the
// remainingPaintExtent - whichever is smaller.
// * The sliver has a cacheExtent of either the viewportMainAxisExtent or
// the remainingCacheExtent - whichever is smaller.
final RenderSliverSingleBoxAdapter sliverFillRemaining = slivers[1] as RenderSliverSingleBoxAdapter;
double remainingPaintExtent = viewportHeight - firstSliverHeight;
double remainingCacheExtent = beginningViewportCacheExtent - firstSliverHeight;
double minExtentOfChild = remainingPaintExtent;
double maxExtentOfChild = remainingPaintExtent;
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: maxExtentOfChild,
minHeight: minExtentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: minExtentOfChild,
cacheExtent: remainingCacheExtent,
visible: true,
);
// Overscroll so first sliver is partially out of view.
root.offset = ViewportOffset.fixed(50);
pumpFrame();
remainingPaintExtent = viewportHeight - firstSliverHeight + 50;
remainingCacheExtent = beginningViewportCacheExtent - firstSliverHeight + 50;
minExtentOfChild = remainingPaintExtent;
maxExtentOfChild = remainingPaintExtent;
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: maxExtentOfChild,
minHeight: minExtentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: minExtentOfChild,
cacheExtent: remainingCacheExtent,
visible: true,
);
// Overscroll so only RenderSliverFillRemainingWithScrollable is visible.
root.offset = ViewportOffset.fixed(firstSliverHeight);
pumpFrame();
remainingPaintExtent = viewportHeight;
remainingCacheExtent = beginningViewportCacheExtent;
minExtentOfChild = remainingPaintExtent;
maxExtentOfChild = remainingPaintExtent;
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: maxExtentOfChild,
minHeight: minExtentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: minExtentOfChild,
cacheExtent: viewportHeight,
visible: true,
);
});
test('when scrolled into view', () {
// Viewport is 800x600
const double viewportHeight = 600;
const double viewportWidth = 800;
const double cacheExtent = 250.0;
const double beginningViewportCacheExtent = viewportHeight + cacheExtent;
const double firstSliverHeight = beginningViewportCacheExtent;
const double sliverFillRemainingChildHeight = 100.0;
final List<RenderSliver> slivers = <RenderSliver>[
RenderSliverToBoxAdapter(
child: RenderSizedBox(const Size(400.0, firstSliverHeight)),
),
RenderSliverFillRemainingWithScrollable(
child: RenderSizedBox(const Size(100.0, sliverFillRemainingChildHeight)),
)
];
final RenderViewport root = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
cacheExtent: cacheExtent,
children: slivers,
);
layout(root);
final RenderSliver firstVisibleSliver = slivers[0];
expectSliverConstraints(
sliver: firstVisibleSliver,
cacheOrigin: 0.0,
remainingPaintExtent: viewportHeight,
remainingCacheExtent: beginningViewportCacheExtent,
scrollOffset: 0.0,
);
expectSliverGeometry(
sliver: firstVisibleSliver,
paintExtent: viewportHeight,
cacheExtent: firstSliverHeight,
visible: true,
);
// With RenderSliverFillRemainingWithScrollable:
// * The child has a minExtent of the remainingPaintExtent.
// * If not within the viewport but within the cacheExtent, the child has
// a maxExtent of the sliver's cacheExtent. Otherwise, the child has a
// maxExtent of the remainingPaintExtent
// * The sliver has a paintExtent of the child's minExtent or the
// remainingPaintExtent - whichever is smaller.
// * The sliver has a cacheExtent of either the viewportMainAxisExtent or
// the remainingCacheExtent - whichever is smaller.
final RenderSliverSingleBoxAdapter sliverFillRemaining = slivers[1] as RenderSliverSingleBoxAdapter;
double remainingPaintExtent = 0;
double remainingCacheExtent = 0;
double minExtentOfChild = remainingPaintExtent;
double maxExtentOfChild = remainingPaintExtent;
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: maxExtentOfChild,
minHeight: minExtentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: minExtentOfChild,
cacheExtent: remainingCacheExtent,
visible: false,
);
// Scroll so RenderSliverFillRemainingWithScrollable is not within
// viewport, but is within remainingCacheExtent.
root.offset = ViewportOffset.fixed(cacheExtent);
pumpFrame();
remainingPaintExtent = 0;
remainingCacheExtent = cacheExtent;
minExtentOfChild = remainingPaintExtent;
// When RenderSliverFillRemainingWithScrollable is completely outside the
// viewport, but is within the remainingCacheExtent, the child has a
// maxExtent of the slivers's cacheExtent.
maxExtentOfChild = remainingCacheExtent;
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: maxExtentOfChild,
minHeight: minExtentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: minExtentOfChild,
cacheExtent: remainingCacheExtent,
visible: false,
);
// Scroll so RenderSliverFillRemainingWithScrollable is partially within
// viewport.
root.offset = ViewportOffset.fixed(cacheExtent + 50);
pumpFrame();
remainingPaintExtent = 50;
remainingCacheExtent = cacheExtent + 50;
minExtentOfChild = remainingPaintExtent;
maxExtentOfChild = remainingPaintExtent;
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: maxExtentOfChild,
minHeight: minExtentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: minExtentOfChild,
cacheExtent: remainingCacheExtent,
visible: true,
);
// Scroll so RenderSliverFillRemainingWithScrollable takes the entire
// viewport.
root.offset = ViewportOffset.fixed(firstSliverHeight);
pumpFrame();
remainingPaintExtent = viewportHeight;
remainingCacheExtent = beginningViewportCacheExtent;
minExtentOfChild = remainingPaintExtent;
maxExtentOfChild = remainingPaintExtent;
expectSliverConstraints(
sliver: sliverFillRemaining,
cacheOrigin: 0.0,
remainingPaintExtent: remainingPaintExtent,
remainingCacheExtent: remainingCacheExtent,
scrollOffset: 0.0,
);
expectSliverChildConstraints(
sliver: sliverFillRemaining,
maxHeight: maxExtentOfChild,
minHeight: minExtentOfChild,
maxWidth: viewportWidth,
minWidth: viewportWidth,
);
expectSliverGeometry(
sliver: sliverFillRemaining,
paintExtent: minExtentOfChild,
cacheExtent: viewportHeight,
visible: true,
);
});
});
}
void expectSliverConstraints({
required RenderSliver sliver,
required double cacheOrigin,
required double remainingPaintExtent,
required double remainingCacheExtent,
required double scrollOffset,
}) {
expect(sliver.constraints.cacheOrigin, cacheOrigin, reason: 'cacheOrigin');
expect(sliver.constraints.remainingPaintExtent, remainingPaintExtent, reason: 'remainingPaintExtent');
expect(sliver.constraints.remainingCacheExtent, remainingCacheExtent, reason: 'remainingCacheExtent');
expect(sliver.constraints.scrollOffset, scrollOffset, reason: 'scrollOffset');
}
void expectSliverGeometry({
required RenderSliver sliver,
required double paintExtent,
required double cacheExtent,
required bool visible,
}) {
expect(sliver.geometry!.paintExtent, paintExtent, reason: 'paintExtent');
expect(sliver.geometry!.cacheExtent, cacheExtent, reason: 'cacheExtent');
expect(sliver.geometry!.visible, visible, reason: 'visible');
}
void expectSliverChildConstraints({
required RenderSliverSingleBoxAdapter sliver,
required double maxWidth,
required double maxHeight,
required double minWidth,
required double minHeight,
}) {
expect(sliver.child!.constraints.maxWidth, maxWidth, reason: 'maxWidth');
expect(sliver.child!.constraints.maxHeight, maxHeight, reason: 'maxHeight');
expect(sliver.child!.constraints.minWidth, minWidth, reason: 'minWidth');
expect(sliver.child!.constraints.minHeight, minHeight, reason: 'minHeight');
}
class TestRenderSliverBoxChildManager extends RenderSliverBoxChildManager {
TestRenderSliverBoxChildManager({
required this.children,
});
RenderSliverMultiBoxAdaptor? _renderObject;
List<RenderBox> children;
RenderSliverList createRenderSliverList() {
assert(_renderObject == null);
_renderObject = RenderSliverList(childManager: this);
return _renderObject! as RenderSliverList;
}
RenderSliverFixedExtentList createRenderSliverFixedExtentList() {
assert(_renderObject == null);
_renderObject = RenderSliverFixedExtentList(
childManager: this,
itemExtent: 100.0,
);
return _renderObject! as RenderSliverFixedExtentList;
}
RenderSliverGrid createRenderSliverGrid() {
assert(_renderObject == null);
_renderObject = RenderSliverGrid(
childManager: this,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 4.0,
),
);
return _renderObject! as RenderSliverGrid;
}
int? _currentlyUpdatingChildIndex;
@override
void createChild(int index, { required RenderBox? after }) {
if (index < 0 || index >= children.length) {
return;
}
try {
_currentlyUpdatingChildIndex = index;
_renderObject!.insert(children[index], after: after);
} finally {
_currentlyUpdatingChildIndex = null;
}
}
@override
void removeChild(RenderBox child) {
_renderObject!.remove(child);
}
@override
double estimateMaxScrollOffset(
SliverConstraints constraints, {
int? firstIndex,
int? lastIndex,
double? leadingScrollOffset,
double? trailingScrollOffset,
}) {
assert(lastIndex! >= firstIndex!);
return children.length * (trailingScrollOffset! - leadingScrollOffset!) / (lastIndex! - firstIndex! + 1);
}
@override
int get childCount => children.length;
@override
void didAdoptChild(RenderBox child) {
assert(_currentlyUpdatingChildIndex != null);
final SliverMultiBoxAdaptorParentData childParentData = child.parentData! as SliverMultiBoxAdaptorParentData;
childParentData.index = _currentlyUpdatingChildIndex;
}
@override
void setDidUnderflow(bool value) { }
}
| flutter/packages/flutter/test/rendering/sliver_cache_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/sliver_cache_test.dart",
"repo_id": "flutter",
"token_count": 25072
} | 678 |
// 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 separate from viewport_caching_test.dart because we can't use
// both testWidgets and rendering_tester in the same file - testWidgets will
// initialize a binding, which rendering_tester will attempt to re-initialize
// (or vice versa).
@Tags(<String>['reduced-test-set'])
library;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
class _TestSliverPersistentHeaderDelegate extends SliverPersistentHeaderDelegate {
_TestSliverPersistentHeaderDelegate({
this.key,
required this.minExtent,
required this.maxExtent,
this.vsync = const TestVSync(),
this.showOnScreenConfiguration = const PersistentHeaderShowOnScreenConfiguration(),
});
final Key? key;
@override
final double maxExtent;
@override
final double minExtent;
@override
final TickerProvider? vsync;
@override
final PersistentHeaderShowOnScreenConfiguration showOnScreenConfiguration;
@override
Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) => SizedBox.expand(key: key);
@override
bool shouldRebuild(_TestSliverPersistentHeaderDelegate oldDelegate) => true;
}
void main() {
testWidgets('Scrollable widget scrollDirection update test', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
Widget buildFrame(Axis axis) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 100.0,
width: 100.0,
child: SingleChildScrollView(
controller: controller,
scrollDirection: axis,
child: const SizedBox(
width: 200,
height: 200,
child: SizedBox.shrink(),
),
),
),
),
);
}
await tester.pumpWidget(buildFrame(Axis.vertical));
expect(controller.position.pixels, 0.0);
// Change the SingleChildScrollView.scrollDirection to horizontal.
await tester.pumpWidget(buildFrame(Axis.horizontal));
expect(controller.position.pixels, 0.0);
final TestGesture gesture = await tester.startGesture(const Offset(400.0, 300.0));
// Drag in the vertical direction should not cause scrolling.
await gesture.moveBy(const Offset(0.0, 10.0));
expect(controller.position.pixels, 0.0);
await gesture.moveBy(const Offset(0.0, -10.0));
expect(controller.position.pixels, 0.0);
// Drag in the horizontal direction should cause scrolling.
await gesture.moveBy(const Offset(-10.0, 0.0));
expect(controller.position.pixels, 10.0);
await gesture.moveBy(const Offset(10.0, 0.0));
expect(controller.position.pixels, 0.0);
});
testWidgets('Viewport getOffsetToReveal - down', (WidgetTester tester) async {
final ScrollController controller = ScrollController(initialScrollOffset: 300.0);
addTearDown(controller.dispose);
List<Widget> children;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
width: 300.0,
child: ListView(
controller: controller,
children: children = List<Widget>.generate(20, (int i) {
return SizedBox(
height: 100.0,
width: 300.0,
child: Text('Tile $i'),
);
}),
),
),
),
),
);
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.byWidget(children[5], skipOffstage: false));
RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0);
expect(revealed.offset, 500.0);
expect(revealed.rect, const Rect.fromLTWH(0.0, 0.0, 300.0, 100.0));
revealed = viewport.getOffsetToReveal(target, 1.0);
expect(revealed.offset, 400.0);
expect(revealed.rect, const Rect.fromLTWH(0.0, 100.0, 300.0, 100.0));
revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0));
expect(revealed.offset, 540.0);
expect(revealed.rect, const Rect.fromLTWH(40.0, 0.0, 10.0, 10.0));
revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0));
expect(revealed.offset, 350.0);
expect(revealed.rect, const Rect.fromLTWH(40.0, 190.0, 10.0, 10.0));
});
testWidgets('Viewport getOffsetToReveal - right', (WidgetTester tester) async {
final ScrollController controller = ScrollController(initialScrollOffset: 300.0);
addTearDown(controller.dispose);
List<Widget> children;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 300.0,
width: 200.0,
child: ListView(
scrollDirection: Axis.horizontal,
controller: controller,
children: children = List<Widget>.generate(20, (int i) {
return SizedBox(
height: 300.0,
width: 100.0,
child: Text('Tile $i'),
);
}),
),
),
),
),
);
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.byWidget(children[5], skipOffstage: false));
RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0);
expect(revealed.offset, 500.0);
expect(revealed.rect, const Rect.fromLTWH(0.0, 0.0, 100.0, 300.0));
revealed = viewport.getOffsetToReveal(target, 1.0);
expect(revealed.offset, 400.0);
expect(revealed.rect, const Rect.fromLTWH(100.0, 0.0, 100.0, 300.0));
revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0));
expect(revealed.offset, 540.0);
expect(revealed.rect, const Rect.fromLTWH(0.0, 40.0, 10.0, 10.0));
revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0));
expect(revealed.offset, 350.0);
expect(revealed.rect, const Rect.fromLTWH(190.0, 40.0, 10.0, 10.0));
});
testWidgets('Viewport getOffsetToReveal - up', (WidgetTester tester) async {
final ScrollController controller = ScrollController(initialScrollOffset: 300.0);
addTearDown(controller.dispose);
List<Widget> children;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
width: 300.0,
child: ListView(
controller: controller,
reverse: true,
children: children = List<Widget>.generate(20, (int i) {
return SizedBox(
height: 100.0,
width: 300.0,
child: Text('Tile $i'),
);
}),
),
),
),
),
);
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.byWidget(children[5], skipOffstage: false));
RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0);
expect(revealed.offset, 500.0);
expect(revealed.rect, const Rect.fromLTWH(0.0, 100.0, 300.0, 100.0));
revealed = viewport.getOffsetToReveal(target, 1.0);
expect(revealed.offset, 400.0);
expect(revealed.rect, const Rect.fromLTWH(0.0, 0.0, 300.0, 100.0));
revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0));
expect(revealed.offset, 550.0);
expect(revealed.rect, const Rect.fromLTWH(40.0, 190.0, 10.0, 10.0));
revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0));
expect(revealed.offset, 360.0);
expect(revealed.rect, const Rect.fromLTWH(40.0, 0.0, 10.0, 10.0));
});
testWidgets('Viewport getOffsetToReveal - left', (WidgetTester tester) async {
final ScrollController controller = ScrollController(initialScrollOffset: 300.0);
addTearDown(controller.dispose);
List<Widget> children;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 300.0,
width: 200.0,
child: ListView(
scrollDirection: Axis.horizontal,
reverse: true,
controller: controller,
children: children = List<Widget>.generate(20, (int i) {
return SizedBox(
height: 300.0,
width: 100.0,
child: Text('Tile $i'),
);
}),
),
),
),
),
);
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.byWidget(children[5], skipOffstage: false));
RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0);
expect(revealed.offset, 500.0);
expect(revealed.rect, const Rect.fromLTWH(100.0, 0.0, 100.0, 300.0));
revealed = viewport.getOffsetToReveal(target, 1.0);
expect(revealed.offset, 400.0);
expect(revealed.rect, const Rect.fromLTWH(0.0, 0.0, 100.0, 300.0));
revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0));
expect(revealed.offset, 550.0);
expect(revealed.rect, const Rect.fromLTWH(190.0, 40.0, 10.0, 10.0));
revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0));
expect(revealed.offset, 360.0);
expect(revealed.rect, const Rect.fromLTWH(0.0, 40.0, 10.0, 10.0));
});
testWidgets('Viewport getOffsetToReveal Sliver - down', (WidgetTester tester) async {
final ScrollController controller = ScrollController(initialScrollOffset: 300.0);
addTearDown(controller.dispose);
final List<Widget> children = <Widget>[];
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
width: 300.0,
child: CustomScrollView(
controller: controller,
slivers: List<Widget>.generate(20, (int i) {
final Widget sliver = SliverToBoxAdapter(
child: SizedBox(
height: 100.0,
child: Text('Tile $i'),
),
);
children.add(sliver);
return SliverPadding(
padding: const EdgeInsets.only(top: 22.0, bottom: 23.0),
sliver: sliver,
);
}),
),
),
),
),
);
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.byWidget(children[5], skipOffstage: false));
RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0);
expect(revealed.offset, 5 * (100 + 22 + 23) + 22);
revealed = viewport.getOffsetToReveal(target, 1.0);
expect(revealed.offset, 5 * (100 + 22 + 23) + 22 - 100);
// With rect specified.
revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTRB(1, 2, 3, 4));
expect(revealed.offset, 5 * (100 + 22 + 23) + 22 + 2);
revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTRB(1, 2, 3, 4));
expect(revealed.offset, 5 * (100 + 22 + 23) + 22 - (200 - 4));
});
testWidgets('Viewport getOffsetToReveal Sliver - right', (WidgetTester tester) async {
final ScrollController controller = ScrollController(initialScrollOffset: 300.0);
addTearDown(controller.dispose);
final List<Widget> children = <Widget>[];
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 300.0,
width: 200.0,
child: CustomScrollView(
scrollDirection: Axis.horizontal,
controller: controller,
slivers: List<Widget>.generate(20, (int i) {
final Widget sliver = SliverToBoxAdapter(
child: SizedBox(
width: 100.0,
child: Text('Tile $i'),
),
);
children.add(sliver);
return SliverPadding(
padding: const EdgeInsets.only(left: 22.0, right: 23.0),
sliver: sliver,
);
}),
),
),
),
),
);
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.byWidget(children[5], skipOffstage: false));
RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0);
expect(revealed.offset, 5 * (100 + 22 + 23) + 22);
revealed = viewport.getOffsetToReveal(target, 1.0);
expect(revealed.offset, 5 * (100 + 22 + 23) + 22 - 100);
// With rect specified.
revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTRB(1, 2, 3, 4));
expect(revealed.offset, 5 * (100 + 22 + 23) + 22 + 1);
revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTRB(1, 2, 3, 4));
expect(revealed.offset, 5 * (100 + 22 + 23) + 22 - (200 - 3));
});
testWidgets('Viewport getOffsetToReveal Sliver - up', (WidgetTester tester) async {
final ScrollController controller = ScrollController(initialScrollOffset: 300.0);
addTearDown(controller.dispose);
final List<Widget> children = <Widget>[];
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
width: 300.0,
child: CustomScrollView(
controller: controller,
reverse: true,
slivers: List<Widget>.generate(20, (int i) {
final Widget sliver = SliverToBoxAdapter(
child: SizedBox(
height: 100.0,
child: Text('Tile $i'),
),
);
children.add(sliver);
return SliverPadding(
padding: const EdgeInsets.only(top: 22.0, bottom: 23.0),
sliver: sliver,
);
}),
),
),
),
),
);
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.byWidget(children[5], skipOffstage: false));
RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0);
// Does not include the bottom padding of children[5] thus + 23 instead of + 22.
expect(revealed.offset, 5 * (100 + 22 + 23) + 23);
revealed = viewport.getOffsetToReveal(target, 1.0);
expect(revealed.offset, 5 * (100 + 22 + 23) + 23 - 100);
// With rect specified.
revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTRB(1, 2, 3, 4));
expect(revealed.offset, 5 * (100 + 22 + 23) + 23 + (100 - 4));
revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTRB(1, 2, 3, 4));
expect(revealed.offset, - 200 + 6 * (100 + 22 + 23) - 22 - 2);
});
testWidgets('Viewport getOffsetToReveal Sliver - up - reverse growth', (WidgetTester tester) async {
const Key centerKey = ValueKey<String>('center');
const EdgeInsets padding = EdgeInsets.only(top: 22.0, bottom: 23.0);
const Widget centerSliver = SliverPadding(
key: centerKey,
padding: padding,
sliver: SliverToBoxAdapter(
child: SizedBox(
height: 100.0,
child: Text('Tile center'),
),
),
);
const Widget lowerItem = SizedBox(
height: 100.0,
child: Text('Tile lower'),
);
const Widget lowerSliver = SliverPadding(
padding: padding,
sliver: SliverToBoxAdapter(
child: lowerItem,
),
);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
width: 300.0,
child: CustomScrollView(
center: centerKey,
reverse: true,
slivers: <Widget>[lowerSliver, centerSliver],
),
),
),
),
);
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.byWidget(lowerItem, skipOffstage: false));
RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0);
expect(revealed.offset, - 100 - 22);
revealed = viewport.getOffsetToReveal(target, 1.0);
expect(revealed.offset, - 100 - 22 - 100);
// With rect specified.
revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTRB(1, 2, 3, 4));
expect(revealed.offset, - 22 - 4);
revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTRB(1, 2, 3, 4));
expect(revealed.offset, -200 - 22 - 2);
});
testWidgets('Viewport getOffsetToReveal Sliver - left - reverse growth', (WidgetTester tester) async {
const Key centerKey = ValueKey<String>('center');
const EdgeInsets padding = EdgeInsets.only(left: 22.0, right: 23.0);
const Widget centerSliver = SliverPadding(
key: centerKey,
padding: padding,
sliver: SliverToBoxAdapter(
child: SizedBox(
width: 100.0,
child: Text('Tile center'),
),
),
);
const Widget lowerItem = SizedBox(
width: 100.0,
child: Text('Tile lower'),
);
const Widget lowerSliver = SliverPadding(
padding: padding,
sliver: SliverToBoxAdapter(
child: lowerItem,
),
);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
width: 300.0,
child: CustomScrollView(
scrollDirection: Axis.horizontal,
center: centerKey,
reverse: true,
slivers: <Widget>[lowerSliver, centerSliver],
),
),
),
),
);
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.byWidget(lowerItem, skipOffstage: false));
RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0);
expect(revealed.offset, -100 - 22);
revealed = viewport.getOffsetToReveal(target, 1.0);
expect(revealed.offset, - 100 - 22 - 200);
// With rect specified.
revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTRB(1, 2, 3, 4));
expect(revealed.offset, - 22 - 3);
revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTRB(1, 2, 3, 4));
expect(revealed.offset, - 300 - 22 - 1);
});
testWidgets('Viewport getOffsetToReveal Sliver - left', (WidgetTester tester) async {
final ScrollController controller = ScrollController(initialScrollOffset: 300.0);
addTearDown(controller.dispose);
final List<Widget> children = <Widget>[];
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 300.0,
width: 200.0,
child: CustomScrollView(
scrollDirection: Axis.horizontal,
reverse: true,
controller: controller,
slivers: List<Widget>.generate(20, (int i) {
final Widget sliver = SliverToBoxAdapter(
child: SizedBox(
width: 100.0,
child: Text('Tile $i'),
),
);
children.add(sliver);
return SliverPadding(
padding: const EdgeInsets.only(left: 22.0, right: 23.0),
sliver: sliver,
);
}),
),
),
),
),
);
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.byWidget(children[5], skipOffstage: false));
RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0);
expect(revealed.offset, 5 * (100 + 22 + 23) + 23);
revealed = viewport.getOffsetToReveal(target, 1.0);
expect(revealed.offset, 5 * (100 + 22 + 23) + 23 - 100);
// With rect specified.
revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTRB(1, 2, 3, 4));
expect(revealed.offset, 6 * (100 + 22 + 23) - 22 - 3);
revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTRB(1, 2, 3, 4));
expect(revealed.offset, -200 + 6 * (100 + 22 + 23) - 22 - 1);
});
testWidgets('Nested Viewports showOnScreen', (WidgetTester tester) async {
final List<ScrollController> controllersX = List<ScrollController>.generate(10, (int i) => ScrollController(initialScrollOffset: 400.0));
final ScrollController controllerY = ScrollController(initialScrollOffset: 400.0);
addTearDown((){
controllerY.dispose();
for (final ScrollController controller in controllersX) {
controller.dispose();
}
});
final List<List<Widget>> children = List<List<Widget>>.generate(10, (int y) {
return List<Widget>.generate(10, (int x) {
return SizedBox(
height: 100.0,
width: 100.0,
child: Text('$x,$y'),
);
});
});
/// Builds a grid:
///
/// <- x ->
/// 0 1 2 3 4 5 6 7 8 9
/// 0 c c c c c c c c c c
/// 1 c c c c c c c c c c
/// 2 c c c c c c c c c c
/// 3 c c c c c c c c c c y
/// 4 c c c c v v c c c c
/// 5 c c c c v v c c c c
/// 6 c c c c c c c c c c
/// 7 c c c c c c c c c c
/// 8 c c c c c c c c c c
/// 9 c c c c c c c c c c
///
/// Each c is a 100x100 container, v are containers visible in initial
/// viewport.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
width: 200.0,
child: ListView(
controller: controllerY,
children: List<Widget>.generate(10, (int y) {
return SizedBox(
height: 100.0,
child: ListView(
scrollDirection: Axis.horizontal,
controller: controllersX[y],
children: children[y],
),
);
}),
),
),
),
),
);
// Already in viewport
tester.renderObject(find.byWidget(children[4][4], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(controllersX[4].offset, 400.0);
expect(controllerY.offset, 400.0);
controllersX[4].jumpTo(400.0);
controllerY.jumpTo(400.0);
await tester.pumpAndSettle();
// Above viewport
tester.renderObject(find.byWidget(children[3][4], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(controllersX[3].offset, 400.0);
expect(controllerY.offset, 300.0);
controllersX[3].jumpTo(400.0);
controllerY.jumpTo(400.0);
await tester.pumpAndSettle();
// Below viewport
tester.renderObject(find.byWidget(children[6][4], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(controllersX[6].offset, 400.0);
expect(controllerY.offset, 500.0);
controllersX[6].jumpTo(400.0);
controllerY.jumpTo(400.0);
await tester.pumpAndSettle();
// Left of viewport
tester.renderObject(find.byWidget(children[4][3], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(controllersX[4].offset, 300.0);
expect(controllerY.offset, 400.0);
controllersX[4].jumpTo(400.0);
controllerY.jumpTo(400.0);
await tester.pumpAndSettle();
// Right of viewport
tester.renderObject(find.byWidget(children[4][6], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(controllersX[4].offset, 500.0);
expect(controllerY.offset, 400.0);
controllersX[4].jumpTo(400.0);
controllerY.jumpTo(400.0);
await tester.pumpAndSettle();
// Above and left of viewport
tester.renderObject(find.byWidget(children[3][3], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(controllersX[3].offset, 300.0);
expect(controllerY.offset, 300.0);
controllersX[3].jumpTo(400.0);
controllerY.jumpTo(400.0);
await tester.pumpAndSettle();
// Below and left of viewport
tester.renderObject(find.byWidget(children[6][3], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(controllersX[6].offset, 300.0);
expect(controllerY.offset, 500.0);
controllersX[6].jumpTo(400.0);
controllerY.jumpTo(400.0);
await tester.pumpAndSettle();
// Above and right of viewport
tester.renderObject(find.byWidget(children[3][6], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(controllersX[3].offset, 500.0);
expect(controllerY.offset, 300.0);
controllersX[3].jumpTo(400.0);
controllerY.jumpTo(400.0);
await tester.pumpAndSettle();
// Below and right of viewport
tester.renderObject(find.byWidget(children[6][6], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(controllersX[6].offset, 500.0);
expect(controllerY.offset, 500.0);
controllersX[6].jumpTo(400.0);
controllerY.jumpTo(400.0);
await tester.pumpAndSettle();
// Below and right of viewport with animations
tester.renderObject(find.byWidget(children[6][6], skipOffstage: false)).showOnScreen(duration: const Duration(seconds: 2));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(tester.hasRunningAnimations, isTrue);
expect(controllersX[6].offset, greaterThan(400.0));
expect(controllersX[6].offset, lessThan(500.0));
expect(controllerY.offset, greaterThan(400.0));
expect(controllerY.offset, lessThan(500.0));
await tester.pumpAndSettle();
expect(controllersX[6].offset, 500.0);
expect(controllerY.offset, 500.0);
});
group('Nested viewports (same orientation) showOnScreen', () {
final List<Widget> children = List<Widget>.generate(10, (int i) {
return SizedBox(
height: 100.0,
width: 300.0,
child: Text('$i'),
);
});
Future<void> buildNestedScroller({ required WidgetTester tester, required ScrollController inner, required ScrollController outer }) {
return tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
width: 300.0,
child: ListView(
controller: outer,
children: <Widget>[
const SizedBox(
height: 200.0,
),
SizedBox(
height: 200.0,
width: 300.0,
child: ListView(
controller: inner,
children: children,
),
),
const SizedBox(
height: 200.0,
),
],
),
),
),
),
);
}
testWidgets('Reverse List showOnScreen', (WidgetTester tester) async {
addTearDown(tester.view.reset);
const double screenHeight = 400.0;
const double screenWidth = 400.0;
const double itemHeight = screenHeight / 10.0;
const ValueKey<String> centerKey = ValueKey<String>('center');
tester.view.devicePixelRatio = 1.0;
tester.view.physicalSize = const Size(screenWidth, screenHeight);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
center: centerKey,
reverse: true,
slivers: <Widget>[
SliverList(
delegate: SliverChildListDelegate(
List<Widget>.generate(
10,
(int index) => SizedBox(
height: itemHeight,
child: Text('Item ${-index - 1}'),
),
),
),
),
SliverList(
key: centerKey,
delegate: SliverChildListDelegate(
List<Widget>.generate(
1,
(int index) => const SizedBox(
height: itemHeight,
child: Text('Item 0'),
),
),
),
),
SliverList(
delegate: SliverChildListDelegate(
List<Widget>.generate(
10,
(int index) => SizedBox(
height: itemHeight,
child: Text('Item ${index + 1}'),
),
),
),
),
],
),
),
);
expect(find.text('Item -1'), findsNothing);
final RenderBox itemNeg1 =
tester.renderObject(find.text('Item -1', skipOffstage: false));
itemNeg1.showOnScreen(duration: const Duration(seconds: 1));
await tester.pumpAndSettle();
expect(find.text('Item -1'), findsOneWidget);
});
testWidgets('in view in inner, but not in outer', (WidgetTester tester) async {
final ScrollController inner = ScrollController();
final ScrollController outer = ScrollController();
addTearDown(inner.dispose);
addTearDown(outer.dispose);
await buildNestedScroller(
tester: tester,
inner: inner,
outer: outer,
);
expect(outer.offset, 0.0);
expect(inner.offset, 0.0);
tester.renderObject(find.byWidget(children[0], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(inner.offset, 0.0);
expect(outer.offset, 100.0);
});
testWidgets('not in view of neither inner nor outer', (WidgetTester tester) async {
final ScrollController inner = ScrollController();
final ScrollController outer = ScrollController();
addTearDown(inner.dispose);
addTearDown(outer.dispose);
await buildNestedScroller(
tester: tester,
inner: inner,
outer: outer,
);
expect(outer.offset, 0.0);
expect(inner.offset, 0.0);
tester.renderObject(find.byWidget(children[4], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(inner.offset, 300.0);
expect(outer.offset, 200.0);
});
testWidgets('in view in inner and outer', (WidgetTester tester) async {
final ScrollController inner = ScrollController(initialScrollOffset: 200.0);
final ScrollController outer = ScrollController(initialScrollOffset: 200.0);
addTearDown(inner.dispose);
addTearDown(outer.dispose);
await buildNestedScroller(
tester: tester,
inner: inner,
outer: outer,
);
expect(outer.offset, 200.0);
expect(inner.offset, 200.0);
tester.renderObject(find.byWidget(children[2])).showOnScreen();
await tester.pumpAndSettle();
expect(outer.offset, 200.0);
expect(inner.offset, 200.0);
});
testWidgets('inner shown in outer, but item not visible', (WidgetTester tester) async {
final ScrollController inner = ScrollController(initialScrollOffset: 200.0);
final ScrollController outer = ScrollController(initialScrollOffset: 200.0);
addTearDown(inner.dispose);
addTearDown(outer.dispose);
await buildNestedScroller(
tester: tester,
inner: inner,
outer: outer,
);
expect(outer.offset, 200.0);
expect(inner.offset, 200.0);
tester.renderObject(find.byWidget(children[5], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(outer.offset, 200.0);
expect(inner.offset, 400.0);
});
testWidgets('inner half shown in outer, item only visible in inner', (WidgetTester tester) async {
final ScrollController inner = ScrollController();
final ScrollController outer = ScrollController(initialScrollOffset: 100.0);
addTearDown(inner.dispose);
addTearDown(outer.dispose);
await buildNestedScroller(
tester: tester,
inner: inner,
outer: outer,
);
expect(outer.offset, 100.0);
expect(inner.offset, 0.0);
tester.renderObject(find.byWidget(children[1])).showOnScreen();
await tester.pumpAndSettle();
expect(outer.offset, 200.0);
expect(inner.offset, 0.0);
});
});
testWidgets('Nested Viewports showOnScreen with allowImplicitScrolling=false for inner viewport', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/20893.
List<Widget> slivers;
final ScrollController controllerX = ScrollController();
final ScrollController controllerY = ScrollController();
addTearDown(controllerX.dispose);
addTearDown(controllerY.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
width: 200.0,
child: ListView(
controller: controllerY,
children: <Widget>[
const SizedBox(
height: 150.0,
),
SizedBox(
height: 100.0,
child: ListView(
physics: const PageScrollPhysics(), // Turns off `allowImplicitScrolling`
scrollDirection: Axis.horizontal,
controller: controllerX,
children: slivers = <Widget>[
Container(
width: 150.0,
),
Container(
width: 150.0,
),
],
),
),
const SizedBox(
height: 150.0,
),
],
),
),
),
),
);
tester.renderObject(find.byWidget(slivers[1])).showOnScreen();
await tester.pumpAndSettle();
expect(controllerX.offset, 0.0);
expect(controllerY.offset, 50.0);
});
testWidgets('Nested Viewports showOnScreen on Sliver with allowImplicitScrolling=false for inner viewport', (WidgetTester tester) async {
Widget sliver;
final ScrollController controllerX = ScrollController();
final ScrollController controllerY = ScrollController();
addTearDown(controllerX.dispose);
addTearDown(controllerY.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
width: 200.0,
child: ListView(
controller: controllerY,
children: <Widget>[
const SizedBox(
height: 150.0,
),
SizedBox(
height: 100.0,
child: CustomScrollView(
physics: const PageScrollPhysics(), // Turns off `allowImplicitScrolling`
scrollDirection: Axis.horizontal,
controller: controllerX,
slivers: <Widget>[
SliverPadding(
padding: const EdgeInsets.all(25.0),
sliver: SliverToBoxAdapter(
child: Container(
width: 100.0,
),
),
),
SliverPadding(
padding: const EdgeInsets.all(25.0),
sliver: sliver = SliverToBoxAdapter(
child: Container(
width: 100.0,
),
),
),
],
),
),
const SizedBox(
height: 150.0,
),
],
),
),
),
),
);
tester.renderObject(find.byWidget(sliver)).showOnScreen();
await tester.pumpAndSettle();
expect(controllerX.offset, 0.0);
expect(controllerY.offset, 25.0);
});
testWidgets('Viewport showOnScreen with objects larger than viewport', (WidgetTester tester) async {
List<Widget> children;
final ScrollController controller = ScrollController(initialScrollOffset: 300.0);
addTearDown(controller.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
child: ListView(
controller: controller,
children: children = List<Widget>.generate(20, (int i) {
return SizedBox(
height: 300.0,
child: Text('Tile $i'),
);
}),
),
),
),
),
);
expect(controller.offset, 300.0);
// Already aligned with leading edge, nothing happens.
tester.renderObject(find.byWidget(children[1], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(controller.offset, 300.0);
// Above leading edge aligns trailing edges
tester.renderObject(find.byWidget(children[0], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(controller.offset, 100.0);
// Below trailing edge aligns leading edges
tester.renderObject(find.byWidget(children[1], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(controller.offset, 300.0);
controller.jumpTo(250.0);
await tester.pumpAndSettle();
expect(controller.offset, 250.0);
// Partly visible across leading edge aligns trailing edges
tester.renderObject(find.byWidget(children[0], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(controller.offset, 100.0);
controller.jumpTo(150.0);
await tester.pumpAndSettle();
expect(controller.offset, 150.0);
// Partly visible across trailing edge aligns leading edges
tester.renderObject(find.byWidget(children[1], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(controller.offset, 300.0);
});
testWidgets(
'Viewport showOnScreen should not scroll if the rect is already visible, even if it does not scroll linearly',
(WidgetTester tester) async {
List<Widget> children;
final ScrollController controller = ScrollController(initialScrollOffset: 300.0);
addTearDown(controller.dispose);
const Key headerKey = Key('header');
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 600.0,
child: CustomScrollView(
controller: controller,
slivers: children = List<Widget>.generate(20, (int i) {
return i == 10
? SliverPersistentHeader(
pinned: true,
delegate: _TestSliverPersistentHeaderDelegate(
minExtent: 100,
maxExtent: 300,
key: headerKey,
),
)
: SliverToBoxAdapter(
child: SizedBox(
height: 300.0,
child: Text('Tile $i'),
),
);
}),
),
),
),
),
);
controller.jumpTo(300.0 * 15);
await tester.pumpAndSettle();
final Finder pinnedHeaderContent = find.descendant(
of: find.byWidget(children[10]),
matching: find.byKey(headerKey),
);
// The persistent header is pinned to the leading edge thus still visible,
// the viewport should not scroll.
tester.renderObject(pinnedHeaderContent).showOnScreen();
await tester.pumpAndSettle();
expect(controller.offset, 300.0 * 15);
// The 11th child will be partially obstructed by the persistent header,
// the viewport should scroll to reveal it.
controller.jumpTo(
11 * 300.0 // Preceding headers
+ 200.0 // Shrinks the pinned header to minExtent
+ 100.0, // Obstructs the leading 100 pixels of the 11th header
);
await tester.pumpAndSettle();
tester.renderObject(find.byWidget(children[11], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(controller.offset, lessThan(11 * 300.0 + 200.0 + 100.0));
},
);
void testFloatingHeaderShowOnScreen({ bool animated = true, Axis axis = Axis.vertical }) {
final TickerProvider? vsync = animated ? const TestVSync() : null;
const Key headerKey = Key('header');
late List<Widget> children;
final ScrollController controller = ScrollController(initialScrollOffset: 300.0);
Widget buildList({ required SliverPersistentHeader floatingHeader, bool reversed = false }) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 400.0,
width: 400.0,
child: CustomScrollView(
scrollDirection: axis,
center: reversed ? const Key('19') : null,
controller: controller,
slivers: children = List<Widget>.generate(20, (int i) {
return i == 10
? floatingHeader
: SliverToBoxAdapter(
key: (i == 19) ? const Key('19') : null,
child: SizedBox(
height: 300.0,
width: 300,
child: Text('Tile $i'),
),
);
}),
),
),
),
);
}
double mainAxisExtent(WidgetTester tester, Finder finder) {
final RenderObject renderObject = tester.renderObject(finder);
if (renderObject is RenderSliver) {
return renderObject.geometry!.paintExtent;
}
final RenderBox renderBox = renderObject as RenderBox;
return switch (axis) {
Axis.horizontal => renderBox.size.width,
Axis.vertical => renderBox.size.height,
};
}
group('animated: $animated, scrollDirection: $axis', () {
testWidgets(
'RenderViewportBase.showOnScreen',
(WidgetTester tester) async {
await tester.pumpWidget(
buildList(
floatingHeader: SliverPersistentHeader(
pinned: true,
floating: true,
delegate: _TestSliverPersistentHeaderDelegate(minExtent: 100, maxExtent: 300, key: headerKey, vsync: vsync),
),
),
);
final Finder pinnedHeaderContent = find.byKey(headerKey, skipOffstage: false);
controller.jumpTo(300.0 * 15);
await tester.pumpAndSettle();
expect(mainAxisExtent(tester, pinnedHeaderContent), lessThan(300));
// The persistent header is pinned to the leading edge thus still visible,
// the viewport should not scroll.
tester.renderObject(pinnedHeaderContent).showOnScreen(
descendant: tester.renderObject(pinnedHeaderContent),
rect: Offset.zero & const Size(300, 300),
);
await tester.pumpAndSettle();
// The header expands but doesn't move.
expect(controller.offset, 300.0 * 15);
expect(mainAxisExtent(tester, pinnedHeaderContent), 300);
// The rect specifies that the persistent header needs to be 1 pixel away
// from the leading edge of the viewport. Ignore the 1 pixel, the viewport
// should not scroll.
//
// See: https://github.com/flutter/flutter/issues/25507.
tester.renderObject(pinnedHeaderContent).showOnScreen(
descendant: tester.renderObject(pinnedHeaderContent),
rect: const Offset(-1, -1) & const Size(300, 300),
);
await tester.pumpAndSettle();
expect(controller.offset, 300.0 * 15);
expect(mainAxisExtent(tester, pinnedHeaderContent), 300);
},
);
testWidgets('RenderViewportBase.showOnScreen twice almost instantly', (WidgetTester tester) async{
// Regression test for https://github.com/flutter/flutter/issues/137901
await tester.pumpWidget(
buildList(
floatingHeader: SliverPersistentHeader(
pinned: true,
floating: true,
delegate: _TestSliverPersistentHeaderDelegate(minExtent: 100, maxExtent: 300, key: headerKey, vsync: vsync),
),
),
);
final Finder pinnedHeaderContent = find.byKey(headerKey, skipOffstage: false);
controller.jumpTo(300.0 * 15);
await tester.pumpAndSettle();
expect(mainAxisExtent(tester, pinnedHeaderContent), lessThan(300));
tester.renderObject(pinnedHeaderContent).showOnScreen(
descendant: tester.renderObject(pinnedHeaderContent),
// Adding different rect to check if the second showOnScreen call
// leads to a different result.
// When the animation has forward status and the second showOnScreen
// is called, the new animation won't start.
rect: Offset.zero & const Size(150, 150),
duration: const Duration(seconds: 3),
);
await tester.pump(const Duration(seconds: 1));
tester.renderObject(pinnedHeaderContent).showOnScreen(
descendant: tester.renderObject(pinnedHeaderContent),
rect: Offset.zero & const Size(300, 300),
);
await tester.pumpAndSettle();
expect(controller.offset, 300.0 * 15);
expect(mainAxisExtent(tester, pinnedHeaderContent), 150);
});
testWidgets(
'RenderViewportBase.showOnScreen but no child',
(WidgetTester tester) async {
await tester.pumpWidget(
buildList(
floatingHeader: SliverPersistentHeader(
key: headerKey,
pinned: true,
floating: true,
delegate: _TestSliverPersistentHeaderDelegate(minExtent: 100, maxExtent: 300, vsync: vsync),
),
),
);
final Finder pinnedHeaderContent = find.byKey(headerKey, skipOffstage: false);
controller.jumpTo(300.0 * 15);
await tester.pumpAndSettle();
expect(mainAxisExtent(tester, pinnedHeaderContent), lessThan(300));
// The persistent header is pinned to the leading edge thus still visible,
// the viewport should not scroll.
tester.renderObject(pinnedHeaderContent).showOnScreen(
rect: Offset.zero & const Size(300, 300),
);
await tester.pumpAndSettle();
// The header expands but doesn't move.
expect(controller.offset, 300.0 * 15);
expect(mainAxisExtent(tester, pinnedHeaderContent), 300);
// The rect specifies that the persistent header needs to be 1 pixel away
// from the leading edge of the viewport. Ignore the 1 pixel, the viewport
// should not scroll.
//
// See: https://github.com/flutter/flutter/issues/25507.
tester.renderObject(pinnedHeaderContent).showOnScreen(
rect: const Offset(-1, -1) & const Size(300, 300),
);
await tester.pumpAndSettle();
expect(controller.offset, 300.0 * 15);
expect(mainAxisExtent(tester, pinnedHeaderContent), 300);
},
);
testWidgets(
'RenderViewportBase.showOnScreen with maxShowOnScreenExtent ',
(WidgetTester tester) async {
await tester.pumpWidget(
buildList(
floatingHeader: SliverPersistentHeader(
pinned: true,
floating: true,
delegate: _TestSliverPersistentHeaderDelegate(
minExtent: 100,
maxExtent: 300,
key: headerKey,
vsync: vsync,
showOnScreenConfiguration: const PersistentHeaderShowOnScreenConfiguration(maxShowOnScreenExtent: 200),
),
),
),
);
final Finder pinnedHeaderContent = find.byKey(headerKey, skipOffstage: false);
controller.jumpTo(300.0 * 15);
await tester.pumpAndSettle();
// childExtent was initially 100.
expect(mainAxisExtent(tester, pinnedHeaderContent), 100);
tester.renderObject(pinnedHeaderContent).showOnScreen(
descendant: tester.renderObject(pinnedHeaderContent),
rect: Offset.zero & const Size(300, 300),
);
await tester.pumpAndSettle();
// The header doesn't move. It would have expanded to 300 but
// maxShowOnScreenExtent is 200, preventing it from doing so.
expect(controller.offset, 300.0 * 15);
expect(mainAxisExtent(tester, pinnedHeaderContent), 200);
// ignoreLeading still works.
tester.renderObject(pinnedHeaderContent).showOnScreen(
descendant: tester.renderObject(pinnedHeaderContent),
rect: const Offset(-1, -1) & const Size(300, 300),
);
await tester.pumpAndSettle();
expect(controller.offset, 300.0 * 15);
expect(mainAxisExtent(tester, pinnedHeaderContent), 200);
// Move the viewport so that its childExtent reaches 250.
controller.jumpTo(300.0 * 10 + 50.0);
await tester.pumpAndSettle();
expect(mainAxisExtent(tester, pinnedHeaderContent), 250);
// Doesn't move, doesn't expand or shrink, leading still ignored.
tester.renderObject(pinnedHeaderContent).showOnScreen(
descendant: tester.renderObject(pinnedHeaderContent),
rect: const Offset(-1, -1) & const Size(300, 300),
);
await tester.pumpAndSettle();
expect(controller.offset, 300.0 * 10 + 50.0);
expect(mainAxisExtent(tester, pinnedHeaderContent), 250);
},
);
testWidgets(
'RenderViewportBase.showOnScreen with minShowOnScreenExtent ',
(WidgetTester tester) async {
await tester.pumpWidget(
buildList(
floatingHeader: SliverPersistentHeader(
pinned: true,
floating: true,
delegate: _TestSliverPersistentHeaderDelegate(
minExtent: 100,
maxExtent: 300,
key: headerKey,
vsync: vsync,
showOnScreenConfiguration: const PersistentHeaderShowOnScreenConfiguration(minShowOnScreenExtent: 200),
),
),
),
);
final Finder pinnedHeaderContent = find.byKey(headerKey, skipOffstage: false);
controller.jumpTo(300.0 * 15);
await tester.pumpAndSettle();
// childExtent was initially 100.
expect(mainAxisExtent(tester, pinnedHeaderContent), 100);
tester.renderObject(pinnedHeaderContent).showOnScreen(
descendant: tester.renderObject(pinnedHeaderContent),
rect: Offset.zero & const Size(110, 110),
);
await tester.pumpAndSettle();
// The header doesn't move. It would have expanded to 110 but
// minShowOnScreenExtent is 200, preventing it from doing so.
expect(controller.offset, 300.0 * 15);
expect(mainAxisExtent(tester, pinnedHeaderContent), 200);
// ignoreLeading still works.
tester.renderObject(pinnedHeaderContent).showOnScreen(
descendant: tester.renderObject(pinnedHeaderContent),
rect: const Offset(-1, -1) & const Size(110, 110),
);
await tester.pumpAndSettle();
expect(controller.offset, 300.0 * 15);
expect(mainAxisExtent(tester, pinnedHeaderContent), 200);
// Move the viewport so that its childExtent reaches 250.
controller.jumpTo(300.0 * 10 + 50.0);
await tester.pumpAndSettle();
expect(mainAxisExtent(tester, pinnedHeaderContent), 250);
// Doesn't move, doesn't expand or shrink, leading still ignored.
tester.renderObject(pinnedHeaderContent).showOnScreen(
descendant: tester.renderObject(pinnedHeaderContent),
rect: const Offset(-1, -1) & const Size(110, 110),
);
await tester.pumpAndSettle();
expect(controller.offset, 300.0 * 10 + 50.0);
expect(mainAxisExtent(tester, pinnedHeaderContent), 250);
},
);
testWidgets(
'RenderViewportBase.showOnScreen should not scroll if the rect is already visible, '
'even if it does not scroll linearly (reversed order version)',
(WidgetTester tester) async {
await tester.pumpWidget(
buildList(
floatingHeader: SliverPersistentHeader(
pinned: true,
floating: true,
delegate: _TestSliverPersistentHeaderDelegate(minExtent: 100, maxExtent: 300, key: headerKey, vsync: vsync),
),
reversed: true,
),
);
controller.jumpTo(-300.0 * 15);
await tester.pumpAndSettle();
final Finder pinnedHeaderContent = find.byKey(headerKey, skipOffstage: false);
// The persistent header is pinned to the leading edge thus still visible,
// the viewport should not scroll.
tester.renderObject(pinnedHeaderContent).showOnScreen();
await tester.pumpAndSettle();
expect(controller.offset, -300.0 * 15);
// children[9] will be partially obstructed by the persistent header,
// the viewport should scroll to reveal it.
controller.jumpTo(
- 8 * 300.0 // Preceding headers 11 - 18, children[11]'s top edge is aligned to the leading edge.
- 400.0 // Viewport height. children[10] (the pinned header) becomes pinned at the bottom of the screen.
- 200.0 // Shrinks the pinned header to minExtent (100).
- 100.0, // Obstructs the leading 100 pixels of the 11th header
);
await tester.pumpAndSettle();
tester.renderObject(find.byWidget(children[9], skipOffstage: false)).showOnScreen();
await tester.pumpAndSettle();
expect(controller.offset, -8 * 300.0 - 400.0 - 200.0);
},
);
});
}
group('Floating header showOnScreen', () {
testFloatingHeaderShowOnScreen();
testFloatingHeaderShowOnScreen(axis: Axis.horizontal);
});
group('RenderViewport getOffsetToReveal renderBox to sliver coordinates conversion', () {
const EdgeInsets padding = EdgeInsets.fromLTRB(22, 22, 34, 34);
const Key centerKey = Key('5');
Widget buildList({ required Axis axis, bool reverse = false, bool reverseGrowth = false }) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 400.0,
width: 400.0,
child: CustomScrollView(
scrollDirection: axis,
reverse: reverse,
center: reverseGrowth ? centerKey : null,
slivers: List<Widget>.generate(6, (int i) {
return SliverPadding(
key: i == 5 ? centerKey : null,
padding: padding,
sliver: SliverToBoxAdapter(
child: Container(
padding: padding,
height: 300.0,
width: 300.0,
child: Text('Tile $i'),
),
),
);
}),
),
),
),
);
}
testWidgets('up, forward growth', (WidgetTester tester) async {
await tester.pumpWidget(buildList(axis: Axis.vertical, reverse: true));
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.text('Tile 5', skipOffstage: false));
final double revealOffset = viewport.getOffsetToReveal(target, 0.0).offset;
expect(revealOffset, (300.0 + padding.horizontal) * 5 + 34.0 * 2);
});
testWidgets('up, reverse growth', (WidgetTester tester) async {
await tester.pumpWidget(buildList(axis: Axis.vertical, reverse: true, reverseGrowth: true));
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.text('Tile 0', skipOffstage: false));
final double revealOffset = viewport.getOffsetToReveal(target, 0.0).offset;
expect(revealOffset, -(300.0 + padding.horizontal) * 5 + 34.0 * 2);
});
testWidgets('right, forward growth', (WidgetTester tester) async {
await tester.pumpWidget(buildList(axis: Axis.horizontal));
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.text('Tile 5', skipOffstage: false));
final double revealOffset = viewport.getOffsetToReveal(target, 0.0).offset;
expect(revealOffset, (300.0 + padding.horizontal) * 5 + 22.0 * 2);
});
testWidgets('right, reverse growth', (WidgetTester tester) async {
await tester.pumpWidget(buildList(axis: Axis.horizontal, reverseGrowth: true));
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.text('Tile 0', skipOffstage: false));
final double revealOffset = viewport.getOffsetToReveal(target, 0.0).offset;
expect(revealOffset, -(300.0 + padding.horizontal) * 5 + 22.0 * 2);
});
testWidgets('down, forward growth', (WidgetTester tester) async {
await tester.pumpWidget(buildList(axis: Axis.vertical));
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.text('Tile 5', skipOffstage: false));
final double revealOffset = viewport.getOffsetToReveal(target, 0.0).offset;
expect(revealOffset, (300.0 + padding.horizontal) * 5 + 22.0 * 2);
});
testWidgets('down, reverse growth', (WidgetTester tester) async {
await tester.pumpWidget(buildList(axis: Axis.vertical, reverseGrowth: true));
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.text('Tile 0', skipOffstage: false));
final double revealOffset = viewport.getOffsetToReveal(target, 0.0).offset;
expect(revealOffset, -(300.0 + padding.horizontal) * 5 + 22.0 * 2);
});
testWidgets('left, forward growth', (WidgetTester tester) async {
await tester.pumpWidget(buildList(axis: Axis.horizontal, reverse: true));
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.text('Tile 5', skipOffstage: false));
final double revealOffset = viewport.getOffsetToReveal(target, 0.0).offset;
expect(revealOffset, (300.0 + padding.horizontal) * 5 + 34.0 * 2);
});
testWidgets('left, reverse growth', (WidgetTester tester) async {
await tester.pumpWidget(buildList(axis: Axis.horizontal, reverse: true, reverseGrowth: true));
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.text('Tile 0', skipOffstage: false));
final double revealOffset = viewport.getOffsetToReveal(target, 0.0).offset;
expect(revealOffset, -(300.0 + padding.horizontal) * 5 + 34.0 * 2);
});
testWidgets('will not assert on mismatched axis', (WidgetTester tester) async {
await tester.pumpWidget(buildList(axis: Axis.vertical, reverse: true, reverseGrowth: true));
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.text('Tile 0', skipOffstage: false));
viewport.getOffsetToReveal(target, 0.0, axis: Axis.horizontal);
});
});
testWidgets('RenderViewportBase.showOnScreen reports the correct targetRect', (WidgetTester tester) async {
final ScrollController innerController = ScrollController();
final ScrollController outerController = ScrollController();
addTearDown(innerController.dispose);
addTearDown(outerController.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 300.0,
child: CustomScrollView(
cacheExtent: 0,
controller: outerController,
slivers: <Widget>[
SliverToBoxAdapter(
child: SizedBox(
height: 300,
child: CustomScrollView(
controller: innerController,
slivers: List<Widget>.generate(5, (int i) {
return SliverToBoxAdapter(
child: SizedBox(
height: 300.0,
child: Text('Tile $i'),
),
);
}),
),
),
),
const SliverToBoxAdapter(
child: SizedBox(
height: 300.0,
child: Text('hidden'),
),
),
],
),
),
),
),
);
tester.renderObject(find.widgetWithText(SizedBox, 'Tile 1', skipOffstage: false).first).showOnScreen();
await tester.pumpAndSettle();
// The inner viewport scrolls to reveal the 2nd tile.
expect(innerController.offset, 300.0);
expect(outerController.offset, 0);
});
group('unbounded constraints control test', () {
Widget buildNestedWidget([Axis a1 = Axis.vertical, Axis a2 = Axis.horizontal]) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: ListView(
scrollDirection: a1,
children: List<Widget>.generate(10, (int y) {
return ListView(
scrollDirection: a2,
);
}),
),
),
);
}
Future<void> expectFlutterError({
required Widget widget,
required WidgetTester tester,
required String message,
}) async {
final List<FlutterErrorDetails> errors = <FlutterErrorDetails>[];
final FlutterExceptionHandler? oldHandler = FlutterError.onError;
FlutterError.onError = (FlutterErrorDetails error) => errors.add(error);
try {
await tester.pumpWidget(widget);
} finally {
FlutterError.onError = oldHandler;
}
expect(errors, isNotEmpty);
expect(errors.first.exception, isFlutterError);
expect((errors.first.exception as FlutterError).toStringDeep(), message);
}
testWidgets('Horizontal viewport was given unbounded height', (WidgetTester tester) async {
await expectFlutterError(
widget: buildNestedWidget(),
tester: tester,
message:
'FlutterError\n'
' Horizontal viewport was given unbounded height.\n'
' Viewports expand in the cross axis to fill their container and\n'
' constrain their children to match their extent in the cross axis.\n'
' In this case, a horizontal viewport was given an unlimited amount\n'
' of vertical space in which to expand.\n',
);
});
testWidgets('Horizontal viewport was given unbounded width', (WidgetTester tester) async {
await expectFlutterError(
widget: buildNestedWidget(Axis.horizontal),
tester: tester,
message:
'FlutterError\n'
' Horizontal viewport was given unbounded width.\n'
' Viewports expand in the scrolling direction to fill their\n'
' container. In this case, a horizontal viewport was given an\n'
' unlimited amount of horizontal space in which to expand. This\n'
' situation typically happens when a scrollable widget is nested\n'
' inside another scrollable widget.\n'
' If this widget is always nested in a scrollable widget there is\n'
' no need to use a viewport because there will always be enough\n'
' horizontal space for the children. In this case, consider using a\n'
' Row or Wrap instead. Otherwise, consider using a CustomScrollView\n'
' to concatenate arbitrary slivers into a single scrollable.\n',
);
});
testWidgets('Vertical viewport was given unbounded width', (WidgetTester tester) async {
await expectFlutterError(
widget: buildNestedWidget(Axis.horizontal, Axis.vertical),
tester: tester,
message:
'FlutterError\n'
' Vertical viewport was given unbounded width.\n'
' Viewports expand in the cross axis to fill their container and\n'
' constrain their children to match their extent in the cross axis.\n'
' In this case, a vertical viewport was given an unlimited amount\n'
' of horizontal space in which to expand.\n',
);
});
testWidgets('Vertical viewport was given unbounded height', (WidgetTester tester) async {
await expectFlutterError(
widget: buildNestedWidget(Axis.vertical, Axis.vertical),
tester: tester,
message:
'FlutterError\n'
' Vertical viewport was given unbounded height.\n'
' Viewports expand in the scrolling direction to fill their\n'
' container. In this case, a vertical viewport was given an\n'
' unlimited amount of vertical space in which to expand. This\n'
' situation typically happens when a scrollable widget is nested\n'
' inside another scrollable widget.\n'
' If this widget is always nested in a scrollable widget there is\n'
' no need to use a viewport because there will always be enough\n'
' vertical space for the children. In this case, consider using a\n'
' Column or Wrap instead. Otherwise, consider using a\n'
' CustomScrollView to concatenate arbitrary slivers into a single\n'
' scrollable.\n',
);
});
});
test('Viewport debugThrowIfNotCheckingIntrinsics() control test', () {
final RenderViewport renderViewport = RenderViewport(
crossAxisDirection: AxisDirection.right, offset: ViewportOffset.zero(),
);
late FlutterError error;
try {
renderViewport.computeMinIntrinsicHeight(0);
} on FlutterError catch (e) {
error = e;
}
expect(
error.toStringDeep(),
'FlutterError\n'
' RenderViewport does not support returning intrinsic dimensions.\n'
' Calculating the intrinsic dimensions would require instantiating\n'
' every child of the viewport, which defeats the point of viewports\n'
' being lazy.\n'
' If you are merely trying to shrink-wrap the viewport in the main\n'
' axis direction, consider a RenderShrinkWrappingViewport render\n'
' object (ShrinkWrappingViewport widget), which achieves that\n'
' effect without implementing the intrinsic dimension API.\n',
);
final RenderShrinkWrappingViewport renderShrinkWrappingViewport = RenderShrinkWrappingViewport(
crossAxisDirection: AxisDirection.right, offset: ViewportOffset.zero(),
);
try {
renderShrinkWrappingViewport.computeMinIntrinsicHeight(0);
} on FlutterError catch (e) {
error = e;
}
expect(error, isNotNull);
expect(
error.toStringDeep(),
'FlutterError\n'
' RenderShrinkWrappingViewport does not support returning intrinsic\n'
' dimensions.\n'
' Calculating the intrinsic dimensions would require instantiating\n'
' every child of the viewport, which defeats the point of viewports\n'
' being lazy.\n'
' If you are merely trying to shrink-wrap the viewport in the main\n'
' axis direction, you should be able to achieve that effect by just\n'
' giving the viewport loose constraints, without needing to measure\n'
' its intrinsic dimensions.\n',
);
});
group('Viewport childrenInPaintOrder control test', () {
test('RenderViewport', () async {
final List<RenderSliver> children = <RenderSliver>[
RenderSliverToBoxAdapter(),
RenderSliverToBoxAdapter(),
RenderSliverToBoxAdapter(),
];
final RenderViewport renderViewport = RenderViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
children: children,
);
// Children should be painted in reverse order to the list given
expect(renderViewport.childrenInPaintOrder, equals(children.reversed));
// childrenInPaintOrder should be reverse of childrenInHitTestOrder
expect(
renderViewport.childrenInPaintOrder,
equals(renderViewport.childrenInHitTestOrder.toList().reversed),
);
});
test('RenderShrinkWrappingViewport', () async {
final List<RenderSliver> children = <RenderSliver>[
RenderSliverToBoxAdapter(),
RenderSliverToBoxAdapter(),
RenderSliverToBoxAdapter(),
];
final RenderShrinkWrappingViewport renderViewport =
RenderShrinkWrappingViewport(
crossAxisDirection: AxisDirection.right,
offset: ViewportOffset.zero(),
children: children,
);
// Children should be painted in reverse order to the list given
expect(renderViewport.childrenInPaintOrder, equals(children.reversed));
// childrenInPaintOrder should be reverse of childrenInHitTestOrder
expect(
renderViewport.childrenInPaintOrder,
equals(renderViewport.childrenInHitTestOrder.toList().reversed),
);
});
});
group('Overscrolling RenderShrinkWrappingViewport', () {
Widget buildSimpleShrinkWrap({
ScrollController? controller,
Axis scrollDirection = Axis.vertical,
ScrollPhysics? physics,
}) {
return Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child: ListView.builder(
controller: controller,
physics: physics,
scrollDirection: scrollDirection,
shrinkWrap: true,
itemBuilder: (BuildContext context, int index) => SizedBox(height: 50, width: 50, child: Text('Item $index')),
itemCount: 20,
itemExtent: 50,
),
),
);
}
Widget buildClippingShrinkWrap(
ScrollController controller, {
bool constrain = false,
}) {
return Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child: ColoredBox(
color: const Color(0xFF000000),
child: Column(
children: <Widget>[
// Translucent boxes above and below the shrinkwrapped viewport
// make it easily discernible if the viewport is not being
// clipped properly.
Opacity(
opacity: 0.5,
child: Container(height: 100, color: const Color(0xFF00B0FF)),
),
Container(
height: constrain ? 150 : null,
color: const Color(0xFFF44336),
child: ListView.builder(
controller: controller,
shrinkWrap: true,
physics: const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()),
itemBuilder: (BuildContext context, int index) => Text('Item $index'),
itemCount: 10,
),
),
Opacity(
opacity: 0.5,
child: Container(height: 100, color: const Color(0xFF00B0FF)),
),
],
),
),
),
);
}
testWidgets('constrained viewport correctly clips overflow', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/89717
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
buildClippingShrinkWrap(controller, constrain: true)
);
expect(controller.offset, 0.0);
expect(tester.getTopLeft(find.text('Item 0')).dy, 100.0);
expect(tester.getTopLeft(find.text('Item 9')).dy, 226.0);
// Overscroll
final TestGesture overscrollGesture = await tester.startGesture(tester.getCenter(find.text('Item 0')));
await overscrollGesture.moveBy(const Offset(0, 100));
await tester.pump();
expect(controller.offset, -100.0);
expect(tester.getTopLeft(find.text('Item 0')).dy, 200.0);
await expectLater(
find.byType(Directionality),
matchesGoldenFile('shrinkwrap_clipped_constrained_overscroll.png'),
);
await overscrollGesture.up();
await tester.pumpAndSettle();
expect(controller.offset, 0.0);
expect(tester.getTopLeft(find.text('Item 0')).dy, 100.0);
expect(tester.getTopLeft(find.text('Item 9')).dy, 226.0);
});
testWidgets('correctly clips overflow without constraints', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/89717
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
buildClippingShrinkWrap(controller)
);
expect(controller.offset, 0.0);
expect(tester.getTopLeft(find.text('Item 0')).dy, 100.0);
expect(tester.getTopLeft(find.text('Item 9')).dy, 226.0);
// Overscroll
final TestGesture overscrollGesture = await tester.startGesture(tester.getCenter(find.text('Item 0')));
await overscrollGesture.moveBy(const Offset(0, 100));
await tester.pump();
expect(controller.offset, -100.0);
expect(tester.getTopLeft(find.text('Item 0')).dy, 200.0);
await expectLater(
find.byType(Directionality),
matchesGoldenFile('shrinkwrap_clipped_overscroll.png'),
);
await overscrollGesture.up();
await tester.pumpAndSettle();
expect(controller.offset, 0.0);
expect(tester.getTopLeft(find.text('Item 0')).dy, 100.0);
expect(tester.getTopLeft(find.text('Item 9')).dy, 226.0);
});
testWidgets('allows overscrolling on default platforms - vertical', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/10949
// Scrollables should overscroll by default on iOS and macOS
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
buildSimpleShrinkWrap(controller: controller),
);
expect(controller.offset, 0.0);
expect(tester.getTopLeft(find.text('Item 0')).dy, 0.0);
// Check overscroll at both ends
// Start
TestGesture overscrollGesture = await tester.startGesture(tester.getCenter(find.byType(ListView)));
await overscrollGesture.moveBy(const Offset(0, 25));
await tester.pump();
expect(controller.offset, -25.0);
expect(tester.getTopLeft(find.text('Item 0')).dy, 25.0);
await overscrollGesture.up();
await tester.pumpAndSettle();
expect(controller.offset, 0.0);
expect(tester.getTopLeft(find.text('Item 0')).dy, 0.0);
// End
final double maxExtent = controller.position.maxScrollExtent;
controller.jumpTo(controller.position.maxScrollExtent);
await tester.pumpAndSettle();
expect(controller.offset, maxExtent);
expect(tester.getBottomLeft(find.text('Item 19')).dy, 600.0);
overscrollGesture = await tester.startGesture(tester.getCenter(find.byType(ListView)));
await overscrollGesture.moveBy(const Offset(0, -25));
await tester.pump();
expect(controller.offset, greaterThan(maxExtent));
expect(tester.getBottomLeft(find.text('Item 19')).dy, 575.0);
await overscrollGesture.up();
await tester.pumpAndSettle();
expect(controller.offset, maxExtent);
expect(tester.getBottomLeft(find.text('Item 19')).dy, 600.0);
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('allows overscrolling on default platforms - horizontal', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/10949
// Scrollables should overscroll by default on iOS and macOS
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
buildSimpleShrinkWrap(controller: controller, scrollDirection: Axis.horizontal),
);
expect(controller.offset, 0.0);
expect(tester.getTopLeft(find.text('Item 0')).dx, 0.0);
// Check overscroll at both ends
// Start
TestGesture overscrollGesture = await tester.startGesture(tester.getCenter(find.byType(ListView)));
await overscrollGesture.moveBy(const Offset(25, 0));
await tester.pump();
expect(controller.offset, -25.0);
expect(tester.getTopLeft(find.text('Item 0')).dx, 25.0);
await overscrollGesture.up();
await tester.pumpAndSettle();
expect(controller.offset, 0.0);
expect(tester.getTopLeft(find.text('Item 0')).dx, 0.0);
// End
final double maxExtent = controller.position.maxScrollExtent;
controller.jumpTo(controller.position.maxScrollExtent);
await tester.pumpAndSettle();
expect(controller.offset, maxExtent);
expect(tester.getTopRight(find.text('Item 19')).dx, 800.0);
overscrollGesture = await tester.startGesture(tester.getCenter(find.byType(ListView)));
await overscrollGesture.moveBy(const Offset(-25, 0));
await tester.pump();
expect(controller.offset, greaterThan(maxExtent));
expect(tester.getTopRight(find.text('Item 19')).dx, 775.0);
await overscrollGesture.up();
await tester.pumpAndSettle();
expect(controller.offset, maxExtent);
expect(tester.getTopRight(find.text('Item 19')).dx, 800.0);
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('allows overscrolling per physics - vertical', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/10949
// Scrollables should overscroll when the scroll physics allow
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
buildSimpleShrinkWrap(controller: controller, physics: const BouncingScrollPhysics()),
);
expect(controller.offset, 0.0);
expect(tester.getTopLeft(find.text('Item 0')).dy, 0.0);
// Check overscroll at both ends
// Start
TestGesture overscrollGesture = await tester.startGesture(tester.getCenter(find.byType(ListView)));
await overscrollGesture.moveBy(const Offset(0, 25));
await tester.pump();
expect(controller.offset, -25.0);
expect(tester.getTopLeft(find.text('Item 0')).dy, 25.0);
await overscrollGesture.up();
await tester.pumpAndSettle();
expect(controller.offset, 0.0);
expect(tester.getTopLeft(find.text('Item 0')).dy, 0.0);
// End
final double maxExtent = controller.position.maxScrollExtent;
controller.jumpTo(controller.position.maxScrollExtent);
await tester.pumpAndSettle();
expect(controller.offset, maxExtent);
expect(tester.getBottomLeft(find.text('Item 19')).dy, 600.0);
overscrollGesture = await tester.startGesture(tester.getCenter(find.byType(ListView)));
await overscrollGesture.moveBy(const Offset(0, -25));
await tester.pump();
expect(controller.offset, greaterThan(maxExtent));
expect(tester.getBottomLeft(find.text('Item 19')).dy, 575.0);
await overscrollGesture.up();
await tester.pumpAndSettle();
expect(controller.offset, maxExtent);
expect(tester.getBottomLeft(find.text('Item 19')).dy, 600.0);
});
testWidgets('allows overscrolling per physics - horizontal', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/10949
// Scrollables should overscroll when the scroll physics allow
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
buildSimpleShrinkWrap(
controller: controller,
scrollDirection: Axis.horizontal,
physics: const BouncingScrollPhysics(),
),
);
expect(controller.offset, 0.0);
expect(tester.getTopLeft(find.text('Item 0')).dx, 0.0);
// Check overscroll at both ends
// Start
TestGesture overscrollGesture = await tester.startGesture(tester.getCenter(find.byType(ListView)));
await overscrollGesture.moveBy(const Offset(25, 0));
await tester.pump();
expect(controller.offset, -25.0);
expect(tester.getTopLeft(find.text('Item 0')).dx, 25.0);
await overscrollGesture.up();
await tester.pumpAndSettle();
expect(controller.offset, 0.0);
expect(tester.getTopLeft(find.text('Item 0')).dx, 0.0);
// End
final double maxExtent = controller.position.maxScrollExtent;
controller.jumpTo(controller.position.maxScrollExtent);
await tester.pumpAndSettle();
expect(controller.offset, maxExtent);
expect(tester.getTopRight(find.text('Item 19')).dx, 800.0);
overscrollGesture = await tester.startGesture(tester.getCenter(find.byType(ListView)));
await overscrollGesture.moveBy(const Offset(-25, 0));
await tester.pump();
expect(controller.offset, greaterThan(maxExtent));
expect(tester.getTopRight(find.text('Item 19')).dx, 775.0);
await overscrollGesture.up();
await tester.pumpAndSettle();
expect(controller.offset, maxExtent);
expect(tester.getTopRight(find.text('Item 19')).dx, 800.0);
});
});
testWidgets('Handles infinite constraints when TargetPlatform is iOS or macOS', (WidgetTester tester) async {
// regression test for https://github.com/flutter/flutter/issues/45866
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
GridView(
shrinkWrap: true,
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 3,
childAspectRatio: 3,
mainAxisSpacing: 3,
crossAxisSpacing: 3,
),
children: const <Widget>[
Text('a'),
Text('b'),
Text('c'),
],
),
],
),
),
),
);
expect(find.text('b'), findsOneWidget);
await tester.drag(find.text('b'), const Offset(0, 200));
await tester.pumpAndSettle();
}, variant: const TargetPlatformVariant(<TargetPlatform>{ TargetPlatform.iOS, TargetPlatform.macOS }));
testWidgets('Viewport describeApproximateClip respects clipBehavior', (WidgetTester tester) async {
await tester.pumpWidget(const Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
clipBehavior: Clip.none,
slivers: <Widget>[
SliverToBoxAdapter(child: SizedBox(width: 20, height: 20)),
]
),
));
RenderViewport viewport = tester.allRenderObjects.whereType<RenderViewport>().first;
expect(viewport.clipBehavior, Clip.none);
bool visited = false;
viewport.visitChildren((RenderObject child) {
visited = true;
expect(viewport.describeApproximatePaintClip(child as RenderSliver), null);
});
expect(visited, true);
await tester.pumpWidget(const Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
slivers: <Widget>[
SliverToBoxAdapter(child: SizedBox(width: 20, height: 20)),
]
),
));
viewport = tester.allRenderObjects.whereType<RenderViewport>().first;
expect(viewport.clipBehavior, Clip.hardEdge);
visited = false;
viewport.visitChildren((RenderObject child) {
visited = true;
expect(viewport.describeApproximatePaintClip(child as RenderSliver), Offset.zero & viewport.size);
});
expect(visited, true);
});
testWidgets(
'Shrinkwrapping viewport asserts bounded cross axis', (WidgetTester tester) async {
final List<FlutterErrorDetails> errors = <FlutterErrorDetails>[];
FlutterError.onError = (FlutterErrorDetails error) => errors.add(error);
// Vertical
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
ListView(
shrinkWrap: true,
children: const <Widget>[ SizedBox.square(dimension: 500) ],
),
],
),
));
expect(errors, isNotEmpty);
expect(errors.first.exception, isFlutterError);
FlutterError error = errors.first.exception as FlutterError;
expect(
error.toString(),
contains('Viewports expand in the cross axis to fill their container'),
);
errors.clear();
// Horizontal
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: ListView(
children: <Widget>[
ListView(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
children: const <Widget>[ SizedBox.square(dimension: 500) ],
),
],
),
));
expect(errors, isNotEmpty);
expect(errors.first.exception, isFlutterError);
error = errors.first.exception as FlutterError;
expect(
error.toString(),
contains('Viewports expand in the cross axis to fill their container'),
);
errors.clear();
// No children
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
ListView(
shrinkWrap: true,
),
],
),
));
expect(errors, isNotEmpty);
expect(errors.first.exception, isFlutterError);
error = errors.first.exception as FlutterError;
expect(
error.toString(),
contains('Viewports expand in the cross axis to fill their container'),
);
errors.clear();
});
testWidgets('RenderViewport maxLayoutCycles depends on the number of children',
(WidgetTester tester) async {
Future<void> expectFlutterError({
required Widget widget,
required WidgetTester tester,
}) async {
final List<FlutterErrorDetails> errors = <FlutterErrorDetails>[];
final FlutterExceptionHandler? oldHandler = FlutterError.onError;
FlutterError.onError = (FlutterErrorDetails error) => errors.add(error);
try {
await tester.pumpWidget(widget);
} finally {
FlutterError.onError = oldHandler;
}
expect(errors, isNotEmpty);
expect(errors.first.exception, isFlutterError);
}
Widget buildWidget({required int sliverCount, required int correctionsCount}) {
return Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
slivers: List<Widget>.generate(
sliverCount,
(_) => _ScrollOffsetCorrectionSliver(correctionsCount: correctionsCount)),
),
);
}
// 5 correction per child will pass.
await tester.pumpWidget(buildWidget(sliverCount: 30, correctionsCount: 5));
// 15 correction per child will throw exception.
await expectFlutterError(
widget: buildWidget(sliverCount: 1, correctionsCount: 15),
tester: tester,
);
});
}
// Simple sliver that applies N scroll offset corrections.
class _RenderScrollOffsetCorrectionSliver extends RenderSliver {
int _correctionCount = 0;
@override
void performLayout() {
if (_correctionCount > 0) {
--_correctionCount;
geometry = const SliverGeometry(scrollOffsetCorrection: 1.0);
return;
}
const double extent = 5;
final double paintedChildSize = calculatePaintOffset(constraints, from: 0.0, to: extent);
final double cacheExtent = calculateCacheOffset(constraints, from: 0.0, to: extent);
geometry = SliverGeometry(
scrollExtent: extent,
paintExtent: paintedChildSize,
maxPaintExtent: extent,
cacheExtent: cacheExtent
);
}
}
class _ScrollOffsetCorrectionSliver extends SingleChildRenderObjectWidget {
const _ScrollOffsetCorrectionSliver({required this.correctionsCount});
final int correctionsCount;
@override
_RenderScrollOffsetCorrectionSliver createRenderObject(BuildContext context) {
final _RenderScrollOffsetCorrectionSliver sliver = _RenderScrollOffsetCorrectionSliver();
sliver._correctionCount = correctionsCount;
return sliver;
}
@override
void updateRenderObject(BuildContext context, covariant _RenderScrollOffsetCorrectionSliver renderObject) {
super.updateRenderObject(context, renderObject);
renderObject.markNeedsLayout();
renderObject._correctionCount = correctionsCount;
}
}
| flutter/packages/flutter/test/rendering/viewport_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/rendering/viewport_test.dart",
"repo_id": "flutter",
"token_count": 40473
} | 679 |
// 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/semantics.dart';
import 'package:flutter/services.dart' show SystemChannels;
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
test('Semantic announcement', () async {
final List<Map<dynamic, dynamic>> log = <Map<dynamic, dynamic>>[];
Future<dynamic> handleMessage(dynamic mockMessage) async {
final Map<dynamic, dynamic> message = mockMessage as Map<dynamic, dynamic>;
log.add(message);
}
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockDecodedMessageHandler<dynamic>(SystemChannels.accessibility, handleMessage);
await SemanticsService.announce('announcement 1', TextDirection.ltr);
await SemanticsService.announce('announcement 2', TextDirection.rtl, assertiveness: Assertiveness.assertive);
expect(log, equals(<Map<String, dynamic>>[
<String, dynamic>{'type': 'announce', 'data': <String, dynamic>{'message': 'announcement 1', 'textDirection': 1}},
<String, dynamic>{'type': 'announce', 'data': <String, dynamic>{'message': 'announcement 2', 'textDirection': 0, 'assertiveness': 1}},
]));
});
}
| flutter/packages/flutter/test/semantics/semantics_service_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/semantics/semantics_service_test.dart",
"repo_id": "flutter",
"token_count": 438
} | 680 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
class TestFontLoader extends FontLoader {
TestFontLoader(super.family);
@override
Future<void> loadFont(Uint8List list, String family) async {
fontAssets.add(list);
}
List<Uint8List> fontAssets = <Uint8List>[];
}
void main() {
test('Font loader test', () async {
final TestFontLoader tfl = TestFontLoader('TestFamily');
final List<Uint8List> expectedAssets = <Uint8List>[
Uint8List.fromList(<int>[100]),
Uint8List.fromList(<int>[10, 20, 30]),
Uint8List.fromList(<int>[200]),
];
for (final Uint8List asset in expectedAssets) {
tfl.addFont(Future<ByteData>.value(ByteData.view(asset.buffer)));
}
await tfl.load();
expect(tfl.fontAssets, unorderedEquals(expectedAssets));
});
}
| flutter/packages/flutter/test/services/font_loader_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/services/font_loader_test.dart",
"repo_id": "flutter",
"token_count": 368
} | 681 |
// 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/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
import 'restoration.dart';
void main() {
test('root bucket values', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket bucket = RestorationBucket.root(manager: manager, rawData: rawData);
expect(bucket.restorationId, 'root');
expect(bucket.debugOwner, manager);
// Bucket contains expected values from rawData.
expect(bucket.read<int>('value1'), 10);
expect(bucket.read<String>('value2'), 'Hello');
expect(bucket.read<String>('value3'), isNull); // Does not exist.
expect(manager.updateScheduled, isFalse);
// Can overwrite existing value.
bucket.write<int>('value1', 22);
expect(manager.updateScheduled, isTrue);
expect(bucket.read<int>('value1'), 22);
manager.doSerialization();
expect((rawData[valuesMapKey] as Map<String, dynamic>)['value1'], 22);
expect(manager.updateScheduled, isFalse);
// Can add a new value.
bucket.write<bool>('value3', true);
expect(manager.updateScheduled, isTrue);
expect(bucket.read<bool>('value3'), true);
manager.doSerialization();
expect((rawData[valuesMapKey] as Map<String, dynamic>)['value3'], true);
expect(manager.updateScheduled, isFalse);
// Can remove existing value.
expect(bucket.remove<int>('value1'), 22);
expect(manager.updateScheduled, isTrue);
expect(bucket.read<int>('value1'), isNull); // Does not exist anymore.
manager.doSerialization();
expect((rawData[valuesMapKey] as Map<String, dynamic>).containsKey('value1'), isFalse);
expect(manager.updateScheduled, isFalse);
// Removing non-existing value is no-op.
expect(bucket.remove<Object>('value4'), isNull);
expect(manager.updateScheduled, isFalse);
// Can store null.
bucket.write<bool?>('value4', null);
expect(manager.updateScheduled, isTrue);
expect(bucket.read<int>('value4'), null);
manager.doSerialization();
expect((rawData[valuesMapKey] as Map<String, dynamic>).containsKey('value4'), isTrue);
expect((rawData[valuesMapKey] as Map<String, dynamic>)['value4'], null);
expect(manager.updateScheduled, isFalse);
});
test('child bucket values', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rootRawData = _createRawDataSet();
final Object debugOwner = Object();
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rootRawData);
final RestorationBucket child = RestorationBucket.child(
restorationId: 'child1',
parent: root,
debugOwner: debugOwner,
);
expect(child.restorationId, 'child1');
expect(child.debugOwner, debugOwner);
// Bucket contains expected values from rawData.
expect(child.read<int>('foo'), 22);
expect(child.read<String>('bar'), isNull); // Does not exist.
expect(manager.updateScheduled, isFalse);
// Can overwrite existing value.
child.write<int>('foo', 44);
expect(manager.updateScheduled, isTrue);
expect(child.read<int>('foo'), 44);
manager.doSerialization();
expect((((rootRawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<String, dynamic>)['foo'], 44);
expect(manager.updateScheduled, isFalse);
// Can add a new value.
child.write<bool>('value3', true);
expect(manager.updateScheduled, isTrue);
expect(child.read<bool>('value3'), true);
manager.doSerialization();
expect((((rootRawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<String, dynamic>)['value3'], true);
expect(manager.updateScheduled, isFalse);
// Can remove existing value.
expect(child.remove<int>('foo'), 44);
expect(manager.updateScheduled, isTrue);
expect(child.read<int>('foo'), isNull); // Does not exist anymore.
manager.doSerialization();
expect(((rootRawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>).containsKey('foo'), isFalse);
expect(manager.updateScheduled, isFalse);
// Removing non-existing value is no-op.
expect(child.remove<Object>('value4'), isNull);
expect(manager.updateScheduled, isFalse);
// Can store null.
child.write<bool?>('value4', null);
expect(manager.updateScheduled, isTrue);
expect(child.read<int>('value4'), null);
manager.doSerialization();
expect((((rootRawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<String, dynamic>).containsKey('value4'), isTrue);
expect((((rootRawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<String, dynamic>)['value4'], null);
expect(manager.updateScheduled, isFalse);
});
test('claim child with existing data', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket bucket = RestorationBucket.root(manager: manager, rawData: rawData);
final Object debugOwner = Object();
final RestorationBucket child = bucket.claimChild('child1', debugOwner: debugOwner);
expect(manager.updateScheduled, isFalse);
expect(child.restorationId, 'child1');
expect(child.debugOwner, debugOwner);
expect(child.read<int>('foo'), 22);
child.write('bar', 44);
expect(manager.updateScheduled, isTrue);
manager.doSerialization();
expect((((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<String, dynamic>)['bar'], 44);
expect(manager.updateScheduled, isFalse);
});
test('claim child with no existing data', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket bucket = RestorationBucket.root(manager: manager, rawData: rawData);
expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child2'), isFalse);
final Object debugOwner = Object();
final RestorationBucket child = bucket.claimChild('child2', debugOwner: debugOwner);
expect(manager.updateScheduled, isTrue);
expect(child.restorationId, 'child2');
expect(child.debugOwner, debugOwner);
child.write('foo', 55);
expect(child.read<int>('foo'), 55);
manager.doSerialization();
expect(manager.updateScheduled, isFalse);
expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child2'), isTrue);
expect((((rawData[childrenMapKey] as Map<String, dynamic>)['child2'] as Map<String, dynamic>)[valuesMapKey] as Map<Object?, Object?>)['foo'], 55);
});
test('claim child that is already claimed throws if not given up', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket bucket = RestorationBucket.root(manager: manager, rawData: rawData);
final RestorationBucket child1 = bucket.claimChild('child1', debugOwner: 'FirstClaim');
expect(manager.updateScheduled, isFalse);
expect(child1.restorationId, 'child1');
expect(child1.read<int>('foo'), 22);
manager.doSerialization();
expect(manager.updateScheduled, isFalse);
final RestorationBucket child2 = bucket.claimChild('child1', debugOwner: 'SecondClaim');
expect(child2.restorationId, 'child1');
expect(child2.read<int>('foo'), isNull); // Value does not exist in this child.
// child1 is not given up before running finalizers.
expect(
() => manager.doSerialization(),
throwsA(isFlutterError.having(
(FlutterError error) => error.message,
'message',
equals(
'Multiple owners claimed child RestorationBuckets with the same IDs.\n'
'The following IDs were claimed multiple times from the parent RestorationBucket(restorationId: root, owner: MockManager):\n'
' * "child1" was claimed by:\n'
' * SecondClaim\n'
' * FirstClaim (current owner)',
),
)),
);
});
test('claim child that is already claimed does not throw if given up', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket bucket = RestorationBucket.root(manager: manager, rawData: rawData);
final RestorationBucket child1 = bucket.claimChild('child1', debugOwner: 'FirstClaim');
expect(manager.updateScheduled, isFalse);
expect(child1.restorationId, 'child1');
expect(child1.read<int>('foo'), 22);
manager.doSerialization();
expect(manager.updateScheduled, isFalse);
final RestorationBucket child2 = bucket.claimChild('child1', debugOwner: 'SecondClaim');
expect(child2.restorationId, 'child1');
expect(child2.read<int>('foo'), isNull); // Value does not exist in this child.
child2.write<int>('bar', 55);
// give up child1.
child1.dispose();
manager.doSerialization();
expect(manager.updateScheduled, isFalse);
expect((((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<Object?, Object?>).containsKey('foo'), isFalse);
expect((((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[valuesMapKey] as Map<Object?, Object?>)['bar'], 55);
});
test('claiming a claimed child twice and only giving it up once throws', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket bucket = RestorationBucket.root(manager: manager, rawData: rawData);
final RestorationBucket child1 = bucket.claimChild('child1', debugOwner: 'FirstClaim');
expect(child1.restorationId, 'child1');
final RestorationBucket child2 = bucket.claimChild('child1', debugOwner: 'SecondClaim');
expect(child2.restorationId, 'child1');
child1.dispose();
final RestorationBucket child3 = bucket.claimChild('child1', debugOwner: 'ThirdClaim');
expect(child3.restorationId, 'child1');
expect(manager.updateScheduled, isTrue);
expect(() => manager.doSerialization(), throwsFlutterError);
});
test('unclaiming and then claiming same id gives fresh bucket', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket bucket = RestorationBucket.root(manager: manager, rawData: rawData);
final RestorationBucket child1 = bucket.claimChild('child1', debugOwner: 'FirstClaim');
expect(manager.updateScheduled, isFalse);
expect(child1.read<int>('foo'), 22);
child1.dispose();
expect(manager.updateScheduled, isTrue);
final RestorationBucket child2 = bucket.claimChild('child1', debugOwner: 'SecondClaim');
expect(child2.read<int>('foo'), isNull);
});
test('cleans up raw data if last value/child is dropped', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData);
expect(rawData.containsKey(childrenMapKey), isTrue);
final RestorationBucket child = root.claimChild('child1', debugOwner: 'owner');
child.dispose();
expect(manager.updateScheduled, isTrue);
manager.doSerialization();
expect(rawData.containsKey(childrenMapKey), isFalse);
expect(rawData.containsKey(valuesMapKey), isTrue);
expect(root.remove<int>('value1'), 10);
expect(root.remove<String>('value2'), 'Hello');
expect(manager.updateScheduled, isTrue);
manager.doSerialization();
expect(rawData.containsKey(valuesMapKey), isFalse);
});
test('dispose deletes data', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData);
final RestorationBucket child1 = root.claimChild('child1', debugOwner: 'owner1');
child1.claimChild('child1OfChild1', debugOwner: 'owner1.1');
child1.claimChild('child2OfChild1', debugOwner: 'owner1.2');
final RestorationBucket child2 = root.claimChild('child2', debugOwner: 'owner2');
expect(manager.updateScheduled, isTrue);
manager.doSerialization();
expect(manager.updateScheduled, isFalse);
expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child1'), isTrue);
expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child2'), isTrue);
child1.dispose();
expect(manager.updateScheduled, isTrue);
manager.doSerialization();
expect(manager.updateScheduled, isFalse);
expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child1'), isFalse);
child2.dispose();
expect(manager.updateScheduled, isTrue);
manager.doSerialization();
expect(manager.updateScheduled, isFalse);
expect(rawData.containsKey(childrenMapKey), isFalse);
});
test('rename is no-op if same id', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData);
final RestorationBucket child = root.claimChild('child1', debugOwner: 'owner1');
expect(manager.updateScheduled, isFalse);
expect(child.restorationId, 'child1');
child.rename('child1');
expect(manager.updateScheduled, isFalse);
expect(child.restorationId, 'child1');
expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child1'), isTrue);
});
test('rename to unused id', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData);
final RestorationBucket child = root.claimChild('child1', debugOwner: 'owner1');
final Object rawChildData = (rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Object;
expect(rawChildData, isNotNull);
expect(manager.updateScheduled, isFalse);
expect(child.restorationId, 'child1');
child.rename('new-name');
expect(child.restorationId, 'new-name');
expect(manager.updateScheduled, isTrue);
manager.doSerialization();
expect(manager.updateScheduled, isFalse);
expect((rawData[childrenMapKey] as Map<Object?, Object?>).containsKey('child1'), isFalse);
expect((rawData[childrenMapKey] as Map<Object?, Object?>)['new-name'], rawChildData);
});
test('rename to used id throws if id is not given up', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData);
final RestorationBucket child1 = root.claimChild('child1', debugOwner: 'owner1');
final RestorationBucket child2 = root.claimChild('child2', debugOwner: 'owner1');
manager.doSerialization();
expect(child1.restorationId, 'child1');
expect(child2.restorationId, 'child2');
child2.rename('child1');
expect(child2.restorationId, 'child1');
expect(manager.updateScheduled, isTrue);
expect(() => manager.doSerialization(), throwsFlutterError);
});
test('rename to used id does not throw if id is given up', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData);
final RestorationBucket child1 = root.claimChild('child1', debugOwner: 'owner1');
final RestorationBucket child2 = root.claimChild('child2', debugOwner: 'owner1');
manager.doSerialization();
final Object rawChild1Data = (rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Object;
expect(rawChild1Data, isNotNull);
final Object rawChild2Data = (rawData[childrenMapKey] as Map<String, dynamic>)['child2'] as Object;
expect(rawChild2Data, isNotNull);
expect(child1.restorationId, 'child1');
expect(child2.restorationId, 'child2');
child2.rename('child1');
expect(child2.restorationId, 'child1');
expect(child1.restorationId, 'child1');
child1.dispose();
expect(manager.updateScheduled, isTrue);
manager.doSerialization();
expect(manager.updateScheduled, isFalse);
expect((rawData[childrenMapKey] as Map<String, dynamic>)['child1'], rawChild2Data);
expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child2'), isFalse);
});
test('renaming a to be added child', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData);
final Object rawChild1Data = (rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Object;
expect(rawChild1Data, isNotNull);
final RestorationBucket child1 = root.claimChild('child1', debugOwner: 'owner1');
final RestorationBucket child2 = root.claimChild('child1', debugOwner: 'owner1');
child2.rename('foo');
expect(manager.updateScheduled, isTrue);
manager.doSerialization();
expect(manager.updateScheduled, isFalse);
expect(child1.restorationId, 'child1');
expect(child2.restorationId, 'foo');
expect((rawData[childrenMapKey] as Map<String, dynamic>)['child1'], rawChild1Data);
expect((rawData[childrenMapKey] as Map<String, dynamic>)['foo'], isEmpty); // new bucket
});
test('adopt is no-op if same parent', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData);
final RestorationBucket child1 = root.claimChild('child1', debugOwner: 'owner1');
root.adoptChild(child1);
expect(manager.updateScheduled, isFalse);
expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('child1'), isTrue);
});
test('adopt fresh child', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData);
final RestorationBucket child = RestorationBucket.empty(restorationId: 'fresh-child', debugOwner: 'owner1');
root.adoptChild(child);
expect(manager.updateScheduled, isTrue);
child.write('value', 22);
manager.doSerialization();
expect(manager.updateScheduled, isFalse);
expect((rawData[childrenMapKey] as Map<String, dynamic>).containsKey('fresh-child'), isTrue);
expect((((rawData[childrenMapKey] as Map<String, dynamic>)['fresh-child'] as Map<String, dynamic>)[valuesMapKey] as Map<Object?, Object?>)['value'], 22);
child.write('bar', 'blabla');
expect(manager.updateScheduled, isTrue);
});
test('adopt child that already had a parent', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData);
final RestorationBucket child = root.claimChild('child1', debugOwner: 'owner1');
final RestorationBucket childOfChild = child.claimChild('childOfChild', debugOwner: 'owner2');
childOfChild.write<String>('foo', 'bar');
expect(manager.updateScheduled, isTrue);
manager.doSerialization();
expect(manager.updateScheduled, isFalse);
final Object childOfChildData = (((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[childrenMapKey] as Map<Object?, Object?>)['childOfChild']!;
expect(childOfChildData, isNotEmpty);
root.adoptChild(childOfChild);
expect(manager.updateScheduled, isTrue);
manager.doSerialization();
expect(manager.updateScheduled, isFalse);
expect(((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>).containsKey(childrenMapKey), isFalse); // child1 has no children anymore.
expect((rawData[childrenMapKey] as Map<String, dynamic>)['childOfChild'], childOfChildData);
});
test('adopting child throws if id is already in use and not given up', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData);
final RestorationBucket child = root.claimChild('child1', debugOwner: 'owner1');
final RestorationBucket childOfChild = child.claimChild('child1', debugOwner: 'owner2');
childOfChild.write<String>('foo', 'bar');
root.adoptChild(childOfChild);
expect(manager.updateScheduled, isTrue);
expect(() => manager.doSerialization(), throwsFlutterError);
});
test('adopting child does not throw if id is already in use and given up', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData);
final RestorationBucket child = root.claimChild('child1', debugOwner: 'owner1');
final RestorationBucket childOfChild = child.claimChild('child1', debugOwner: 'owner2');
childOfChild.write<String>('foo', 'bar');
final Object childOfChildData = (((rawData[childrenMapKey] as Map<String, dynamic>)['child1'] as Map<String, dynamic>)[childrenMapKey] as Map<Object?, Object?>)['child1']!;
expect(childOfChildData, isNotEmpty);
expect(manager.updateScheduled, isTrue);
manager.doSerialization();
expect(manager.updateScheduled, isFalse);
root.adoptChild(childOfChild);
expect(manager.updateScheduled, isTrue);
child.dispose();
manager.doSerialization();
expect(manager.updateScheduled, isFalse);
expect((rawData[childrenMapKey] as Map<String, dynamic>)['child1'], childOfChildData);
});
test('adopting a to-be-added child under an already in use id', () {
final MockRestorationManager manager = MockRestorationManager();
final Map<String, dynamic> rawData = _createRawDataSet();
final RestorationBucket root = RestorationBucket.root(manager: manager, rawData: rawData);
final RestorationBucket child1 = root.claimChild('child1', debugOwner: 'owner1');
final RestorationBucket child2 = root.claimChild('child2', debugOwner: 'owner1');
expect(manager.updateScheduled, isTrue);
manager.doSerialization();
expect(manager.updateScheduled, isFalse);
final RestorationBucket child1OfChild1 = child1.claimChild('child2', debugOwner: 'owner2');
child1OfChild1.write<String>('hello', 'world');
final RestorationBucket child2OfChild1 = child1.claimChild('child2', debugOwner: 'owner2');
child2OfChild1.write<String>('foo', 'bar');
root.adoptChild(child2OfChild1);
child2.dispose();
expect(manager.updateScheduled, isTrue);
manager.doSerialization();
expect(manager.updateScheduled, isFalse);
expect((((rawData[childrenMapKey] as Map<String, dynamic>)['child2'] as Map<String, dynamic>)[valuesMapKey] as Map<Object?, Object?>)['foo'], 'bar');
expect((((((rawData[childrenMapKey] as Map<String, dynamic>)
['child1'] as Map<String, dynamic>)
[childrenMapKey] as Map<Object?, Object?>)
['child2']! as Map<String, dynamic>)
[valuesMapKey] as Map<Object?, Object?>)
['hello'], 'world');
});
test('throws when used after dispose', () {
final RestorationBucket bucket = RestorationBucket.empty(restorationId: 'foo', debugOwner: null);
bucket.dispose();
expect(() => bucket.debugOwner, throwsFlutterError);
expect(() => bucket.restorationId, throwsFlutterError);
expect(() => bucket.read<int>('foo'), throwsFlutterError);
expect(() => bucket.write('foo', 10), throwsFlutterError);
expect(() => bucket.remove<int>('foo'), throwsFlutterError);
expect(() => bucket.contains('foo'), throwsFlutterError);
expect(() => bucket.claimChild('child', debugOwner: null), throwsFlutterError);
final RestorationBucket child = RestorationBucket.empty(restorationId: 'child', debugOwner: null);
expect(() => bucket.adoptChild(child), throwsFlutterError);
expect(() => bucket.rename('bar'), throwsFlutterError);
expect(() => bucket.dispose(), throwsFlutterError);
});
test('$RestorationBucket dispatches memory events', () async {
await expectLater(
await memoryEvents(
() => RestorationBucket.empty(
restorationId: 'child1',
debugOwner: null,
).dispose(),
RestorationBucket,
),
areCreateAndDispose,
);
final MockRestorationManager manager1 = MockRestorationManager();
addTearDown(manager1.dispose);
await expectLater(
await memoryEvents(
() => RestorationBucket.root(
manager: manager1,
rawData: null,
).dispose(),
RestorationBucket,
),
areCreateAndDispose,
);
final MockRestorationManager manager2 = MockRestorationManager();
addTearDown(manager2.dispose);
final RestorationBucket parent = RestorationBucket.root(
manager: manager2,
rawData: _createRawDataSet()
);
addTearDown(parent.dispose);
await expectLater(
await memoryEvents(
() => RestorationBucket.child(
restorationId: 'child1',
parent: parent,
debugOwner: null,
).dispose(),
RestorationBucket,
),
areCreateAndDispose,
);
});
}
Map<String, dynamic> _createRawDataSet() {
return <String, dynamic>{
valuesMapKey: <String, dynamic>{
'value1' : 10,
'value2' : 'Hello',
},
childrenMapKey: <String, dynamic>{
'child1' : <String, dynamic>{
valuesMapKey : <String, dynamic>{
'foo': 22,
},
},
},
};
}
| flutter/packages/flutter/test/services/restoration_bucket_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/services/restoration_bucket_test.dart",
"repo_id": "flutter",
"token_count": 8958
} | 682 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('AnimatedAlign.debugFillProperties', (WidgetTester tester) async {
const AnimatedAlign box = AnimatedAlign(
alignment: Alignment.topCenter,
curve: Curves.ease,
duration: Duration(milliseconds: 200),
);
expect(box, hasOneLineDescription);
});
testWidgets('AnimatedAlign alignment visual-to-directional animation', (WidgetTester tester) async {
final Key target = UniqueKey();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: AnimatedAlign(
duration: const Duration(milliseconds: 200),
alignment: Alignment.topRight,
child: SizedBox(key: target, width: 100.0, height: 200.0),
),
),
);
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(800.0, 0.0));
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: AnimatedAlign(
duration: const Duration(milliseconds: 200),
alignment: AlignmentDirectional.bottomStart,
child: SizedBox(key: target, width: 100.0, height: 200.0),
),
),
);
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(800.0, 0.0));
await tester.pump(const Duration(milliseconds: 100));
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(800.0, 200.0));
await tester.pump(const Duration(milliseconds: 500));
expect(tester.getSize(find.byKey(target)), const Size(100.0, 200.0));
expect(tester.getTopRight(find.byKey(target)), const Offset(800.0, 400.0));
});
testWidgets('AnimatedAlign widthFactor', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
AnimatedAlign(
alignment: Alignment.center,
curve: Curves.ease,
widthFactor: 0.5,
duration: Duration(milliseconds: 200),
child: SizedBox(
height: 100.0,
width: 100.0,
),
),
],
),
),
);
final RenderBox box = tester.renderObject<RenderBox>(find.byType(AnimatedAlign));
expect(box.size.width, equals(50.0));
});
testWidgets('AnimatedAlign heightFactor', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Column(
children: <Widget>[
AnimatedAlign(
alignment: Alignment.center,
curve: Curves.ease,
heightFactor: 0.5,
duration: Duration(milliseconds: 200),
child: SizedBox(
height: 100.0,
width: 100.0,
),
),
],
),
),
);
final RenderBox box = tester.renderObject<RenderBox>(find.byType(AnimatedAlign));
expect(box.size.height, equals( 50.0));
});
testWidgets('AnimatedAlign null height factor', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
AnimatedAlign(
alignment: Alignment.center,
curve: Curves.ease,
duration: Duration(milliseconds: 200),
child: SizedBox(
height: 100.0,
width: 100.0,
),
),
],
),
),
);
final RenderBox box = tester.renderObject<RenderBox>(find.byType(SizedBox));
expect(box.size, equals(const Size(100.0, 100)));
});
testWidgets('AnimatedAlign null widthFactor', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: SizedBox.shrink(
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
AnimatedAlign(
alignment: Alignment.center,
curve: Curves.ease,
duration: Duration(milliseconds: 200),
child: SizedBox(
height: 100.0,
width: 100.0,
),
),
],
),
),
),
);
final RenderBox box = tester.renderObject<RenderBox>(find.byType(SizedBox).last);
expect(box.size, equals(const Size(100.0, 100)));
});
}
| flutter/packages/flutter/test/widgets/animated_align_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/animated_align_test.dart",
"repo_id": "flutter",
"token_count": 2402
} | 683 |
// 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 Color kTitleColor = Color(0xFF333333);
const String kTitleString = 'Hello World';
Future<void> pumpApp(WidgetTester tester, { GenerateAppTitle? onGenerateTitle, Color? color }) async {
await tester.pumpWidget(
WidgetsApp(
supportedLocales: const <Locale>[
Locale('en', 'US'),
Locale('en', 'GB'),
],
title: kTitleString,
color: color ?? kTitleColor,
onGenerateTitle: onGenerateTitle,
onGenerateRoute: (RouteSettings settings) {
return PageRouteBuilder<void>(
pageBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
return Container();
},
);
},
),
);
}
void main() {
testWidgets('Specified title and color are used to build a Title', (WidgetTester tester) async {
await pumpApp(tester);
expect(tester.widget<Title>(find.byType(Title)).title, kTitleString);
expect(tester.widget<Title>(find.byType(Title)).color, kTitleColor);
});
testWidgets('Specified color is made opaque for Title', (WidgetTester tester) async {
// The Title widget can only handle fully opaque colors, the WidgetApp should
// ensure it only uses a fully opaque version of its color for the title.
const Color transparentBlue = Color(0xDD0000ff);
const Color opaqueBlue = Color(0xFF0000ff);
await pumpApp(tester, color: transparentBlue);
expect(tester.widget<Title>(find.byType(Title)).color, opaqueBlue);
});
testWidgets('onGenerateTitle handles changing locales', (WidgetTester tester) async {
String generateTitle(BuildContext context) {
return Localizations.localeOf(context).toString();
}
await pumpApp(tester, onGenerateTitle: generateTitle);
expect(tester.widget<Title>(find.byType(Title)).title, 'en_US');
expect(tester.widget<Title>(find.byType(Title)).color, kTitleColor);
await tester.binding.setLocale('en', 'GB');
await tester.pump();
expect(tester.widget<Title>(find.byType(Title)).title, 'en_GB');
expect(tester.widget<Title>(find.byType(Title)).color, kTitleColor);
// Not a supported locale, so we switch to supportedLocales[0], en_US
await tester.binding.setLocale('fr', 'CA');
await tester.pump();
expect(tester.widget<Title>(find.byType(Title)).title, 'en_US');
expect(tester.widget<Title>(find.byType(Title)).color, kTitleColor);
});
}
| flutter/packages/flutter/test/widgets/app_title_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/app_title_test.dart",
"repo_id": "flutter",
"token_count": 935
} | 684 |
// 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/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('Instantiating WidgetsFlutterBinding does neither schedule a frame nor register frame callbacks', () async {
// Regression test for https://github.com/flutter/flutter/issues/39494.
// Preconditions.
expect(PlatformDispatcher.instance.onBeginFrame, isNull);
expect(PlatformDispatcher.instance.onDrawFrame, isNull);
// Instantiation does nothing with regards to frame scheduling.
final WidgetsFlutterBindingWithTestBinaryMessenger binding = WidgetsFlutterBindingWithTestBinaryMessenger();
expect(binding, isA<WidgetsFlutterBinding>());
expect(SchedulerBinding.instance.hasScheduledFrame, isFalse);
expect(PlatformDispatcher.instance.onBeginFrame, isNull);
expect(PlatformDispatcher.instance.onDrawFrame, isNull);
// Framework starts with detached statue. Sends resumed signal to enable frame.
final ByteData message = const StringCodec().encodeMessage('AppLifecycleState.resumed')!;
await binding.defaultBinaryMessenger.handlePlatformMessage('flutter/lifecycle', message, (_) { });
expect(PlatformDispatcher.instance.onBeginFrame, isNull);
expect(PlatformDispatcher.instance.onDrawFrame, isNull);
expect(SchedulerBinding.instance.hasScheduledFrame, isFalse);
// Frame callbacks are registered lazily (and a frame scheduled) when the root widget is attached.
WidgetsBinding.instance.attachRootWidget(const Placeholder());
expect(PlatformDispatcher.instance.onBeginFrame, isNotNull);
expect(PlatformDispatcher.instance.onDrawFrame, isNotNull);
expect(SchedulerBinding.instance.hasScheduledFrame, isTrue);
});
}
class WidgetsFlutterBindingWithTestBinaryMessenger extends WidgetsFlutterBinding with TestDefaultBinaryMessengerBinding { }
| flutter/packages/flutter/test/widgets/binding_frame_scheduling_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/binding_frame_scheduling_test.dart",
"repo_id": "flutter",
"token_count": 636
} | 685 |
// 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() {
group('Container control tests:', () {
final Container container = Container(
alignment: Alignment.bottomRight,
padding: const EdgeInsets.all(7.0),
// uses color, not decoration:
color: const Color(0xFF00FF00),
foregroundDecoration: const BoxDecoration(color: Color(0x7F0000FF)),
width: 53.0,
height: 76.0,
constraints: const BoxConstraints(
minWidth: 50.0,
maxWidth: 55.0,
minHeight: 78.0,
maxHeight: 82.0,
),
margin: const EdgeInsets.all(5.0),
child: const SizedBox(
width: 25.0,
height: 33.0,
child: DecoratedBox(
// uses decoration, not color:
decoration: BoxDecoration(color: Color(0xFFFFFF00)),
),
),
);
testWidgets('paints as expected', (WidgetTester tester) async {
await tester.pumpWidget(Align(
alignment: Alignment.topLeft,
child: container,
));
final RenderBox box = tester.renderObject(find.byType(Container));
expect(box, isNotNull);
expect(box, paints
..rect(rect: const Rect.fromLTWH(5.0, 5.0, 53.0, 78.0), color: const Color(0xFF00FF00))
..rect(rect: const Rect.fromLTWH(26.0, 43.0, 25.0, 33.0), color: const Color(0xFFFFFF00))
..rect(rect: const Rect.fromLTWH(5.0, 5.0, 53.0, 78.0), color: const Color(0x7F0000FF)),
);
});
group('diagnostics', () {
testWidgets('has reasonable default diagnostics', (WidgetTester tester) async {
await tester.pumpWidget(Align(
alignment: Alignment.topLeft,
child: container,
));
final RenderBox box = tester.renderObject(find.byType(Container));
expect(container, hasOneLineDescription);
expect(box, hasAGoodToStringDeep);
});
testWidgets('has expected info diagnostics', (WidgetTester tester) async {
await tester.pumpWidget(Align(
alignment: Alignment.topLeft,
child: container,
));
final RenderBox box = tester.renderObject(find.byType(Container));
expect(
box.toStringDeep(minLevel: DiagnosticLevel.info),
equalsIgnoringHashCodes(
'RenderPadding#00000 relayoutBoundary=up1\n'
' │ parentData: offset=Offset(0.0, 0.0) (can use size)\n'
' │ constraints: BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0)\n'
' │ size: Size(63.0, 88.0)\n'
' │ padding: EdgeInsets.all(5.0)\n'
' │\n'
' └─child: RenderConstrainedBox#00000 relayoutBoundary=up2\n'
' │ parentData: offset=Offset(5.0, 5.0) (can use size)\n'
' │ constraints: BoxConstraints(0.0<=w<=790.0, 0.0<=h<=590.0)\n'
' │ size: Size(53.0, 78.0)\n'
' │ additionalConstraints: BoxConstraints(w=53.0, h=78.0)\n'
' │\n'
' └─child: RenderDecoratedBox#00000\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=53.0, h=78.0)\n'
' │ size: Size(53.0, 78.0)\n'
' │ decoration: BoxDecoration:\n'
' │ color: Color(0x7f0000ff)\n'
' │ configuration: ImageConfiguration(bundle:\n'
' │ PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n'
' │ android)\n'
' │\n'
' └─child: _RenderColoredBox#00000\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=53.0, h=78.0)\n'
' │ size: Size(53.0, 78.0)\n'
' │ behavior: opaque\n'
' │\n'
' └─child: RenderPadding#00000\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=53.0, h=78.0)\n'
' │ size: Size(53.0, 78.0)\n'
' │ padding: EdgeInsets.all(7.0)\n'
' │\n'
' └─child: RenderPositionedBox#00000\n'
' │ parentData: offset=Offset(7.0, 7.0) (can use size)\n'
' │ constraints: BoxConstraints(w=39.0, h=64.0)\n'
' │ size: Size(39.0, 64.0)\n'
' │ alignment: Alignment.bottomRight\n'
' │ widthFactor: expand\n'
' │ heightFactor: expand\n'
' │\n'
' └─child: RenderConstrainedBox#00000 relayoutBoundary=up1\n'
' │ parentData: offset=Offset(14.0, 31.0) (can use size)\n'
' │ constraints: BoxConstraints(0.0<=w<=39.0, 0.0<=h<=64.0)\n'
' │ size: Size(25.0, 33.0)\n'
' │ additionalConstraints: BoxConstraints(w=25.0, h=33.0)\n'
' │\n'
' └─child: RenderDecoratedBox#00000\n'
' parentData: <none> (can use size)\n'
' constraints: BoxConstraints(w=25.0, h=33.0)\n'
' size: Size(25.0, 33.0)\n'
' decoration: BoxDecoration:\n'
' color: Color(0xffffff00)\n'
' configuration: ImageConfiguration(bundle:\n'
' PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n'
' android)\n',
),
);
});
testWidgets('has expected debug diagnostics', (WidgetTester tester) async {
await tester.pumpWidget(Align(
alignment: Alignment.topLeft,
child: container,
));
final RenderBox box = tester.renderObject(find.byType(Container));
expect(
// Using the redundant value to ensure the test is explicitly for
// debug diagnostics, regardless of any changes to the default value.
// ignore: avoid_redundant_argument_values
box.toStringDeep(minLevel: DiagnosticLevel.debug),
equalsIgnoringHashCodes(
'RenderPadding#00000 relayoutBoundary=up1\n'
' │ creator: Padding ← Container ← Align ← MediaQuery ←\n'
' │ _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ←\n'
' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← View ←\n'
' │ [root]\n'
' │ parentData: offset=Offset(0.0, 0.0) (can use size)\n'
' │ constraints: BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0)\n'
' │ size: Size(63.0, 88.0)\n'
' │ padding: EdgeInsets.all(5.0)\n'
' │\n'
' └─child: RenderConstrainedBox#00000 relayoutBoundary=up2\n'
' │ creator: ConstrainedBox ← Padding ← Container ← Align ←\n'
' │ MediaQuery ← _MediaQueryFromView ← _PipelineOwnerScope ←\n'
' │ _ViewScope ← _RawView-[_DeprecatedRawViewKey\n'
' │ TestFlutterView#00000] ← View ← [root]\n'
' │ parentData: offset=Offset(5.0, 5.0) (can use size)\n'
' │ constraints: BoxConstraints(0.0<=w<=790.0, 0.0<=h<=590.0)\n'
' │ size: Size(53.0, 78.0)\n'
' │ additionalConstraints: BoxConstraints(w=53.0, h=78.0)\n'
' │\n'
' └─child: RenderDecoratedBox#00000\n'
' │ creator: DecoratedBox ← ConstrainedBox ← Padding ← Container ←\n'
' │ Align ← MediaQuery ← _MediaQueryFromView ← _PipelineOwnerScope\n'
' │ ← _ViewScope ← _RawView-[_DeprecatedRawViewKey\n'
' │ TestFlutterView#00000] ← View ← [root]\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=53.0, h=78.0)\n'
' │ size: Size(53.0, 78.0)\n'
' │ decoration: BoxDecoration:\n'
' │ color: Color(0x7f0000ff)\n'
' │ configuration: ImageConfiguration(bundle:\n'
' │ PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n'
' │ android)\n'
' │\n'
' └─child: _RenderColoredBox#00000\n'
' │ creator: ColoredBox ← DecoratedBox ← ConstrainedBox ← Padding ←\n'
' │ Container ← Align ← MediaQuery ← _MediaQueryFromView ←\n'
' │ _PipelineOwnerScope ← _ViewScope ←\n'
' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← View ←\n'
' │ ⋯\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=53.0, h=78.0)\n'
' │ size: Size(53.0, 78.0)\n'
' │ behavior: opaque\n'
' │\n'
' └─child: RenderPadding#00000\n'
' │ creator: Padding ← ColoredBox ← DecoratedBox ← ConstrainedBox ←\n'
' │ Padding ← Container ← Align ← MediaQuery ← _MediaQueryFromView\n'
' │ ← _PipelineOwnerScope ← _ViewScope ←\n'
' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← ⋯\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=53.0, h=78.0)\n'
' │ size: Size(53.0, 78.0)\n'
' │ padding: EdgeInsets.all(7.0)\n'
' │\n'
' └─child: RenderPositionedBox#00000\n'
' │ creator: Align ← Padding ← ColoredBox ← DecoratedBox ←\n'
' │ ConstrainedBox ← Padding ← Container ← Align ← MediaQuery ←\n'
' │ _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ← ⋯\n'
' │ parentData: offset=Offset(7.0, 7.0) (can use size)\n'
' │ constraints: BoxConstraints(w=39.0, h=64.0)\n'
' │ size: Size(39.0, 64.0)\n'
' │ alignment: Alignment.bottomRight\n'
' │ widthFactor: expand\n'
' │ heightFactor: expand\n'
' │\n'
' └─child: RenderConstrainedBox#00000 relayoutBoundary=up1\n'
' │ creator: SizedBox ← Align ← Padding ← ColoredBox ← DecoratedBox ←\n'
' │ ConstrainedBox ← Padding ← Container ← Align ← MediaQuery ←\n'
' │ _MediaQueryFromView ← _PipelineOwnerScope ← ⋯\n'
' │ parentData: offset=Offset(14.0, 31.0) (can use size)\n'
' │ constraints: BoxConstraints(0.0<=w<=39.0, 0.0<=h<=64.0)\n'
' │ size: Size(25.0, 33.0)\n'
' │ additionalConstraints: BoxConstraints(w=25.0, h=33.0)\n'
' │\n'
' └─child: RenderDecoratedBox#00000\n'
' creator: DecoratedBox ← SizedBox ← Align ← Padding ← ColoredBox ←\n'
' DecoratedBox ← ConstrainedBox ← Padding ← Container ← Align ←\n'
' MediaQuery ← _MediaQueryFromView ← ⋯\n'
' parentData: <none> (can use size)\n'
' constraints: BoxConstraints(w=25.0, h=33.0)\n'
' size: Size(25.0, 33.0)\n'
' decoration: BoxDecoration:\n'
' color: Color(0xffffff00)\n'
' configuration: ImageConfiguration(bundle:\n'
' PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n'
' android)\n',
),
);
});
testWidgets('has expected fine diagnostics', (WidgetTester tester) async {
await tester.pumpWidget(Align(
alignment: Alignment.topLeft,
child: container,
));
final RenderBox box = tester.renderObject(find.byType(Container));
expect(
box.toStringDeep(minLevel: DiagnosticLevel.fine),
equalsIgnoringHashCodes(
'RenderPadding#00000 relayoutBoundary=up1\n'
' │ creator: Padding ← Container ← Align ← MediaQuery ←\n'
' │ _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ←\n'
' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← View ←\n'
' │ [root]\n'
' │ parentData: offset=Offset(0.0, 0.0) (can use size)\n'
' │ constraints: BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0)\n'
' │ layer: null\n'
' │ semantics node: null\n'
' │ size: Size(63.0, 88.0)\n'
' │ padding: EdgeInsets.all(5.0)\n'
' │ textDirection: null\n'
' │\n'
' └─child: RenderConstrainedBox#00000 relayoutBoundary=up2\n'
' │ creator: ConstrainedBox ← Padding ← Container ← Align ←\n'
' │ MediaQuery ← _MediaQueryFromView ← _PipelineOwnerScope ←\n'
' │ _ViewScope ← _RawView-[_DeprecatedRawViewKey\n'
' │ TestFlutterView#00000] ← View ← [root]\n'
' │ parentData: offset=Offset(5.0, 5.0) (can use size)\n'
' │ constraints: BoxConstraints(0.0<=w<=790.0, 0.0<=h<=590.0)\n'
' │ layer: null\n'
' │ semantics node: null\n'
' │ size: Size(53.0, 78.0)\n'
' │ additionalConstraints: BoxConstraints(w=53.0, h=78.0)\n'
' │\n'
' └─child: RenderDecoratedBox#00000\n'
' │ creator: DecoratedBox ← ConstrainedBox ← Padding ← Container ←\n'
' │ Align ← MediaQuery ← _MediaQueryFromView ← _PipelineOwnerScope\n'
' │ ← _ViewScope ← _RawView-[_DeprecatedRawViewKey\n'
' │ TestFlutterView#00000] ← View ← [root]\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=53.0, h=78.0)\n'
' │ layer: null\n'
' │ semantics node: null\n'
' │ size: Size(53.0, 78.0)\n'
' │ decoration: BoxDecoration:\n'
' │ color: Color(0x7f0000ff)\n'
' │ image: null\n'
' │ border: null\n'
' │ borderRadius: null\n'
' │ boxShadow: null\n'
' │ gradient: null\n'
' │ shape: rectangle\n'
' │ configuration: ImageConfiguration(bundle:\n'
' │ PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n'
' │ android)\n'
' │\n'
' └─child: _RenderColoredBox#00000\n'
' │ creator: ColoredBox ← DecoratedBox ← ConstrainedBox ← Padding ←\n'
' │ Container ← Align ← MediaQuery ← _MediaQueryFromView ←\n'
' │ _PipelineOwnerScope ← _ViewScope ←\n'
' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← View ←\n'
' │ ⋯\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=53.0, h=78.0)\n'
' │ layer: null\n'
' │ semantics node: null\n'
' │ size: Size(53.0, 78.0)\n'
' │ behavior: opaque\n'
' │\n'
' └─child: RenderPadding#00000\n'
' │ creator: Padding ← ColoredBox ← DecoratedBox ← ConstrainedBox ←\n'
' │ Padding ← Container ← Align ← MediaQuery ← _MediaQueryFromView\n'
' │ ← _PipelineOwnerScope ← _ViewScope ←\n'
' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← ⋯\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=53.0, h=78.0)\n'
' │ layer: null\n'
' │ semantics node: null\n'
' │ size: Size(53.0, 78.0)\n'
' │ padding: EdgeInsets.all(7.0)\n'
' │ textDirection: null\n'
' │\n'
' └─child: RenderPositionedBox#00000\n'
' │ creator: Align ← Padding ← ColoredBox ← DecoratedBox ←\n'
' │ ConstrainedBox ← Padding ← Container ← Align ← MediaQuery ←\n'
' │ _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ← ⋯\n'
' │ parentData: offset=Offset(7.0, 7.0) (can use size)\n'
' │ constraints: BoxConstraints(w=39.0, h=64.0)\n'
' │ layer: null\n'
' │ semantics node: null\n'
' │ size: Size(39.0, 64.0)\n'
' │ alignment: Alignment.bottomRight\n'
' │ textDirection: null\n'
' │ widthFactor: expand\n'
' │ heightFactor: expand\n'
' │\n'
' └─child: RenderConstrainedBox#00000 relayoutBoundary=up1\n'
' │ creator: SizedBox ← Align ← Padding ← ColoredBox ← DecoratedBox ←\n'
' │ ConstrainedBox ← Padding ← Container ← Align ← MediaQuery ←\n'
' │ _MediaQueryFromView ← _PipelineOwnerScope ← ⋯\n'
' │ parentData: offset=Offset(14.0, 31.0) (can use size)\n'
' │ constraints: BoxConstraints(0.0<=w<=39.0, 0.0<=h<=64.0)\n'
' │ layer: null\n'
' │ semantics node: null\n'
' │ size: Size(25.0, 33.0)\n'
' │ additionalConstraints: BoxConstraints(w=25.0, h=33.0)\n'
' │\n'
' └─child: RenderDecoratedBox#00000\n'
' creator: DecoratedBox ← SizedBox ← Align ← Padding ← ColoredBox ←\n'
' DecoratedBox ← ConstrainedBox ← Padding ← Container ← Align ←\n'
' MediaQuery ← _MediaQueryFromView ← ⋯\n'
' parentData: <none> (can use size)\n'
' constraints: BoxConstraints(w=25.0, h=33.0)\n'
' layer: null\n'
' semantics node: null\n'
' size: Size(25.0, 33.0)\n'
' decoration: BoxDecoration:\n'
' color: Color(0xffffff00)\n'
' image: null\n'
' border: null\n'
' borderRadius: null\n'
' boxShadow: null\n'
' gradient: null\n'
' shape: rectangle\n'
' configuration: ImageConfiguration(bundle:\n'
' PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n'
' android)\n'
),
);
});
testWidgets('has expected hidden diagnostics', (WidgetTester tester) async {
await tester.pumpWidget(Align(
alignment: Alignment.topLeft,
child: container,
));
final RenderBox box = tester.renderObject(find.byType(Container));
expect(
box.toStringDeep(minLevel: DiagnosticLevel.hidden),
equalsIgnoringHashCodes(
'RenderPadding#00000 relayoutBoundary=up1\n'
' │ needsCompositing: false\n'
' │ creator: Padding ← Container ← Align ← MediaQuery ←\n'
' │ _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ←\n'
' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← View ←\n'
' │ [root]\n'
' │ parentData: offset=Offset(0.0, 0.0) (can use size)\n'
' │ constraints: BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0)\n'
' │ layer: null\n'
' │ semantics node: null\n'
' │ isBlockingSemanticsOfPreviouslyPaintedNodes: false\n'
' │ isSemanticBoundary: false\n'
' │ size: Size(63.0, 88.0)\n'
' │ padding: EdgeInsets.all(5.0)\n'
' │ textDirection: null\n'
' │\n'
' └─child: RenderConstrainedBox#00000 relayoutBoundary=up2\n'
' │ needsCompositing: false\n'
' │ creator: ConstrainedBox ← Padding ← Container ← Align ←\n'
' │ MediaQuery ← _MediaQueryFromView ← _PipelineOwnerScope ←\n'
' │ _ViewScope ← _RawView-[_DeprecatedRawViewKey\n'
' │ TestFlutterView#00000] ← View ← [root]\n'
' │ parentData: offset=Offset(5.0, 5.0) (can use size)\n'
' │ constraints: BoxConstraints(0.0<=w<=790.0, 0.0<=h<=590.0)\n'
' │ layer: null\n'
' │ semantics node: null\n'
' │ isBlockingSemanticsOfPreviouslyPaintedNodes: false\n'
' │ isSemanticBoundary: false\n'
' │ size: Size(53.0, 78.0)\n'
' │ additionalConstraints: BoxConstraints(w=53.0, h=78.0)\n'
' │\n'
' └─child: RenderDecoratedBox#00000\n'
' │ needsCompositing: false\n'
' │ creator: DecoratedBox ← ConstrainedBox ← Padding ← Container ←\n'
' │ Align ← MediaQuery ← _MediaQueryFromView ← _PipelineOwnerScope\n'
' │ ← _ViewScope ← _RawView-[_DeprecatedRawViewKey\n'
' │ TestFlutterView#00000] ← View ← [root]\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=53.0, h=78.0)\n'
' │ layer: null\n'
' │ semantics node: null\n'
' │ isBlockingSemanticsOfPreviouslyPaintedNodes: false\n'
' │ isSemanticBoundary: false\n'
' │ size: Size(53.0, 78.0)\n'
' │ decoration: BoxDecoration:\n'
' │ color: Color(0x7f0000ff)\n'
' │ image: null\n'
' │ border: null\n'
' │ borderRadius: null\n'
' │ boxShadow: null\n'
' │ gradient: null\n'
' │ shape: rectangle\n'
' │ configuration: ImageConfiguration(bundle:\n'
' │ PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n'
' │ android)\n'
' │\n'
' └─child: _RenderColoredBox#00000\n'
' │ needsCompositing: false\n'
' │ creator: ColoredBox ← DecoratedBox ← ConstrainedBox ← Padding ←\n'
' │ Container ← Align ← MediaQuery ← _MediaQueryFromView ←\n'
' │ _PipelineOwnerScope ← _ViewScope ←\n'
' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← View ←\n'
' │ ⋯\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=53.0, h=78.0)\n'
' │ layer: null\n'
' │ semantics node: null\n'
' │ isBlockingSemanticsOfPreviouslyPaintedNodes: false\n'
' │ isSemanticBoundary: false\n'
' │ size: Size(53.0, 78.0)\n'
' │ behavior: opaque\n'
' │\n'
' └─child: RenderPadding#00000\n'
' │ needsCompositing: false\n'
' │ creator: Padding ← ColoredBox ← DecoratedBox ← ConstrainedBox ←\n'
' │ Padding ← Container ← Align ← MediaQuery ← _MediaQueryFromView\n'
' │ ← _PipelineOwnerScope ← _ViewScope ←\n'
' │ _RawView-[_DeprecatedRawViewKey TestFlutterView#00000] ← ⋯\n'
' │ parentData: <none> (can use size)\n'
' │ constraints: BoxConstraints(w=53.0, h=78.0)\n'
' │ layer: null\n'
' │ semantics node: null\n'
' │ isBlockingSemanticsOfPreviouslyPaintedNodes: false\n'
' │ isSemanticBoundary: false\n'
' │ size: Size(53.0, 78.0)\n'
' │ padding: EdgeInsets.all(7.0)\n'
' │ textDirection: null\n'
' │\n'
' └─child: RenderPositionedBox#00000\n'
' │ needsCompositing: false\n'
' │ creator: Align ← Padding ← ColoredBox ← DecoratedBox ←\n'
' │ ConstrainedBox ← Padding ← Container ← Align ← MediaQuery ←\n'
' │ _MediaQueryFromView ← _PipelineOwnerScope ← _ViewScope ← ⋯\n'
' │ parentData: offset=Offset(7.0, 7.0) (can use size)\n'
' │ constraints: BoxConstraints(w=39.0, h=64.0)\n'
' │ layer: null\n'
' │ semantics node: null\n'
' │ isBlockingSemanticsOfPreviouslyPaintedNodes: false\n'
' │ isSemanticBoundary: false\n'
' │ size: Size(39.0, 64.0)\n'
' │ alignment: Alignment.bottomRight\n'
' │ textDirection: null\n'
' │ widthFactor: expand\n'
' │ heightFactor: expand\n'
' │\n'
' └─child: RenderConstrainedBox#00000 relayoutBoundary=up1\n'
' │ needsCompositing: false\n'
' │ creator: SizedBox ← Align ← Padding ← ColoredBox ← DecoratedBox ←\n'
' │ ConstrainedBox ← Padding ← Container ← Align ← MediaQuery ←\n'
' │ _MediaQueryFromView ← _PipelineOwnerScope ← ⋯\n'
' │ parentData: offset=Offset(14.0, 31.0) (can use size)\n'
' │ constraints: BoxConstraints(0.0<=w<=39.0, 0.0<=h<=64.0)\n'
' │ layer: null\n'
' │ semantics node: null\n'
' │ isBlockingSemanticsOfPreviouslyPaintedNodes: false\n'
' │ isSemanticBoundary: false\n'
' │ size: Size(25.0, 33.0)\n'
' │ additionalConstraints: BoxConstraints(w=25.0, h=33.0)\n'
' │\n'
' └─child: RenderDecoratedBox#00000\n'
' needsCompositing: false\n'
' creator: DecoratedBox ← SizedBox ← Align ← Padding ← ColoredBox ←\n'
' DecoratedBox ← ConstrainedBox ← Padding ← Container ← Align ←\n'
' MediaQuery ← _MediaQueryFromView ← ⋯\n'
' parentData: <none> (can use size)\n'
' constraints: BoxConstraints(w=25.0, h=33.0)\n'
' layer: null\n'
' semantics node: null\n'
' isBlockingSemanticsOfPreviouslyPaintedNodes: false\n'
' isSemanticBoundary: false\n'
' size: Size(25.0, 33.0)\n'
' decoration: BoxDecoration:\n'
' color: Color(0xffffff00)\n'
' image: null\n'
' border: null\n'
' borderRadius: null\n'
' boxShadow: null\n'
' gradient: null\n'
' shape: rectangle\n'
' configuration: ImageConfiguration(bundle:\n'
' PlatformAssetBundle#00000(), devicePixelRatio: 3.0, platform:\n'
' android)\n'
),
);
});
testWidgets('painting error has expected diagnostics', (WidgetTester tester) async {
await tester.pumpWidget(Align(
alignment: Alignment.topLeft,
child: container,
));
final RenderBox decoratedBox = tester.renderObject(find.byType(DecoratedBox).last);
final PaintingContext context = _MockPaintingContext();
late FlutterError error;
try {
decoratedBox.paint(context, Offset.zero);
} on FlutterError catch (e) {
error = e;
}
expect(error, isNotNull);
expect(
error.toStringDeep(),
'FlutterError\n'
' BoxDecoration painter had mismatching save and restore calls.\n'
' Before painting the decoration, the canvas save count was 0.\n'
' After painting it, the canvas save count was 2. Every call to\n'
' save() or saveLayer() must be matched by a call to restore().\n'
' The decoration was:\n'
' BoxDecoration(color: Color(0xffffff00))\n'
' The painter was:\n'
' BoxPainter for BoxDecoration(color: Color(0xffffff00))\n',
);
});
});
});
testWidgets('Can be placed in an infinite box', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(children: <Widget>[Container()]),
),
);
});
testWidgets('Container transformAlignment', (WidgetTester tester) async {
final Key key = UniqueKey();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Stack(
children: <Widget>[
Positioned(
top: 100.0,
left: 100.0,
child: Container(
width: 100.0,
height: 100.0,
color: const Color(0xFF0000FF),
),
),
Positioned(
top: 100.0,
left: 100.0,
child: Container(
width: 100.0,
height: 100.0,
key: key,
transform: Matrix4.diagonal3Values(0.5, 0.5, 1.0),
transformAlignment: Alignment.centerRight,
child: Container(
color: const Color(0xFF00FFFF),
),
),
),
],
),
),
);
final Finder finder = find.byKey(key);
expect(tester.getSize(finder), equals(const Size(100, 100)));
expect(tester.getTopLeft(finder), equals(const Offset(100, 100)));
expect(tester.getTopRight(finder), equals(const Offset(200, 100)));
expect(tester.getBottomLeft(finder), equals(const Offset(100, 200)));
expect(tester.getBottomRight(finder), equals(const Offset(200, 200)));
});
testWidgets('giving clipBehaviour Clip.None, will not add a ClipPath to the tree', (WidgetTester tester) async {
await tester.pumpWidget(
Container(
decoration: const BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(1)),
),
child: const SizedBox(),
));
expect(
find.byType(ClipPath),
findsNothing,
);
});
testWidgets('giving clipBehaviour not a Clip.None, will add a ClipPath to the tree', (WidgetTester tester) async {
final Container container = Container(
clipBehavior: Clip.hardEdge,
decoration: const BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(1)),
),
child: const SizedBox(),
);
await tester.pumpWidget(container);
expect(
find.byType(ClipPath),
findsOneWidget,
);
});
testWidgets('getClipPath() works for lots of kinds of decorations', (WidgetTester tester) async {
Future<void> test(Decoration decoration) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.rtl,
child: Center(
child: SizedBox(
width: 100.0,
height: 100.0,
child: RepaintBoundary(
child: Container(
clipBehavior: Clip.hardEdge,
decoration: decoration,
child: ColoredBox(
color: Colors.yellow.withOpacity(0.5),
),
),
),
),
),
),
);
await expectLater(find.byType(Container), matchesGoldenFile('container_test.getClipPath.${decoration.runtimeType}.png'));
}
await test(const BoxDecoration());
await test(const UnderlineTabIndicator());
await test(const ShapeDecoration(shape: StadiumBorder()));
await test(const FlutterLogoDecoration());
});
testWidgets('Container is hittable only when having decorations', (WidgetTester tester) async {
bool tapped = false;
await tester.pumpWidget(GestureDetector(
onTap: () { tapped = true; },
child: Container(
decoration: const BoxDecoration(color: Colors.black),
),
));
await tester.tap(find.byType(Container));
expect(tapped, true);
tapped = false;
await tester.pumpWidget(GestureDetector(
onTap: () { tapped = true; },
child: Container(
foregroundDecoration: const BoxDecoration(color: Colors.black),
),
));
await tester.tap(find.byType(Container));
expect(tapped, true);
tapped = false;
await tester.pumpWidget(GestureDetector(
onTap: () { tapped = true; },
child: Container(
color: Colors.black,
),
));
await tester.tap(find.byType(Container));
expect(tapped, true);
tapped = false;
// Everything but color or decorations
await tester.pumpWidget(GestureDetector(
onTap: () { tapped = true; },
child: Center(
child: Container(
alignment: Alignment.bottomRight,
padding: const EdgeInsets.all(2),
width: 50,
height: 50,
margin: const EdgeInsets.all(2),
transform: Matrix4.rotationZ(1),
),
),
));
await tester.tap(find.byType(Container), warnIfMissed: false);
expect(tapped, false);
});
testWidgets('Container discards alignment when the child parameter is null and constraints is not Tight', (WidgetTester tester) async {
await tester.pumpWidget(
Container(
decoration: const BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(1)),
),
alignment: Alignment.centerLeft
));
expect(
find.byType(Align),
findsNothing,
);
});
testWidgets('using clipBehaviour and shadow, should not clip the shadow', (WidgetTester tester) async {
final Container container = Container(
clipBehavior: Clip.hardEdge,
decoration: const BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(30)),
color: Colors.red,
boxShadow: <BoxShadow>[
BoxShadow(
color: Colors.blue,
spreadRadius: 10,
blurRadius: 20.0,
),
],
),
child: const SizedBox(width: 50, height: 50),
);
await tester.pumpWidget(
RepaintBoundary(
child: Padding(
padding: const EdgeInsets.all(30.0),
child: container,
),
),
);
await expectLater(
find.byType(RepaintBoundary),
matchesGoldenFile('container.clipBehaviour.with.shadow.png'),
);
});
}
class _MockPaintingContext extends Fake implements PaintingContext {
@override
final Canvas canvas = _MockCanvas();
}
class _MockCanvas extends Fake implements Canvas {
int saveCount = 0;
@override
int getSaveCount() {
return saveCount++;
}
@override
void drawRect(Rect rect, Paint paint) { }
}
| flutter/packages/flutter/test/widgets/container_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/container_test.dart",
"repo_id": "flutter",
"token_count": 19891
} | 686 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'package:flutter/gestures.dart' show DragStartBehavior;
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
const DismissDirection defaultDismissDirection = DismissDirection.horizontal;
const double crossAxisEndOffset = 0.5;
bool reportedDismissUpdateReached = false;
bool reportedDismissUpdatePreviousReached = false;
double reportedDismissUpdateProgress = 0.0;
late DismissDirection reportedDismissUpdateReachedDirection;
DismissDirection reportedDismissDirection = DismissDirection.horizontal;
List<int> dismissedItems = <int>[];
Widget buildTest({
Axis scrollDirection = Axis.vertical,
DismissDirection dismissDirection = defaultDismissDirection,
double? startToEndThreshold,
TextDirection textDirection = TextDirection.ltr,
Future<bool?> Function(BuildContext context, DismissDirection direction)? confirmDismiss,
ScrollController? controller,
ScrollPhysics? scrollPhysics,
Widget? background,
}) {
return Directionality(
textDirection: textDirection,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
Widget buildDismissibleItem(int item) {
return Dismissible(
dragStartBehavior: DragStartBehavior.down,
key: ValueKey<int>(item),
direction: dismissDirection,
confirmDismiss: confirmDismiss == null ? null : (DismissDirection direction) {
return confirmDismiss(context, direction);
},
onDismissed: (DismissDirection direction) {
setState(() {
reportedDismissDirection = direction;
expect(dismissedItems.contains(item), isFalse);
dismissedItems.add(item);
});
},
onResize: () {
expect(dismissedItems.contains(item), isFalse);
},
onUpdate: (DismissUpdateDetails details) {
reportedDismissUpdateReachedDirection = details.direction;
reportedDismissUpdateReached = details.reached;
reportedDismissUpdatePreviousReached = details.previousReached;
reportedDismissUpdateProgress = details.progress;
},
background: background,
dismissThresholds: startToEndThreshold == null
? <DismissDirection, double>{}
: <DismissDirection, double>{DismissDirection.startToEnd: startToEndThreshold},
crossAxisEndOffset: crossAxisEndOffset,
child: SizedBox(
width: 100.0,
height: 100.0,
child: Text(item.toString()),
),
);
}
return Container(
padding: const EdgeInsets.all(10.0),
child: ListView(
physics: scrollPhysics,
controller: controller,
dragStartBehavior: DragStartBehavior.down,
scrollDirection: scrollDirection,
itemExtent: 100.0,
children: <int>[0, 1, 2, 3, 4, 5, 6, 7, 8]
.where((int i) => !dismissedItems.contains(i))
.map<Widget>(buildDismissibleItem).toList(),
),
);
},
),
);
}
typedef DismissMethod = Future<void> Function(WidgetTester tester, Finder finder, { required AxisDirection gestureDirection });
Future<void> dismissElement(WidgetTester tester, Finder finder, { required AxisDirection gestureDirection }) async {
Offset downLocation;
Offset upLocation;
switch (gestureDirection) {
case AxisDirection.left:
// getTopRight() returns a point that's just beyond itemWidget's right
// edge and outside the Dismissible event listener's bounds.
downLocation = tester.getTopRight(finder) + const Offset(-0.1, 0.0);
upLocation = tester.getTopLeft(finder) + const Offset(-0.1, 0.0);
case AxisDirection.right:
// we do the same thing here to keep the test symmetric
downLocation = tester.getTopLeft(finder) + const Offset(0.1, 0.0);
upLocation = tester.getTopRight(finder) + const Offset(0.1, 0.0);
case AxisDirection.up:
// getBottomLeft() returns a point that's just below itemWidget's bottom
// edge and outside the Dismissible event listener's bounds.
downLocation = tester.getBottomLeft(finder) + const Offset(0.0, -0.1);
upLocation = tester.getTopLeft(finder) + const Offset(0.0, -0.1);
case AxisDirection.down:
// again with doing the same here for symmetry
downLocation = tester.getTopLeft(finder) + const Offset(0.1, 0.0);
upLocation = tester.getBottomLeft(finder) + const Offset(0.1, 0.0);
}
final TestGesture gesture = await tester.startGesture(downLocation);
await gesture.moveTo(upLocation);
await gesture.up();
}
Future<void> dragElement(WidgetTester tester, Finder finder, { required AxisDirection gestureDirection, required double amount }) async {
final Offset delta = switch (gestureDirection) {
AxisDirection.left => Offset(-amount, 0.0),
AxisDirection.right => Offset(amount, 0.0),
AxisDirection.up => Offset(0.0, -amount),
AxisDirection.down => Offset(0.0, amount),
};
await tester.drag(finder, delta);
}
Future<void> flingElement(WidgetTester tester, Finder finder, { required AxisDirection gestureDirection, double initialOffsetFactor = 0.0 }) async {
final Offset delta = switch (gestureDirection) {
AxisDirection.left => const Offset(-300, 0.0),
AxisDirection.right => const Offset(300, 0.0),
AxisDirection.up => const Offset(0.0, -300),
AxisDirection.down => const Offset(0.0, 300),
};
await tester.fling(finder, delta, 1000.0, initialOffset: delta * initialOffsetFactor);
}
Future<void> flingElementFromZero(WidgetTester tester, Finder finder, { required AxisDirection gestureDirection }) async {
// This is a special case where we drag in one direction, then fling back so
// that at the point of release, we're at exactly the point at which we
// started, but with velocity. This is needed to check a boundary condition
// in the flinging behavior.
await flingElement(tester, finder, gestureDirection: gestureDirection, initialOffsetFactor: -1.0);
}
Future<void> dismissItem(
WidgetTester tester,
int item, {
required AxisDirection gestureDirection,
DismissMethod mechanism = dismissElement,
}) async {
final Finder itemFinder = find.text(item.toString());
expect(itemFinder, findsOneWidget);
await mechanism(tester, itemFinder, gestureDirection: gestureDirection);
await tester.pumpAndSettle();
}
Future<void> dragItem(
WidgetTester tester,
int item, {
required AxisDirection gestureDirection,
required double amount,
}) async {
final Finder itemFinder = find.text(item.toString());
expect(itemFinder, findsOneWidget);
await dragElement(tester, itemFinder, gestureDirection: gestureDirection, amount: amount);
await tester.pump();
}
Future<void> checkFlingItemBeforeMovementEnd(
WidgetTester tester,
int item, {
required AxisDirection gestureDirection,
DismissMethod mechanism = rollbackElement,
}) async {
final Finder itemFinder = find.text(item.toString());
expect(itemFinder, findsOneWidget);
await mechanism(tester, itemFinder, gestureDirection: gestureDirection);
await tester.pump(); // start the slide
await tester.pump(const Duration(milliseconds: 100));
}
Future<void> checkFlingItemAfterMovement(
WidgetTester tester,
int item, {
required AxisDirection gestureDirection,
DismissMethod mechanism = rollbackElement,
}) async {
final Finder itemFinder = find.text(item.toString());
expect(itemFinder, findsOneWidget);
await mechanism(tester, itemFinder, gestureDirection: gestureDirection);
await tester.pump(); // start the slide
await tester.pump(const Duration(milliseconds: 300));
}
Future<void> rollbackElement(WidgetTester tester, Finder finder, { required AxisDirection gestureDirection, double initialOffsetFactor = 0.0 }) async {
final Offset delta = switch (gestureDirection) {
AxisDirection.left => const Offset(-30.0, 0.0),
AxisDirection.right => const Offset(30.0, 0.0),
AxisDirection.up => const Offset(0.0, -30.0),
AxisDirection.down => const Offset(0.0, 30.0),
};
await tester.fling(finder, delta, 1000.0, initialOffset: delta * initialOffsetFactor);
}
class Test1215DismissibleWidget extends StatelessWidget {
const Test1215DismissibleWidget(this.text, { super.key });
final String text;
@override
Widget build(BuildContext context) {
return Dismissible(
dragStartBehavior: DragStartBehavior.down,
key: ObjectKey(text),
child: AspectRatio(
aspectRatio: 1.0,
child: Text(text),
),
);
}
}
void main() {
setUp(() {
// Reset "results" variables.
reportedDismissDirection = defaultDismissDirection;
dismissedItems = <int>[];
});
testWidgets('Horizontal drag triggers dismiss scrollDirection=vertical', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(),
);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.right);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
expect(reportedDismissDirection, DismissDirection.startToEnd);
await dismissItem(tester, 1, gestureDirection: AxisDirection.left);
expect(find.text('1'), findsNothing);
expect(dismissedItems, equals(<int>[0, 1]));
expect(reportedDismissDirection, DismissDirection.endToStart);
});
testWidgets('Horizontal fling triggers dismiss scrollDirection=vertical', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(),
);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.right, mechanism: flingElement);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
expect(reportedDismissDirection, DismissDirection.startToEnd);
await dismissItem(tester, 1, gestureDirection: AxisDirection.left, mechanism: flingElement);
expect(find.text('1'), findsNothing);
expect(dismissedItems, equals(<int>[0, 1]));
expect(reportedDismissDirection, DismissDirection.endToStart);
});
testWidgets('Horizontal fling does not trigger at zero offset, but does otherwise', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(
startToEndThreshold: 0.95,
),
);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.right, mechanism: flingElementFromZero);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, equals(<int>[]));
await dismissItem(tester, 0, gestureDirection: AxisDirection.left, mechanism: flingElementFromZero);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, equals(<int>[]));
await dismissItem(tester, 0, gestureDirection: AxisDirection.right, mechanism: flingElement);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
expect(reportedDismissDirection, DismissDirection.startToEnd);
await dismissItem(tester, 1, gestureDirection: AxisDirection.left, mechanism: flingElement);
expect(find.text('1'), findsNothing);
expect(dismissedItems, equals(<int>[0, 1]));
expect(reportedDismissDirection, DismissDirection.endToStart);
});
testWidgets('Vertical drag triggers dismiss scrollDirection=horizontal', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(
scrollDirection: Axis.horizontal,
dismissDirection: DismissDirection.vertical,
),
);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.up);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
expect(reportedDismissDirection, DismissDirection.up);
await dismissItem(tester, 1, gestureDirection: AxisDirection.down);
expect(find.text('1'), findsNothing);
expect(dismissedItems, equals(<int>[0, 1]));
expect(reportedDismissDirection, DismissDirection.down);
});
testWidgets('drag-left with DismissDirection.endToStart triggers dismiss (LTR)', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(
dismissDirection: DismissDirection.endToStart,
),
);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.right);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 1, gestureDirection: AxisDirection.right);
await dismissItem(tester, 0, gestureDirection: AxisDirection.left);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
await dismissItem(tester, 1, gestureDirection: AxisDirection.left);
});
testWidgets('drag-right with DismissDirection.startToEnd triggers dismiss (LTR)', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(
dismissDirection: DismissDirection.startToEnd,
),
);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.left);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.right);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
});
testWidgets('drag-right with DismissDirection.endToStart triggers dismiss (RTL)', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(
textDirection: TextDirection.rtl,
dismissDirection: DismissDirection.endToStart,
),
);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.left);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.right);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
});
testWidgets('drag-left with DismissDirection.startToEnd triggers dismiss (RTL)', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(
textDirection: TextDirection.rtl,
dismissDirection: DismissDirection.startToEnd,
),
);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.right);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 1, gestureDirection: AxisDirection.right);
await dismissItem(tester, 0, gestureDirection: AxisDirection.left);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
await dismissItem(tester, 1, gestureDirection: AxisDirection.left);
});
testWidgets('fling-left with DismissDirection.endToStart triggers dismiss (LTR)', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(
dismissDirection: DismissDirection.endToStart,
),
);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.right);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 1, gestureDirection: AxisDirection.right);
await dismissItem(tester, 0, gestureDirection: AxisDirection.left);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
await dismissItem(tester, 1, gestureDirection: AxisDirection.left);
});
testWidgets('fling-right with DismissDirection.startToEnd triggers dismiss (LTR)', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(
dismissDirection: DismissDirection.startToEnd,
),
);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, mechanism: flingElement, gestureDirection: AxisDirection.left);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, mechanism: flingElement, gestureDirection: AxisDirection.right);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
});
testWidgets('fling-right with DismissDirection.endToStart triggers dismiss (RTL)', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(
textDirection: TextDirection.rtl,
dismissDirection: DismissDirection.endToStart,
),
);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, mechanism: flingElement, gestureDirection: AxisDirection.left);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, mechanism: flingElement, gestureDirection: AxisDirection.right);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
});
testWidgets('fling-left with DismissDirection.startToEnd triggers dismiss (RTL)', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(
textDirection: TextDirection.rtl,
dismissDirection: DismissDirection.startToEnd,
),
);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, mechanism: flingElement, gestureDirection: AxisDirection.right);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 1, mechanism: flingElement, gestureDirection: AxisDirection.right);
await dismissItem(tester, 0, mechanism: flingElement, gestureDirection: AxisDirection.left);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
await dismissItem(tester, 1, mechanism: flingElement, gestureDirection: AxisDirection.left);
});
testWidgets('drag-up with DismissDirection.up triggers dismiss', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(
scrollDirection: Axis.horizontal,
dismissDirection: DismissDirection.up,
),
);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.down);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.up);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
});
testWidgets('drag-down with DismissDirection.down triggers dismiss', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(
scrollDirection: Axis.horizontal,
dismissDirection: DismissDirection.down,
),
);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.up);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.down);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
});
testWidgets('fling-up with DismissDirection.up triggers dismiss', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(
scrollDirection: Axis.horizontal,
dismissDirection: DismissDirection.up,
),
);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, mechanism: flingElement, gestureDirection: AxisDirection.down);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, mechanism: flingElement, gestureDirection: AxisDirection.up);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
});
testWidgets('fling-down with DismissDirection.down triggers dismiss', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(
scrollDirection: Axis.horizontal,
dismissDirection: DismissDirection.down,
),
);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, mechanism: flingElement, gestureDirection: AxisDirection.up);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, mechanism: flingElement, gestureDirection: AxisDirection.down);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
});
testWidgets('drag-left has no effect on dismissible with a high dismiss threshold', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(
startToEndThreshold: 1.0,
),
);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.right);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.left);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
});
testWidgets('fling-left has no effect on dismissible with a high dismiss threshold', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(
startToEndThreshold: 1.0,
),
);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, mechanism: flingElement, gestureDirection: AxisDirection.right);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, mechanism: flingElement, gestureDirection: AxisDirection.left);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
});
// This is a regression test for an fn2 bug where dragging a card caused an
// assert "'!_disqualifiedFromEverAppearingAgain' is not true". The old URL
// was https://github.com/domokit/sky_engine/issues/1068 but that issue is 404
// now since we migrated to the new repo. The bug was fixed by
// https://github.com/flutter/engine/pull/1134 at the time, and later made
// irrelevant by fn3, but just in case...
testWidgets('Verify that drag-move events do not assert', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(
scrollDirection: Axis.horizontal,
dismissDirection: DismissDirection.down,
),
);
final Offset location = tester.getTopLeft(find.text('0'));
const Offset offset = Offset(0.0, 5.0);
final TestGesture gesture = await tester.startGesture(location, pointer: 5);
await gesture.moveBy(offset);
await tester.pumpWidget(buildTest());
await gesture.moveBy(offset);
await tester.pumpWidget(buildTest());
await gesture.moveBy(offset);
await tester.pumpWidget(buildTest());
await gesture.moveBy(offset);
await tester.pumpWidget(buildTest());
await gesture.up();
});
// This one is for a case where dismissing a widget above a previously
// dismissed widget threw an exception, which was documented at the
// now-obsolete URL https://github.com/flutter/engine/issues/1215 (the URL
// died in the migration to the new repo). Don't copy this test; it doesn't
// actually remove the dismissed widget, which is a violation of the
// Dismissible contract. This is not an example of good practice.
testWidgets('dismissing bottom then top (smoketest)', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 100.0,
height: 1000.0,
child: Column(
children: <Widget>[
Test1215DismissibleWidget('1'),
Test1215DismissibleWidget('2'),
],
),
),
),
),
);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
await dismissElement(tester, find.text('2'), gestureDirection: AxisDirection.right);
await tester.pump(); // start the slide away
await tester.pump(const Duration(seconds: 1)); // finish the slide away
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsNothing);
await dismissElement(tester, find.text('1'), gestureDirection: AxisDirection.right);
await tester.pump(); // start the slide away
await tester.pump(const Duration(seconds: 1)); // finish the slide away (at which point the child is no longer included in the tree)
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
});
testWidgets('Dismissible starts from the full size when collapsing', (WidgetTester tester) async {
await tester.pumpWidget(
buildTest(
background: const Text('background'),
),
);
expect(dismissedItems, isEmpty);
final Finder itemFinder = find.text('0');
expect(itemFinder, findsOneWidget);
await dismissElement(tester, itemFinder, gestureDirection: AxisDirection.right);
await tester.pump();
expect(find.text('background'), findsOneWidget); // The other four have been culled.
final RenderBox backgroundBox = tester.firstRenderObject(find.text('background'));
expect(backgroundBox.size.height, equals(100.0));
});
testWidgets('Checking fling item before movementDuration completes', (WidgetTester tester) async {
await tester.pumpWidget(buildTest());
expect(dismissedItems, isEmpty);
await checkFlingItemBeforeMovementEnd(tester, 0, gestureDirection: AxisDirection.left, mechanism: flingElement);
expect(find.text('0'), findsOneWidget);
await checkFlingItemBeforeMovementEnd(tester, 1, gestureDirection: AxisDirection.right, mechanism: flingElement);
expect(find.text('1'), findsOneWidget);
});
testWidgets('Checking fling item after movementDuration', (WidgetTester tester) async {
await tester.pumpWidget(buildTest());
expect(dismissedItems, isEmpty);
await checkFlingItemAfterMovement(tester, 1, gestureDirection: AxisDirection.left, mechanism: flingElement);
expect(find.text('1'), findsNothing);
await checkFlingItemAfterMovement(tester, 0, gestureDirection: AxisDirection.right, mechanism: flingElement);
expect(find.text('0'), findsNothing);
});
testWidgets('Horizontal fling less than threshold', (WidgetTester tester) async {
await tester.pumpWidget(buildTest(scrollDirection: Axis.horizontal));
expect(dismissedItems, isEmpty);
await checkFlingItemAfterMovement(tester, 0, gestureDirection: AxisDirection.left);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await checkFlingItemAfterMovement(tester, 1, gestureDirection: AxisDirection.right);
expect(find.text('1'), findsOneWidget);
expect(dismissedItems, isEmpty);
});
testWidgets('Vertical fling less than threshold', (WidgetTester tester) async {
await tester.pumpWidget(buildTest());
expect(dismissedItems, isEmpty);
await checkFlingItemAfterMovement(tester, 0, gestureDirection: AxisDirection.left);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await checkFlingItemAfterMovement(tester, 1, gestureDirection: AxisDirection.right);
expect(find.text('1'), findsOneWidget);
expect(dismissedItems, isEmpty);
});
testWidgets('confirmDismiss returns values: true, false, null', (WidgetTester tester) async {
late DismissDirection confirmDismissDirection;
Widget buildFrame(bool? confirmDismissValue) {
return buildTest(
confirmDismiss: (BuildContext context, DismissDirection dismissDirection) {
confirmDismissDirection = dismissDirection;
return Future<bool?>.value(confirmDismissValue);
},
);
}
// Dismiss is confirmed IFF confirmDismiss() returns true.
await tester.pumpWidget(buildFrame(true));
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.right, mechanism: flingElement);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
expect(reportedDismissDirection, DismissDirection.startToEnd);
expect(confirmDismissDirection, DismissDirection.startToEnd);
await dismissItem(tester, 1, gestureDirection: AxisDirection.left, mechanism: flingElement);
expect(find.text('1'), findsNothing);
expect(dismissedItems, equals(<int>[0, 1]));
expect(reportedDismissDirection, DismissDirection.endToStart);
expect(confirmDismissDirection, DismissDirection.endToStart);
// Dismiss is not confirmed if confirmDismiss() returns false
dismissedItems = <int>[];
await tester.pumpWidget(buildFrame(false));
await dismissItem(tester, 0, gestureDirection: AxisDirection.right, mechanism: flingElement);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
expect(confirmDismissDirection, DismissDirection.startToEnd);
await dismissItem(tester, 1, gestureDirection: AxisDirection.left, mechanism: flingElement);
expect(find.text('1'), findsOneWidget);
expect(dismissedItems, isEmpty);
expect(confirmDismissDirection, DismissDirection.endToStart);
// Dismiss is not confirmed if confirmDismiss() returns null
dismissedItems = <int>[];
await tester.pumpWidget(buildFrame(null));
await dismissItem(tester, 0, gestureDirection: AxisDirection.right, mechanism: flingElement);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
expect(confirmDismissDirection, DismissDirection.startToEnd);
await dismissItem(tester, 1, gestureDirection: AxisDirection.left, mechanism: flingElement);
expect(find.text('1'), findsOneWidget);
expect(dismissedItems, isEmpty);
expect(confirmDismissDirection, DismissDirection.endToStart);
});
testWidgets('Pending confirmDismiss does not cause errors', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/54990
late Completer<bool?> completer;
Widget buildFrame() {
completer = Completer<bool?>();
return buildTest(
confirmDismiss: (BuildContext context, DismissDirection dismissDirection) {
return completer.future;
},
);
}
// false for _handleDragEnd - when dragged to the end and released
await tester.pumpWidget(buildFrame());
await dismissItem(tester, 0, gestureDirection: AxisDirection.right);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await tester.pumpWidget(const SizedBox());
completer.complete(false);
await tester.pump();
// true for _handleDragEnd - when dragged to the end and released
await tester.pumpWidget(buildFrame());
await dismissItem(tester, 0, gestureDirection: AxisDirection.right);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await tester.pumpWidget(const SizedBox());
completer.complete(true);
await tester.pump();
// false for _handleDismissStatusChanged - when fling reaches the end
await tester.pumpWidget(buildFrame());
await dismissItem(tester, 0, gestureDirection: AxisDirection.right, mechanism: flingElement);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await tester.pumpWidget(const SizedBox());
completer.complete(false);
await tester.pump();
// true for _handleDismissStatusChanged - when fling reaches the end
await tester.pumpWidget(buildFrame());
await dismissItem(tester, 0, gestureDirection: AxisDirection.right, mechanism: flingElement);
expect(find.text('0'), findsOneWidget);
expect(dismissedItems, isEmpty);
await tester.pumpWidget(const SizedBox());
completer.complete(true);
await tester.pump();
});
testWidgets('Dismissible cannot be dragged with pending confirmDismiss', (WidgetTester tester) async {
final Completer<bool?> completer = Completer<bool?>();
await tester.pumpWidget(
buildTest(
confirmDismiss: (BuildContext context, DismissDirection dismissDirection) {
return completer.future;
},
),
);
// Trigger confirmDismiss call.
await dismissItem(tester, 0, gestureDirection: AxisDirection.right);
final Offset position = tester.getTopLeft(find.text('0'));
// Try to move and verify it has not moved.
Offset dragAt = tester.getTopLeft(find.text('0'));
dragAt = Offset(100.0, dragAt.dy);
final TestGesture gesture = await tester.startGesture(dragAt);
await gesture.moveTo(dragAt + const Offset(100.0, 0.0));
await gesture.up();
await tester.pump();
expect(tester.getTopLeft(find.text('0')), position);
});
testWidgets('Drag to end and release - items does not get stuck if confirmDismiss returns false', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/87556
final Completer<bool?> completer = Completer<bool?>();
await tester.pumpWidget(
buildTest(
confirmDismiss: (BuildContext context, DismissDirection dismissDirection) {
return completer.future;
},
),
);
final Offset position = tester.getTopLeft(find.text('0'));
await dismissItem(tester, 0, gestureDirection: AxisDirection.right);
completer.complete(false);
await tester.pumpAndSettle();
expect(tester.getTopLeft(find.text('0')), position);
});
testWidgets('Dismissible with null resizeDuration calls onDismissed immediately', (WidgetTester tester) async {
bool resized = false;
bool dismissed = false;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Dismissible(
dragStartBehavior: DragStartBehavior.down,
key: UniqueKey(),
resizeDuration: null,
onDismissed: (DismissDirection direction) {
dismissed = true;
},
onResize: () {
resized = true;
},
child: const SizedBox(
width: 100.0,
height: 100.0,
child: Text('0'),
),
),
),
);
await dismissElement(tester, find.text('0'), gestureDirection: AxisDirection.right);
await tester.pump();
expect(dismissed, true);
expect(resized, false);
});
testWidgets('setState that does not remove the Dismissible from tree should throw Error', (WidgetTester tester) async {
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
return ListView(
dragStartBehavior: DragStartBehavior.down,
itemExtent: 100.0,
children: <Widget>[
Dismissible(
dragStartBehavior: DragStartBehavior.down,
key: const ValueKey<int>(1),
onDismissed: (DismissDirection direction) {
setState(() {
reportedDismissDirection = direction;
expect(dismissedItems.contains(1), isFalse);
dismissedItems.add(1);
});
},
crossAxisEndOffset: crossAxisEndOffset,
child: SizedBox(
width: 100.0,
height: 100.0,
child: Text(1.toString()),
),
),
],
);
},
),
));
expect(dismissedItems, isEmpty);
await dismissItem(tester, 1, gestureDirection: AxisDirection.right);
expect(dismissedItems, equals(<int>[1]));
final dynamic exception = tester.takeException();
expect(exception, isNotNull);
expect(exception, isFlutterError);
final FlutterError error = exception as FlutterError;
expect(error.diagnostics.last.level, DiagnosticLevel.hint);
expect(
error.diagnostics.last.toStringDeep(),
equalsIgnoringHashCodes(
'Make sure to implement the onDismissed handler and to immediately\n'
'remove the Dismissible widget from the application once that\n'
'handler has fired.\n',
),
);
expect(
error.toStringDeep(),
'FlutterError\n'
' A dismissed Dismissible widget is still part of the tree.\n'
' Make sure to implement the onDismissed handler and to immediately\n'
' remove the Dismissible widget from the application once that\n'
' handler has fired.\n',
);
});
testWidgets('Dismissible.behavior should behave correctly during hit testing', (WidgetTester tester) async {
bool didReceivePointerDown = false;
Widget buildStack({required Widget child}) {
return Directionality(
textDirection: TextDirection.ltr,
child: Stack(
children: <Widget>[
Listener(
onPointerDown: (_) {
didReceivePointerDown = true;
},
child: Container(
width: 100.0,
height: 100.0,
color: const Color(0xFF00FF00),
),
),
child,
],
),
);
}
await tester.pumpWidget(
buildStack(
child: const Dismissible(
key: ValueKey<int>(1),
child: SizedBox(
width: 100.0,
height: 100.0,
),
),
),
);
await tester.tapAt(const Offset(10.0, 10.0));
expect(didReceivePointerDown, isFalse);
Future<void> pumpWidgetTree(HitTestBehavior behavior) {
return tester.pumpWidget(
buildStack(
child: Dismissible(
key: const ValueKey<int>(1),
behavior: behavior,
child: const SizedBox(
width: 100.0,
height: 100.0,
),
),
),
);
}
didReceivePointerDown = false;
await pumpWidgetTree(HitTestBehavior.deferToChild);
await tester.tapAt(const Offset(10.0, 10.0));
expect(didReceivePointerDown, isTrue);
didReceivePointerDown = false;
await pumpWidgetTree(HitTestBehavior.opaque);
await tester.tapAt(const Offset(10.0, 10.0));
expect(didReceivePointerDown, isFalse);
didReceivePointerDown = false;
await pumpWidgetTree(HitTestBehavior.translucent);
await tester.tapAt(const Offset(10.0, 10.0));
expect(didReceivePointerDown, isTrue);
});
testWidgets('DismissDirection.none does not trigger dismiss', (WidgetTester tester) async {
await tester.pumpWidget(buildTest(
dismissDirection: DismissDirection.none,
scrollPhysics: const NeverScrollableScrollPhysics(),
));
expect(dismissedItems, isEmpty);
await dismissItem(tester, 0, gestureDirection: AxisDirection.left);
await dismissItem(tester, 0, gestureDirection: AxisDirection.right);
await dismissItem(tester, 0, gestureDirection: AxisDirection.up);
await dismissItem(tester, 0, gestureDirection: AxisDirection.down);
expect(find.text('0'), findsOneWidget);
});
testWidgets('DismissDirection.none does not prevent scrolling', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
await tester.pumpWidget(
buildTest(
controller: controller,
dismissDirection: DismissDirection.none,
),
);
expect(dismissedItems, isEmpty);
expect(controller.offset, 0.0);
await dismissItem(tester, 0, gestureDirection: AxisDirection.left);
expect(controller.offset, 0.0);
await dismissItem(tester, 0, gestureDirection: AxisDirection.right);
expect(controller.offset, 0.0);
await dismissItem(tester, 0, gestureDirection: AxisDirection.down);
expect(controller.offset, 0.0);
await dismissItem(tester, 0, gestureDirection: AxisDirection.up);
expect(controller.offset, 100.0);
controller.dispose();
});
testWidgets('onUpdate', (WidgetTester tester) async {
await tester.pumpWidget(buildTest(
scrollDirection: Axis.horizontal,
));
expect(dismissedItems, isEmpty);
// Unsuccessful dismiss, fractional progress reported
await dragItem(tester, 0, gestureDirection: AxisDirection.right, amount: 20);
expect(reportedDismissUpdateProgress, 0.2);
// Successful dismiss therefore threshold has been reached
await dismissItem(tester, 0, mechanism: flingElement, gestureDirection: AxisDirection.left);
expect(find.text('0'), findsNothing);
expect(dismissedItems, equals(<int>[0]));
expect(reportedDismissUpdateReachedDirection, DismissDirection.endToStart);
expect(reportedDismissUpdateReached, true);
expect(reportedDismissUpdatePreviousReached, true);
expect(reportedDismissUpdateProgress, 1.0);
// Unsuccessful dismiss, threshold has not been reached
await checkFlingItemAfterMovement(tester, 1, gestureDirection: AxisDirection.right);
expect(find.text('1'), findsOneWidget);
expect(dismissedItems, equals(<int>[0]));
expect(reportedDismissUpdateReachedDirection, DismissDirection.startToEnd);
expect(reportedDismissUpdateReached, false);
expect(reportedDismissUpdatePreviousReached, false);
expect(reportedDismissUpdateProgress, 0.0);
// Another successful dismiss from another direction
await dismissItem(tester, 1, mechanism: flingElement, gestureDirection: AxisDirection.right);
expect(find.text('1'), findsNothing);
expect(dismissedItems, equals(<int>[0, 1]));
expect(reportedDismissUpdateReachedDirection, DismissDirection.startToEnd);
expect(reportedDismissUpdateReached, true);
expect(reportedDismissUpdatePreviousReached, true);
expect(reportedDismissUpdateProgress, 1.0);
await tester.pumpWidget(buildTest(
scrollDirection: Axis.horizontal,
confirmDismiss: (BuildContext context, DismissDirection dismissDirection) {
return Future<bool>.value(false);
},
));
// Threshold has been reached but dismiss was not confirmed
await dismissItem(tester, 2, mechanism: flingElement, gestureDirection: AxisDirection.right);
expect(find.text('2'), findsOneWidget);
expect(dismissedItems, equals(<int>[0, 1]));
expect(reportedDismissUpdateReachedDirection, DismissDirection.startToEnd);
expect(reportedDismissUpdateReached, false);
expect(reportedDismissUpdatePreviousReached, false);
expect(reportedDismissUpdateProgress, 0.0);
});
testWidgets('Change direction does not lose child state', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/108961
Widget buildFrame(DismissDirection direction) {
return Directionality(
textDirection: TextDirection.ltr,
child: Dismissible(
dragStartBehavior: DragStartBehavior.down,
direction: direction,
key: const Key('Dismissible'),
resizeDuration: null,
child: const SizedBox(
width: 100.0,
height: 100.0,
child: Text('I Love Flutter!'),
),
),
);
}
await tester.pumpWidget(buildFrame(DismissDirection.horizontal));
final RenderBox textRenderObjectBegin = tester.renderObject(find.text('I Love Flutter!'));
await tester.pumpWidget(buildFrame(DismissDirection.none));
final RenderBox textRenderObjectEnd = tester.renderObject(find.text('I Love Flutter!'));
expect(identical(textRenderObjectBegin, textRenderObjectEnd), true);
});
}
| flutter/packages/flutter/test/widgets/dismissible_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/dismissible_test.dart",
"repo_id": "flutter",
"token_count": 16203
} | 687 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import '../image_data.dart';
import '../painting/image_test_utils.dart';
const Duration animationDuration = Duration(milliseconds: 50);
class FadeInImageParts {
const FadeInImageParts(this.fadeInImageElement, this.placeholder, this.target);
final ComponentElement fadeInImageElement;
final FadeInImageElements? placeholder;
final FadeInImageElements target;
State? get state {
StatefulElement? animatedFadeOutFadeInElement;
fadeInImageElement.visitChildren((Element child) {
expect(animatedFadeOutFadeInElement, isNull);
animatedFadeOutFadeInElement = child as StatefulElement;
});
expect(animatedFadeOutFadeInElement, isNotNull);
return animatedFadeOutFadeInElement!.state;
}
}
class FadeInImageElements {
const FadeInImageElements(this.rawImageElement);
final Element rawImageElement;
RawImage get rawImage => rawImageElement.widget as RawImage;
double get opacity => rawImage.opacity?.value ?? 1.0;
BoxFit? get fit => rawImage.fit;
FilterQuality? get filterQuality => rawImage.filterQuality;
Color? get color => rawImage.color;
BlendMode? get colorBlendMode => rawImage.colorBlendMode;
}
class LoadTestImageProvider extends ImageProvider<Object> {
LoadTestImageProvider(this.provider);
final ImageProvider provider;
ImageStreamCompleter testLoad(Object key, DecoderBufferCallback decode) {
return provider.loadBuffer(key, decode);
}
@override
Future<Object> obtainKey(ImageConfiguration configuration) {
throw UnimplementedError();
}
@override
ImageStreamCompleter loadImage(Object key, ImageDecoderCallback decode) {
throw UnimplementedError();
}
}
FadeInImageParts findFadeInImage(WidgetTester tester) {
final List<FadeInImageElements> elements = <FadeInImageElements>[];
final Iterable<Element> rawImageElements = tester.elementList(find.byType(RawImage));
ComponentElement? fadeInImageElement;
for (final Element rawImageElement in rawImageElements) {
rawImageElement.visitAncestorElements((Element ancestor) {
if (ancestor.widget is FadeInImage) {
if (fadeInImageElement == null) {
fadeInImageElement = ancestor as ComponentElement;
} else {
expect(fadeInImageElement, same(ancestor));
}
return false;
}
return true;
});
expect(fadeInImageElement, isNotNull);
elements.add(FadeInImageElements(rawImageElement));
}
if (elements.length == 2) {
return FadeInImageParts(fadeInImageElement!, elements.last, elements.first);
} else {
expect(elements, hasLength(1));
return FadeInImageParts(fadeInImageElement!, null, elements.first);
}
}
void main() {
// These must run outside test zone to complete
late final ui.Image targetImage;
late final ui.Image placeholderImage;
late final ui.Image replacementImage;
setUpAll(() async {
targetImage = await createTestImage();
placeholderImage = await createTestImage();
replacementImage = await createTestImage();
});
tearDownAll(() {
targetImage.dispose();
placeholderImage.dispose();
replacementImage.dispose();
});
group('FadeInImage', () {
testWidgets('animates an uncached image', (WidgetTester tester) async {
final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage);
final TestImageProvider imageProvider = TestImageProvider(targetImage);
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
fadeOutDuration: animationDuration,
fadeInDuration: animationDuration,
fadeOutCurve: Curves.linear,
fadeInCurve: Curves.linear,
excludeFromSemantics: true,
));
expect(findFadeInImage(tester).placeholder!.rawImage.image, null);
expect(findFadeInImage(tester).target.rawImage.image, null);
placeholderProvider.complete();
await tester.pump();
expect(findFadeInImage(tester).placeholder!.rawImage.image!.isCloneOf(placeholderImage), true);
expect(findFadeInImage(tester).target.rawImage.image, null);
imageProvider.complete();
await tester.pump();
for (int i = 0; i < 5; i += 1) {
final FadeInImageParts parts = findFadeInImage(tester);
expect(parts.placeholder!.rawImage.image!.isCloneOf(placeholderImage), true);
expect(parts.target.rawImage.image!.isCloneOf(targetImage), true);
expect(parts.placeholder!.opacity, moreOrLessEquals(1 - i / 5));
expect(parts.target.opacity, 0);
await tester.pump(const Duration(milliseconds: 10));
}
for (int i = 0; i < 5; i += 1) {
final FadeInImageParts parts = findFadeInImage(tester);
expect(parts.placeholder!.rawImage.image!.isCloneOf(placeholderImage), true);
expect(parts.target.rawImage.image!.isCloneOf(targetImage), true);
expect(parts.placeholder!.opacity, 0);
expect(parts.target.opacity, moreOrLessEquals(i / 5));
await tester.pump(const Duration(milliseconds: 10));
}
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
));
expect(findFadeInImage(tester).target.rawImage.image!.isCloneOf(targetImage), true);
expect(findFadeInImage(tester).target.opacity, 1);
});
testWidgets("FadeInImage's image obeys gapless playback", (WidgetTester tester) async {
final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage);
final TestImageProvider imageProvider = TestImageProvider(targetImage);
final TestImageProvider secondImageProvider = TestImageProvider(replacementImage);
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
fadeOutDuration: animationDuration,
fadeInDuration: animationDuration,
));
imageProvider.complete();
placeholderProvider.complete();
await tester.pump();
await tester.pump(animationDuration * 2);
// Calls setState after the animation, which removes the placeholder image.
await tester.pump(const Duration(milliseconds: 100));
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: secondImageProvider,
));
await tester.pump();
FadeInImageParts parts = findFadeInImage(tester);
// Continually shows previously loaded image,
expect(parts.placeholder, isNull);
expect(parts.target.rawImage.image!.isCloneOf(targetImage), isTrue);
expect(parts.target.opacity, 1);
// Until the new image provider provides the image.
secondImageProvider.complete();
await tester.pump();
parts = findFadeInImage(tester);
expect(parts.target.rawImage.image!.isCloneOf(replacementImage), isTrue);
expect(parts.target.opacity, 1);
});
// Regression test for https://github.com/flutter/flutter/issues/111011
testWidgets("FadeInImage's image obeys gapless playback when first image is cached but second isn't",
(WidgetTester tester) async {
final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage);
final TestImageProvider imageProvider = TestImageProvider(targetImage);
final TestImageProvider secondImageProvider = TestImageProvider(replacementImage);
// Pre-cache the initial image.
imageProvider.resolve(ImageConfiguration.empty);
imageProvider.complete();
placeholderProvider.complete();
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
));
await tester.pumpAndSettle();
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: secondImageProvider,
));
FadeInImageParts parts = findFadeInImage(tester);
// Continually shows previously loaded image until the new image provider provides the image.
expect(parts.placeholder, isNull);
expect(parts.target.rawImage.image!.isCloneOf(targetImage), isTrue);
expect(parts.target.opacity, 1);
// Now, provide the image.
secondImageProvider.complete();
await tester.pump();
parts = findFadeInImage(tester);
expect(parts.target.rawImage.image!.isCloneOf(replacementImage), isTrue);
expect(parts.target.opacity, 1);
});
testWidgets("FadeInImage's placeholder obeys gapless playback", (WidgetTester tester) async {
final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage);
final TestImageProvider secondPlaceholderProvider = TestImageProvider(replacementImage);
final TestImageProvider imageProvider = TestImageProvider(targetImage);
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
));
placeholderProvider.complete();
await tester.pump();
FadeInImageParts parts = findFadeInImage(tester);
expect(parts.placeholder!.rawImage.image!.isCloneOf(placeholderImage), true);
expect(parts.placeholder!.opacity, 1);
await tester.pumpWidget(FadeInImage(
placeholder: secondPlaceholderProvider,
image: imageProvider,
));
parts = findFadeInImage(tester);
// continually shows previously loaded image.
expect(parts.placeholder!.rawImage.image!.isCloneOf(placeholderImage), true);
expect(parts.placeholder!.opacity, 1);
// Until the new image provider provides the image.
secondPlaceholderProvider.complete();
await tester.pump();
parts = findFadeInImage(tester);
expect(parts.placeholder!.rawImage.image!.isCloneOf(replacementImage), true);
expect(parts.placeholder!.opacity, 1);
});
testWidgets('shows a cached image immediately when skipFadeOnSynchronousLoad=true', (WidgetTester tester) async {
final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage);
final TestImageProvider imageProvider = TestImageProvider(targetImage);
imageProvider.resolve(ImageConfiguration.empty);
imageProvider.complete();
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
));
expect(findFadeInImage(tester).target.rawImage.image!.isCloneOf(targetImage), true);
expect(findFadeInImage(tester).placeholder, isNull);
expect(findFadeInImage(tester).target.opacity, 1);
});
testWidgets('handles updating the placeholder image', (WidgetTester tester) async {
final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage);
final TestImageProvider secondPlaceholderProvider = TestImageProvider(replacementImage);
final TestImageProvider imageProvider = TestImageProvider(targetImage);
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
fadeOutDuration: animationDuration,
fadeInDuration: animationDuration,
excludeFromSemantics: true,
));
final State? state = findFadeInImage(tester).state;
placeholderProvider.complete();
await tester.pump();
expect(findFadeInImage(tester).placeholder!.rawImage.image!.isCloneOf(placeholderImage), true);
await tester.pumpWidget(FadeInImage(
placeholder: secondPlaceholderProvider,
image: imageProvider,
fadeOutDuration: animationDuration,
fadeInDuration: animationDuration,
excludeFromSemantics: true,
));
secondPlaceholderProvider.complete();
await tester.pump();
expect(findFadeInImage(tester).placeholder!.rawImage.image!.isCloneOf(replacementImage), true);
expect(findFadeInImage(tester).state, same(state));
});
testWidgets('does not keep the placeholder in the tree if it is invisible', (WidgetTester tester) async {
final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage);
final TestImageProvider imageProvider = TestImageProvider(targetImage);
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
fadeOutDuration: animationDuration,
fadeInDuration: animationDuration,
excludeFromSemantics: true,
));
placeholderProvider.complete();
await tester.pumpAndSettle();
expect(find.byType(Image), findsNWidgets(2));
imageProvider.complete();
await tester.pumpAndSettle();
expect(find.byType(Image), findsOneWidget);
});
testWidgets("doesn't interrupt in-progress animation when animation values are updated", (WidgetTester tester) async {
final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage);
final TestImageProvider imageProvider = TestImageProvider(targetImage);
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
fadeOutDuration: animationDuration,
fadeInDuration: animationDuration,
excludeFromSemantics: true,
));
final State? state = findFadeInImage(tester).state;
placeholderProvider.complete();
imageProvider.complete();
await tester.pump();
await tester.pump(animationDuration);
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
fadeOutDuration: animationDuration * 2,
fadeInDuration: animationDuration * 2,
excludeFromSemantics: true,
));
expect(findFadeInImage(tester).state, same(state));
expect(findFadeInImage(tester).placeholder!.opacity, moreOrLessEquals(0));
expect(findFadeInImage(tester).target.opacity, moreOrLessEquals(0));
await tester.pump(animationDuration);
expect(findFadeInImage(tester).placeholder!.opacity, moreOrLessEquals(0));
expect(findFadeInImage(tester).target.opacity, moreOrLessEquals(1));
});
testWidgets('Image color and colorBlend parameters', (WidgetTester tester) async {
final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage);
final TestImageProvider imageProvider = TestImageProvider(targetImage);
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
color: const Color(0xFF00FF00),
colorBlendMode: BlendMode.clear,
placeholderColor: const Color(0xFF0000FF),
placeholderColorBlendMode: BlendMode.modulate,
fadeOutDuration: animationDuration,
fadeInDuration: animationDuration,
excludeFromSemantics: true,
));
expect(findFadeInImage(tester).placeholder?.color, const Color(0xFF0000FF));
expect(findFadeInImage(tester).placeholder?.colorBlendMode, BlendMode.modulate);
await tester.pump(animationDuration);
expect(findFadeInImage(tester).target.color, const Color(0xFF00FF00));
expect(findFadeInImage(tester).target.colorBlendMode, BlendMode.clear);
});
group('ImageProvider', () {
test('memory placeholder cacheWidth and cacheHeight is passed through', () async {
final Uint8List testBytes = Uint8List.fromList(kTransparentImage);
final FadeInImage image = FadeInImage.memoryNetwork(
placeholder: testBytes,
image: 'test.com',
placeholderCacheWidth: 20,
placeholderCacheHeight: 30,
imageCacheWidth: 40,
imageCacheHeight: 50,
);
bool called = false;
Future<ui.Codec> decode(ui.ImmutableBuffer buffer, {int? cacheWidth, int? cacheHeight, bool allowUpscaling = false}) {
expect(cacheWidth, 20);
expect(cacheHeight, 30);
expect(allowUpscaling, false);
called = true;
return PaintingBinding.instance.instantiateImageCodecFromBuffer(buffer, cacheWidth: cacheWidth, cacheHeight: cacheHeight, allowUpscaling: allowUpscaling);
}
final ImageProvider resizeImage = image.placeholder;
expect(image.placeholder, isA<ResizeImage>());
expect(called, false);
final LoadTestImageProvider testProvider = LoadTestImageProvider(image.placeholder);
final ImageStreamCompleter streamCompleter = testProvider.testLoad(await resizeImage.obtainKey(ImageConfiguration.empty), decode);
final Completer<void> completer = Completer<void>();
streamCompleter.addListener(ImageStreamListener((ImageInfo imageInfo, bool syncCall) {
completer.complete();
}));
await completer.future;
expect(called, true);
});
test('do not resize when null cache dimensions', () async {
final Uint8List testBytes = Uint8List.fromList(kTransparentImage);
final FadeInImage image = FadeInImage.memoryNetwork(
placeholder: testBytes,
image: 'test.com',
);
bool called = false;
Future<ui.Codec> decode(ui.ImmutableBuffer buffer, {int? cacheWidth, int? cacheHeight, bool allowUpscaling = false}) {
expect(cacheWidth, null);
expect(cacheHeight, null);
expect(allowUpscaling, false);
called = true;
return PaintingBinding.instance.instantiateImageCodecFromBuffer(buffer, cacheWidth: cacheWidth, cacheHeight: cacheHeight);
}
// image.placeholder should be an instance of MemoryImage instead of ResizeImage
final ImageProvider memoryImage = image.placeholder;
expect(image.placeholder, isA<MemoryImage>());
expect(called, false);
final LoadTestImageProvider testProvider = LoadTestImageProvider(image.placeholder);
final ImageStreamCompleter streamCompleter = testProvider.testLoad(await memoryImage.obtainKey(ImageConfiguration.empty), decode);
final Completer<void> completer = Completer<void>();
streamCompleter.addListener(ImageStreamListener((ImageInfo imageInfo, bool syncCall) {
completer.complete();
}));
await completer.future;
expect(called, true);
});
});
group('semantics', () {
testWidgets('only one Semantics node appears within FadeInImage', (WidgetTester tester) async {
final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage);
final TestImageProvider imageProvider = TestImageProvider(targetImage);
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
));
expect(find.byType(Semantics), findsOneWidget);
});
testWidgets('is excluded if excludeFromSemantics is true', (WidgetTester tester) async {
final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage);
final TestImageProvider imageProvider = TestImageProvider(targetImage);
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
excludeFromSemantics: true,
));
expect(find.byType(Semantics), findsNothing);
});
group('label', () {
const String imageSemanticText = 'Test image semantic label';
testWidgets('defaults to image label if placeholder label is unspecified', (WidgetTester tester) async {
Semantics semanticsWidget() => tester.widget(find.byType(Semantics));
final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage);
final TestImageProvider imageProvider = TestImageProvider(targetImage);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
fadeOutDuration: animationDuration,
fadeInDuration: animationDuration,
imageSemanticLabel: imageSemanticText,
),
));
placeholderProvider.complete();
await tester.pump();
expect(semanticsWidget().properties.label, imageSemanticText);
imageProvider.complete();
await tester.pump();
await tester.pump(const Duration(milliseconds: 51));
expect(semanticsWidget().properties.label, imageSemanticText);
});
testWidgets('is empty without any specified semantics labels', (WidgetTester tester) async {
Semantics semanticsWidget() => tester.widget(find.byType(Semantics));
final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage);
final TestImageProvider imageProvider = TestImageProvider(targetImage);
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
fadeOutDuration: animationDuration,
fadeInDuration: animationDuration,
));
placeholderProvider.complete();
await tester.pump();
expect(semanticsWidget().properties.label, isEmpty);
imageProvider.complete();
await tester.pump();
await tester.pump(const Duration(milliseconds: 51));
expect(semanticsWidget().properties.label, isEmpty);
});
});
});
group("placeholder's BoxFit", () {
testWidgets("should be the image's BoxFit when not set", (WidgetTester tester) async {
final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage);
final TestImageProvider imageProvider = TestImageProvider(targetImage);
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
fit: BoxFit.cover,
));
expect(findFadeInImage(tester).placeholder!.fit, equals(findFadeInImage(tester).target.fit));
expect(findFadeInImage(tester).placeholder!.fit, equals(BoxFit.cover));
});
testWidgets('should be the given value when set', (WidgetTester tester) async {
final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage);
final TestImageProvider imageProvider = TestImageProvider(targetImage);
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
fit: BoxFit.cover,
placeholderFit: BoxFit.fill,
));
expect(findFadeInImage(tester).target.fit, equals(BoxFit.cover));
expect(findFadeInImage(tester).placeholder!.fit, equals(BoxFit.fill));
});
});
group("placeholder's FilterQuality", () {
testWidgets("should be the image's FilterQuality when not set", (WidgetTester tester) async {
final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage);
final TestImageProvider imageProvider = TestImageProvider(targetImage);
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
filterQuality: FilterQuality.medium,
));
expect(findFadeInImage(tester).placeholder!.filterQuality, equals(findFadeInImage(tester).target.filterQuality));
expect(findFadeInImage(tester).placeholder!.filterQuality, equals(FilterQuality.medium));
});
testWidgets('should be the given value when set', (WidgetTester tester) async {
final TestImageProvider placeholderProvider = TestImageProvider(placeholderImage);
final TestImageProvider imageProvider = TestImageProvider(targetImage);
await tester.pumpWidget(FadeInImage(
placeholder: placeholderProvider,
image: imageProvider,
filterQuality: FilterQuality.medium,
placeholderFilterQuality: FilterQuality.high,
));
expect(findFadeInImage(tester).target.filterQuality, equals(FilterQuality.medium));
expect(findFadeInImage(tester).placeholder!.filterQuality, equals(FilterQuality.high));
});
});
});
}
| flutter/packages/flutter/test/widgets/fade_in_image_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/fade_in_image_test.dart",
"repo_id": "flutter",
"token_count": 8775
} | 688 |
// 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';
class Item {
GlobalKey key1 = GlobalKey();
GlobalKey key2 = GlobalKey();
@override
String toString() => 'Item($key1, $key2)';
}
List<Item> items = <Item>[Item(), Item()];
class StatefulLeaf extends StatefulWidget {
const StatefulLeaf({ GlobalKey? key }) : super(key: key);
@override
StatefulLeafState createState() => StatefulLeafState();
}
class StatefulLeafState extends State<StatefulLeaf> {
void markNeedsBuild() { setState(() { }); }
@override
Widget build(BuildContext context) => const Text('leaf', textDirection: TextDirection.ltr);
}
class KeyedWrapper extends StatelessWidget {
const KeyedWrapper(this.key1, this.key2, { super.key });
final Key key1;
final GlobalKey key2;
@override
Widget build(BuildContext context) {
return Container(
key: key1,
child: StatefulLeaf(
key: key2,
),
);
}
}
Widget builder() {
return Column(
children: <Widget>[
KeyedWrapper(items[1].key1, items[1].key2),
KeyedWrapper(items[0].key1, items[0].key2),
],
);
}
void main() {
testWidgets('moving subtrees with global keys - smoketest', (WidgetTester tester) async {
await tester.pumpWidget(builder());
final StatefulLeafState leaf = tester.firstState(find.byType(StatefulLeaf));
leaf.markNeedsBuild();
await tester.pump();
final Item lastItem = items[1];
items.remove(lastItem);
items.insert(0, lastItem);
await tester.pumpWidget(builder()); // this marks the app dirty and rebuilds it
});
}
| flutter/packages/flutter/test/widgets/global_keys_moving_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/global_keys_moving_test.dart",
"repo_id": "flutter",
"token_count": 633
} | 689 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@TestOn('!chrome')
library;
import 'dart:convert';
import 'dart:ui' as ui show Image;
import 'package:flutter/foundation.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import '../image_data.dart';
ByteData testByteData(double scale) => ByteData(8)..setFloat64(0, scale);
double scaleOf(ByteData data) => data.getFloat64(0);
final Map<Object?, Object?> testManifest = <Object?, Object?>{
'assets/image.png' : <Map<String, Object>>[
<String, String>{'asset': 'assets/image.png'},
<String, Object>{'asset': 'assets/1.5x/image.png', 'dpr': 1.5},
<String, Object>{'asset': 'assets/2.0x/image.png', 'dpr': 2.0},
<String, Object>{'asset': 'assets/3.0x/image.png', 'dpr': 3.0},
<String, Object>{'asset': 'assets/4.0x/image.png', 'dpr': 4.0}
],
};
class TestAssetBundle extends CachingAssetBundle {
TestAssetBundle({ required Map<Object?, Object?> manifest }) {
this.manifest = const StandardMessageCodec().encodeMessage(manifest)!;
}
late final ByteData manifest;
@override
Future<ByteData> load(String key) {
final ByteData data = switch (key) {
'AssetManifest.bin' => manifest,
'assets/image.png' => testByteData(1.0),
'assets/1.0x/image.png' => testByteData(10.0), // see "...with a main asset and a 1.0x asset"
'assets/1.5x/image.png' => testByteData(1.5),
'assets/2.0x/image.png' => testByteData(2.0),
'assets/3.0x/image.png' => testByteData(3.0),
'assets/4.0x/image.png' => testByteData(4.0),
_ => throw ArgumentError('Unexpected key: $key'),
};
return SynchronousFuture<ByteData>(data);
}
@override
String toString() => '${describeIdentity(this)}()';
}
class FakeImageStreamCompleter extends ImageStreamCompleter {
FakeImageStreamCompleter(Future<ImageInfo> image) {
image.then<void>(setImage);
}
}
class TestAssetImage extends AssetImage {
const TestAssetImage(super.assetName, this.images);
final Map<double, ui.Image> images;
@override
ImageStreamCompleter loadImage(AssetBundleImageKey key, ImageDecoderCallback decode) {
late ImageInfo imageInfo;
key.bundle.load(key.name).then<void>((ByteData data) {
final ui.Image image = images[scaleOf(data)]!;
imageInfo = ImageInfo(image: image, scale: key.scale);
});
return FakeImageStreamCompleter(
SynchronousFuture<ImageInfo>(imageInfo),
);
}
}
Widget buildImageAtRatio(String imageName, Key key, double ratio, bool inferSize, Map<double, ui.Image> images, [ AssetBundle? bundle ]) {
const double windowSize = 500.0; // 500 logical pixels
const double imageSize = 200.0; // 200 logical pixels
return MediaQuery(
data: MediaQueryData(
size: const Size(windowSize, windowSize),
devicePixelRatio: ratio,
),
child: DefaultAssetBundle(
bundle: bundle ?? TestAssetBundle(manifest: testManifest),
child: Center(
child: inferSize ?
Image(
key: key,
excludeFromSemantics: true,
image: TestAssetImage(imageName, images),
) :
Image(
key: key,
excludeFromSemantics: true,
image: TestAssetImage(imageName, images),
height: imageSize,
width: imageSize,
fit: BoxFit.fill,
),
),
),
);
}
Widget buildImageCacheResized(String name, Key key, int width, int height, int cacheWidth, int cacheHeight) {
return Center(
child: RepaintBoundary(
child: SizedBox(
width: 250,
height: 250,
child: Center(
child: Image.memory(
Uint8List.fromList(kTransparentImage),
key: key,
excludeFromSemantics: true,
color: const Color(0xFF00FFFF),
colorBlendMode: BlendMode.plus,
width: width.toDouble(),
height: height.toDouble(),
cacheWidth: cacheWidth,
cacheHeight: cacheHeight,
),
),
),
),
);
}
RenderImage getRenderImage(WidgetTester tester, Key key) {
return tester.renderObject<RenderImage>(find.byKey(key));
}
Future<void> pumpTreeToLayout(WidgetTester tester, Widget widget) {
return tester.pumpWidget(widget, duration: Duration.zero, phase: EnginePhase.layout);
}
void main() {
const String image = 'assets/image.png';
final Map<double, ui.Image> images = <double, ui.Image>{};
setUpAll(() async {
for (final double scale in const <double>[0.5, 1.0, 1.5, 2.0, 4.0, 10.0]) {
final int dimension = (48 * scale).floor();
images[scale] = await createTestImage(width: dimension, height: dimension);
}
});
tearDownAll(() {
for (final ui.Image image in images.values) {
image.dispose();
}
});
testWidgets('Image for device pixel ratio 1.0', (WidgetTester tester) async {
const double ratio = 1.0;
Key key = GlobalKey();
await pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false, images));
expect(getRenderImage(tester, key).size, const Size(200.0, 200.0));
expect(getRenderImage(tester, key).scale, 1.0);
key = GlobalKey();
await pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true, images));
expect(getRenderImage(tester, key).size, const Size(48.0, 48.0));
expect(getRenderImage(tester, key).scale, 1.0);
});
testWidgets('Image for device pixel ratio 0.5', (WidgetTester tester) async {
const double ratio = 0.5;
Key key = GlobalKey();
await pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false, images));
expect(getRenderImage(tester, key).size, const Size(200.0, 200.0));
expect(getRenderImage(tester, key).scale, 1.0);
key = GlobalKey();
await pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true, images));
expect(getRenderImage(tester, key).size, const Size(48.0, 48.0));
expect(getRenderImage(tester, key).scale, 1.0);
});
testWidgets('Image for device pixel ratio 1.5', (WidgetTester tester) async {
const double ratio = 1.5;
Key key = GlobalKey();
await pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false, images));
expect(getRenderImage(tester, key).size, const Size(200.0, 200.0));
expect(getRenderImage(tester, key).scale, 1.5);
key = GlobalKey();
await pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true, images));
expect(getRenderImage(tester, key).size, const Size(48.0, 48.0));
expect(getRenderImage(tester, key).scale, 1.5);
});
// A 1.75 DPR screen is typically a low-resolution screen, such that physical
// pixels are visible to the user. For such screens we prefer to pick the
// higher resolution image, if available.
testWidgets('Image for device pixel ratio 1.75', (WidgetTester tester) async {
const double ratio = 1.75;
Key key = GlobalKey();
await pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false, images));
expect(getRenderImage(tester, key).size, const Size(200.0, 200.0));
expect(getRenderImage(tester, key).scale, 2.0);
key = GlobalKey();
await pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true, images));
expect(getRenderImage(tester, key).size, const Size(48.0, 48.0));
expect(getRenderImage(tester, key).scale, 2.0);
});
testWidgets('Image for device pixel ratio 2.3', (WidgetTester tester) async {
const double ratio = 2.3;
Key key = GlobalKey();
await pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false, images));
expect(getRenderImage(tester, key).size, const Size(200.0, 200.0));
expect(getRenderImage(tester, key).scale, 2.0);
key = GlobalKey();
await pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true, images));
expect(getRenderImage(tester, key).size, const Size(48.0, 48.0));
expect(getRenderImage(tester, key).scale, 2.0);
});
testWidgets('Image for device pixel ratio 3.7', (WidgetTester tester) async {
const double ratio = 3.7;
Key key = GlobalKey();
await pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false, images));
expect(getRenderImage(tester, key).size, const Size(200.0, 200.0));
expect(getRenderImage(tester, key).scale, 4.0);
key = GlobalKey();
await pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true, images));
expect(getRenderImage(tester, key).size, const Size(48.0, 48.0));
expect(getRenderImage(tester, key).scale, 4.0);
});
testWidgets('Image for device pixel ratio 5.1', (WidgetTester tester) async {
const double ratio = 5.1;
Key key = GlobalKey();
await pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false, images));
expect(getRenderImage(tester, key).size, const Size(200.0, 200.0));
expect(getRenderImage(tester, key).scale, 4.0);
key = GlobalKey();
await pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true, images));
expect(getRenderImage(tester, key).size, const Size(48.0, 48.0));
expect(getRenderImage(tester, key).scale, 4.0);
});
testWidgets('Image for device pixel ratio 1.0, with a main asset and a 1.0x asset', (WidgetTester tester) async {
// If both a main asset and a 1.0x asset are specified, then prefer
// the 1.0x asset.
final Map<Object?, Object?> manifest = json.decode('''
{
"assets/image.png" : [
{"asset": "assets/1.0x/image.png", "dpr": 1.0},
{"asset": "assets/1.5x/image.png", "dpr": 1.5},
{"asset": "assets/2.0x/image.png", "dpr": 2.0},
{"asset": "assets/3.0x/image.png", "dpr": 3.0},
{"asset": "assets/4.0x/image.png", "dpr": 4.0}
]
}
''') as Map<Object?, Object?>;
final AssetBundle bundle = TestAssetBundle(manifest: manifest);
const double ratio = 1.0;
Key key = GlobalKey();
await pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false, images, bundle));
expect(getRenderImage(tester, key).size, const Size(200.0, 200.0));
// Verify we got the 10x scaled image, since the test ByteData said it should be 10x.
expect(getRenderImage(tester, key).image!.height, 480);
key = GlobalKey();
await pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true, images, bundle));
expect(getRenderImage(tester, key).size, const Size(480.0, 480.0));
// Verify we got the 10x scaled image, since the test ByteData said it should be 10x.
expect(getRenderImage(tester, key).image!.height, 480);
});
testWidgets('Image cache resize upscale display 5', (WidgetTester tester) async {
final Key key = GlobalKey();
await pumpTreeToLayout(tester, buildImageCacheResized(image, key, 5, 5, 20, 20));
expect(getRenderImage(tester, key).size, const Size(5.0, 5.0));
});
testWidgets('Image cache resize upscale display 50', (WidgetTester tester) async {
final Key key = GlobalKey();
await pumpTreeToLayout(tester, buildImageCacheResized(image, key, 50, 50, 20, 20));
expect(getRenderImage(tester, key).size, const Size(50.0, 50.0));
});
testWidgets('Image cache resize downscale display 5', (WidgetTester tester) async {
final Key key = GlobalKey();
await pumpTreeToLayout(tester, buildImageCacheResized(image, key, 5, 5, 1, 1));
expect(getRenderImage(tester, key).size, const Size(5.0, 5.0));
});
// For low-resolution screens we prefer higher-resolution images due to
// visible physical pixel size (see the test for 1.75 DPR above). However,
// if higher resolution assets are not available we will pick the best
// available.
testWidgets('Low-resolution assets', (WidgetTester tester) async {
const Map<Object?, Object?> manifest = <Object?, Object?>{
'assets/image.png': <Map<String, Object>>[
<String, Object>{'asset': 'assets/image.png'},
<String, Object>{'asset': 'assets/1.5x/image.png', 'dpr': 1.5},
],
};
final AssetBundle bundle = TestAssetBundle(manifest: manifest);
Future<void> testRatio({required double ratio, required double expectedScale}) async {
Key key = GlobalKey();
await pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, false, images, bundle));
expect(getRenderImage(tester, key).size, const Size(200.0, 200.0));
expect(getRenderImage(tester, key).scale, expectedScale);
key = GlobalKey();
await pumpTreeToLayout(tester, buildImageAtRatio(image, key, ratio, true, images, bundle));
expect(getRenderImage(tester, key).size, const Size(48.0, 48.0));
expect(getRenderImage(tester, key).scale, expectedScale);
}
// Choose higher resolution image as it's the lowest available.
await testRatio(ratio: 0.25, expectedScale: 1.0);
await testRatio(ratio: 0.5, expectedScale: 1.0);
await testRatio(ratio: 0.75, expectedScale: 1.0);
await testRatio(ratio: 1.0, expectedScale: 1.0);
// Choose higher resolution image even though a lower resolution
// image is closer.
await testRatio(ratio: 1.20, expectedScale: 1.5);
// Choose higher resolution image because it's closer.
await testRatio(ratio: 1.25, expectedScale: 1.5);
await testRatio(ratio: 1.5, expectedScale: 1.5);
// Choose lower resolution image because no higher resolution assets
// are not available.
await testRatio(ratio: 1.75, expectedScale: 1.5);
await testRatio(ratio: 2.0, expectedScale: 1.5);
await testRatio(ratio: 2.25, expectedScale: 1.5);
await testRatio(ratio: 10.0, expectedScale: 1.5);
});
}
| flutter/packages/flutter/test/widgets/image_resolution_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/image_resolution_test.dart",
"repo_id": "flutter",
"token_count": 5203
} | 690 |
// 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:collection/collection.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import '../rendering/rendering_tester.dart' show TestClipPaintingContext;
class TestSliverChildListDelegate extends SliverChildListDelegate {
TestSliverChildListDelegate(super.children);
final List<String> log = <String>[];
@override
void didFinishLayout(int firstIndex, int lastIndex) {
log.add('didFinishLayout firstIndex=$firstIndex lastIndex=$lastIndex');
}
}
class Alive extends StatefulWidget {
const Alive(this.alive, this.index, { super.key });
final bool alive;
final int index;
@override
AliveState createState() => AliveState();
@override
String toString({ DiagnosticLevel minLevel = DiagnosticLevel.info }) => '$index $alive';
}
class AliveState extends State<Alive> with AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => widget.alive;
@override
Widget build(BuildContext context) {
super.build(context);
return Text('${widget.index}:$wantKeepAlive');
}
}
typedef WhetherToKeepAlive = bool Function(int);
class _StatefulListView extends StatefulWidget {
const _StatefulListView(this.aliveCallback);
final WhetherToKeepAlive aliveCallback;
@override
_StatefulListViewState createState() => _StatefulListViewState();
}
class _StatefulListViewState extends State<_StatefulListView> {
@override
Widget build(BuildContext context) {
return GestureDetector(
// force a rebuild - the test(s) using this are verifying that the list is
// still correct after rebuild
onTap: () => setState,
child: Directionality(
textDirection: TextDirection.ltr,
child: ListView(
children: List<Widget>.generate(200, (int i) {
return Builder(
builder: (BuildContext context) {
return Alive(widget.aliveCallback(i), i);
},
);
}),
),
),
);
}
}
void main() {
// Regression test for https://github.com/flutter/flutter/issues/100451
testWidgets('ListView.builder respects findChildIndexCallback', (WidgetTester tester) async {
bool finderCalled = false;
int itemCount = 7;
late StateSetter stateSetter;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
stateSetter = setState;
return ListView.builder(
itemCount: itemCount,
itemBuilder: (BuildContext _, int index) => Container(
key: Key('$index'),
height: 2000.0,
),
findChildIndexCallback: (Key key) {
finderCalled = true;
return null;
},
);
},
),
)
);
expect(finderCalled, false);
// Trigger update.
stateSetter(() => itemCount = 77);
await tester.pump();
expect(finderCalled, true);
});
// Regression test for https://github.com/flutter/flutter/issues/100451
testWidgets('ListView.separator respects findChildIndexCallback', (WidgetTester tester) async {
bool finderCalled = false;
int itemCount = 7;
late StateSetter stateSetter;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
stateSetter = setState;
return ListView.separated(
itemCount: itemCount,
itemBuilder: (BuildContext _, int index) => Container(
key: Key('$index'),
height: 2000.0,
),
findChildIndexCallback: (Key key) {
finderCalled = true;
return null;
},
separatorBuilder: (BuildContext _, int __) => const Divider(),
);
},
),
)
);
expect(finderCalled, false);
// Trigger update.
stateSetter(() => itemCount = 77);
await tester.pump();
expect(finderCalled, true);
});
testWidgets('ListView default control', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: ListView(itemExtent: 100.0),
),
),
);
});
testWidgets('ListView itemExtent control test', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
itemExtent: 200.0,
children: List<Widget>.generate(20, (int i) {
return ColoredBox(
color: Colors.green,
child: Text('$i'),
);
}),
),
),
);
final RenderBox box = tester.renderObject<RenderBox>(find.byType(ColoredBox).first);
expect(box.size.height, equals(200.0));
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsNothing);
await tester.drag(find.byType(ListView), const Offset(0.0, -250.0));
await tester.pump();
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsNothing);
expect(find.text('6'), findsNothing);
await tester.drag(find.byType(ListView), const Offset(0.0, 200.0));
await tester.pump();
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
});
testWidgets('ListView large scroll jump', (WidgetTester tester) async {
final List<int> log = <int>[];
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
itemExtent: 200.0,
children: List<Widget>.generate(20, (int i) {
return Builder(
builder: (BuildContext context) {
log.add(i);
return Text('$i');
},
);
}),
),
),
);
expect(log, equals(<int>[0, 1, 2, 3, 4]));
log.clear();
final ScrollableState state = tester.state(find.byType(Scrollable));
final ScrollPosition position = state.position;
position.jumpTo(2025.0);
expect(log, isEmpty);
await tester.pump();
expect(log, equals(<int>[8, 9, 10, 11, 12, 13, 14]));
log.clear();
position.jumpTo(975.0);
expect(log, isEmpty);
await tester.pump();
expect(log, equals(<int>[7, 6, 5, 4, 3]));
log.clear();
});
testWidgets('ListView large scroll jump and keepAlive first child not keepAlive', (WidgetTester tester) async {
Future<void> checkAndScroll([ String zero = '0:false' ]) async {
expect(find.text(zero), findsOneWidget);
expect(find.text('1:false'), findsOneWidget);
expect(find.text('2:false'), findsOneWidget);
expect(find.text('3:true'), findsOneWidget);
expect(find.text('116:false'), findsNothing);
final ScrollableState state = tester.state(find.byType(Scrollable));
final ScrollPosition position = state.position;
position.jumpTo(1025.0);
await tester.pump();
expect(find.text(zero), findsNothing);
expect(find.text('1:false'), findsNothing);
expect(find.text('2:false'), findsNothing);
expect(find.text('3:true', skipOffstage: false), findsOneWidget);
expect(find.text('116:false'), findsOneWidget);
await tester.tapAt(const Offset(100.0, 100.0));
position.jumpTo(0.0);
await tester.pump();
await tester.pump();
expect(find.text(zero), findsOneWidget);
expect(find.text('1:false'), findsOneWidget);
expect(find.text('2:false'), findsOneWidget);
expect(find.text('3:true'), findsOneWidget);
}
await tester.pumpWidget(_StatefulListView((int i) => i > 2 && i % 3 == 0));
await checkAndScroll();
await tester.pumpWidget(_StatefulListView((int i) => i % 3 == 0));
await checkAndScroll('0:true');
});
testWidgets('ListView can build out of underflow', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
itemExtent: 100.0,
),
),
);
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsNothing);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
itemExtent: 100.0,
children: List<Widget>.generate(2, (int i) {
return Text('$i');
}),
),
),
);
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsNothing);
expect(find.text('3'), findsNothing);
expect(find.text('4'), findsNothing);
expect(find.text('5'), findsNothing);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
itemExtent: 100.0,
children: List<Widget>.generate(5, (int i) {
return Text('$i');
}),
),
),
);
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsOneWidget);
expect(find.text('2'), findsOneWidget);
expect(find.text('3'), findsOneWidget);
expect(find.text('4'), findsOneWidget);
expect(find.text('5'), findsNothing);
});
testWidgets('ListView can build out of overflow padding', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox.shrink(
child: ListView(
padding: const EdgeInsets.all(8.0),
children: const <Widget>[
Text('padded', textDirection: TextDirection.ltr),
],
),
),
),
),
);
expect(find.text('padded', skipOffstage: false), findsOneWidget);
});
testWidgets('ListView with itemExtent in unbounded context', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: SingleChildScrollView(
child: ListView(
itemExtent: 100.0,
shrinkWrap: true,
children: List<Widget>.generate(20, (int i) {
return Text('$i');
}),
),
),
),
);
expect(find.text('0'), findsOneWidget);
expect(find.text('19'), findsOneWidget);
});
testWidgets('ListView with shrink wrap in bounded context correctly uses cache extent', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: SizedBox(
height: 400,
child: ListView(
itemExtent: 100.0,
shrinkWrap: true,
children: List<Widget>.generate(20, (int i) {
return Text('Text $i');
}),
),
),
),
);
expect(tester.getSemantics(find.text('Text 5')), matchesSemantics());
expect(tester.getSemantics(find.text('Text 6', skipOffstage: false)), matchesSemantics(isHidden: true));
expect(tester.getSemantics(find.text('Text 7', skipOffstage: false)), matchesSemantics(isHidden: true));
expect(tester.getSemantics(find.text('Text 8', skipOffstage: false)), matchesSemantics(isHidden: true));
handle.dispose();
});
testWidgets('ListView hidden items should stay hidden if their semantics are updated', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: SizedBox(
height: 400,
child: ListView(
itemExtent: 100.0,
shrinkWrap: true,
children: List<Widget>.generate(20, (int i) {
return Text('Text $i');
}),
),
),
),
);
// Scrollable maybe be marked dirty after layout.
await tester.pumpAndSettle();
expect(tester.getSemantics(find.text('Text 5')), matchesSemantics());
expect(tester.getSemantics(find.text('Text 6', skipOffstage: false)), matchesSemantics(isHidden: true));
expect(tester.getSemantics(find.text('Text 7', skipOffstage: false)), matchesSemantics(isHidden: true));
expect(tester.getSemantics(find.text('Text 8', skipOffstage: false)), matchesSemantics(isHidden: true));
// Marks Text 6 semantics as dirty.
final RenderObject text6 = tester.renderObject(find.text('Text 6', skipOffstage: false));
text6.markNeedsSemanticsUpdate();
// Verify the semantics is still hidden.
await tester.pump();
expect(tester.getSemantics(find.text('Text 6', skipOffstage: false)), matchesSemantics(isHidden: true));
handle.dispose();
});
testWidgets('didFinishLayout has correct indices', (WidgetTester tester) async {
final TestSliverChildListDelegate delegate = TestSliverChildListDelegate(
List<Widget>.generate(
20,
(int i) {
return Text('$i', textDirection: TextDirection.ltr);
},
),
);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView.custom(
itemExtent: 110.0,
childrenDelegate: delegate,
),
),
);
expect(delegate.log, equals(<String>['didFinishLayout firstIndex=0 lastIndex=7']));
delegate.log.clear();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView.custom(
itemExtent: 210.0,
childrenDelegate: delegate,
),
),
);
expect(delegate.log, equals(<String>['didFinishLayout firstIndex=0 lastIndex=4']));
delegate.log.clear();
await tester.drag(find.byType(ListView), const Offset(0.0, -600.0));
expect(delegate.log, isEmpty);
await tester.pump();
expect(delegate.log, equals(<String>['didFinishLayout firstIndex=1 lastIndex=6']));
delegate.log.clear();
});
testWidgets('ListView automatically pad MediaQuery on axis', (WidgetTester tester) async {
EdgeInsets? innerMediaQueryPadding;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(
padding: EdgeInsets.all(30.0),
),
child: ListView(
children: <Widget>[
const Text('top', textDirection: TextDirection.ltr),
Builder(builder: (BuildContext context) {
innerMediaQueryPadding = MediaQuery.paddingOf(context);
return Container();
}),
],
),
),
),
);
// Automatically apply the top/bottom padding into sliver.
expect(tester.getTopLeft(find.text('top')).dy, 30.0);
// Leave left/right padding as is for children.
expect(innerMediaQueryPadding, const EdgeInsets.symmetric(horizontal: 30.0));
});
testWidgets('ListView clips if overflow is smaller than cacheExtent', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/17426.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
child: ListView(
cacheExtent: 500.0,
children: <Widget>[
Container(
height: 90.0,
),
Container(
height: 110.0,
),
Container(
height: 80.0,
),
],
),
),
),
),
);
expect(find.byType(Viewport), paints..clipRect());
});
testWidgets('ListView does not clips if no overflow', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
child: ListView(
cacheExtent: 500.0,
children: const <Widget>[
SizedBox(
height: 100.0,
),
],
),
),
),
),
);
expect(find.byType(Viewport), isNot(paints..clipRect()));
});
testWidgets('ListView (fixed extent) clips if overflow is smaller than cacheExtent', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/17426.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
child: ListView(
itemExtent: 100.0,
cacheExtent: 500.0,
children: const <Widget>[
SizedBox(
height: 100.0,
),
SizedBox(
height: 100.0,
),
SizedBox(
height: 100.0,
),
],
),
),
),
),
);
expect(find.byType(Viewport), paints..clipRect());
});
testWidgets('ListView (fixed extent) does not clips if no overflow', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
child: ListView(
itemExtent: 100.0,
cacheExtent: 500.0,
children: const <Widget>[
SizedBox(
height: 100.0,
),
],
),
),
),
),
);
expect(find.byType(Viewport), isNot(paints..clipRect()));
});
testWidgets('ListView.horizontal has implicit scrolling by default', (WidgetTester tester) async {
final SemanticsHandle handle = tester.ensureSemantics();
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
child: ListView(
scrollDirection: Axis.horizontal,
itemExtent: 100.0,
children: const <Widget>[
SizedBox(
height: 100.0,
),
],
),
),
),
),
);
expect(tester.getSemantics(find.byType(Scrollable)), matchesSemantics(
children: <Matcher>[
matchesSemantics(
children: <Matcher>[
matchesSemantics(hasImplicitScrolling: true),
],
),
],
));
handle.dispose();
});
testWidgets('Updates viewport dimensions when scroll direction changes', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/43380.
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
Widget buildListView({ required Axis scrollDirection }) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
width: 100.0,
child: ListView(
controller: controller,
scrollDirection: scrollDirection,
itemExtent: 50.0,
children: const <Widget>[
SizedBox(
height: 50.0,
width: 50.0,
),
],
),
),
),
);
}
await tester.pumpWidget(buildListView(scrollDirection: Axis.horizontal));
expect(controller.position.viewportDimension, 100.0);
await tester.pumpWidget(buildListView(scrollDirection: Axis.vertical));
expect(controller.position.viewportDimension, 200.0);
await tester.pumpWidget(buildListView(scrollDirection: Axis.horizontal));
expect(controller.position.viewportDimension, 100.0);
});
testWidgets('ListView respects clipBehavior', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
children: <Widget>[Container(height: 2000.0)],
),
),
);
// 1st, check that the render object has received the default clip behavior.
final RenderViewport renderObject = tester.allRenderObjects.whereType<RenderViewport>().first;
expect(renderObject.clipBehavior, equals(Clip.hardEdge));
// 2nd, check that the painting context has received the default clip behavior.
final TestClipPaintingContext context = TestClipPaintingContext();
renderObject.paint(context, Offset.zero);
expect(context.clipBehavior, equals(Clip.hardEdge));
// 3rd, pump a new widget to check that the render object can update its clip behavior.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView(
clipBehavior: Clip.antiAlias,
children: <Widget>[Container(height: 2000.0)],
),
),
);
expect(renderObject.clipBehavior, equals(Clip.antiAlias));
// 4th, check that a non-default clip behavior can be sent to the painting context.
renderObject.paint(context, Offset.zero);
expect(context.clipBehavior, equals(Clip.antiAlias));
context.dispose();
});
testWidgets('ListView.builder respects clipBehavior', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView.builder(
itemCount: 10,
itemBuilder: (BuildContext _, int __) => Container(height: 2000.0),
clipBehavior: Clip.antiAlias,
),
),
);
final RenderViewport renderObject = tester.allRenderObjects.whereType<RenderViewport>().first;
expect(renderObject.clipBehavior, equals(Clip.antiAlias));
});
testWidgets('ListView.custom respects clipBehavior', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView.custom(
childrenDelegate: SliverChildBuilderDelegate(
(BuildContext context, int index) => Container(height: 2000.0),
childCount: 1,
),
clipBehavior: Clip.antiAlias,
),
),
);
final RenderViewport renderObject = tester.allRenderObjects.whereType<RenderViewport>().first;
expect(renderObject.clipBehavior, equals(Clip.antiAlias));
});
testWidgets('ListView.separated respects clipBehavior', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView.separated(
itemCount: 10,
itemBuilder: (BuildContext _, int __) => Container(height: 2000.0),
separatorBuilder: (BuildContext _, int __) => const Divider(),
clipBehavior: Clip.antiAlias,
),
),
);
final RenderViewport renderObject = tester.allRenderObjects.whereType<RenderViewport>().first;
expect(renderObject.clipBehavior, equals(Clip.antiAlias));
});
// Regression test for https://github.com/flutter/flutter/pull/138912
testWidgets('itemExtentBuilder should respect item count', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
final List<double> numbers = <double>[
10, 20, 30, 40, 50,
];
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView.builder(
controller: controller,
itemCount: numbers.length,
itemExtentBuilder: (int index, SliverLayoutDimensions dimensions) {
return numbers[index];
},
itemBuilder: (BuildContext context, int index) {
return SizedBox(
height: numbers[index],
child: Text('Item $index'),
);
},
),
),
);
expect(find.text('Item 0'), findsOneWidget);
expect(find.text('Item 4'), findsOneWidget);
expect(find.text('Item 5'), findsNothing);
});
// Regression test for https://github.com/flutter/flutter/pull/131393
testWidgets('itemExtentBuilder test', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
final List<int> buildLog = <int>[];
late SliverLayoutDimensions sliverLayoutDimensions;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: ListView.builder(
controller: controller,
itemExtentBuilder: (int index, SliverLayoutDimensions dimensions) {
sliverLayoutDimensions = dimensions;
return 100.0;
},
itemBuilder: (BuildContext context, int index) {
buildLog.insert(0, index);
return Text('Item $index');
},
),
),
);
expect(find.text('Item 0'), findsOneWidget);
expect(find.text('Item 5'), findsOneWidget);
expect(find.text('Item 6'), findsNothing);
expect(
sliverLayoutDimensions,
const SliverLayoutDimensions(
scrollOffset: 0.0,
precedingScrollExtent: 0.0,
viewportMainAxisExtent: 600.0,
crossAxisExtent: 800.0,
)
);
// viewport(600.0) + cache extent after(250.0)
expect(buildLog.length, 9);
expect(buildLog.min, 0);
expect(buildLog.max, 8);
buildLog.clear();
// Scrolling drastically.
controller.jumpTo(10000.0);
await tester.pump();
expect(find.text('Item 99'), findsNothing);
expect(find.text('Item 100'), findsOneWidget);
expect(find.text('Item 105'), findsOneWidget);
expect(find.text('Item 106'), findsNothing);
expect(
sliverLayoutDimensions,
const SliverLayoutDimensions(
scrollOffset: 10000.0,
precedingScrollExtent: 0.0,
viewportMainAxisExtent: 600.0,
crossAxisExtent: 800.0,
)
);
// Scrolling drastically only loading the visible and cached area items.
// cache extent before(250.0) + viewport(600.0) + cache extent after(250.0)
expect(buildLog.length, 12);
expect(buildLog.min, 97);
expect(buildLog.max, 108);
buildLog.clear();
controller.jumpTo(5000.0);
await tester.pump();
expect(find.text('Item 49'), findsNothing);
expect(find.text('Item 50'), findsOneWidget);
expect(find.text('Item 55'), findsOneWidget);
expect(find.text('Item 56'), findsNothing);
expect(
sliverLayoutDimensions,
const SliverLayoutDimensions(
scrollOffset: 5000.0,
precedingScrollExtent: 0.0,
viewportMainAxisExtent: 600.0,
crossAxisExtent: 800.0,
)
);
// cache extent before(250.0) + viewport(600.0) + cache extent after(250.0)
expect(buildLog.length, 12);
expect(buildLog.min, 47);
expect(buildLog.max, 58);
buildLog.clear();
controller.jumpTo(4700.0);
await tester.pump();
expect(find.text('Item 46'), findsNothing);
expect(find.text('Item 47'), findsOneWidget);
expect(find.text('Item 52'), findsOneWidget);
expect(find.text('Item 53'), findsNothing);
expect(
sliverLayoutDimensions,
const SliverLayoutDimensions(
scrollOffset: 4700.0,
precedingScrollExtent: 0.0,
viewportMainAxisExtent: 600.0,
crossAxisExtent: 800.0,
)
);
// Only newly entered cached area items need to be loaded.
expect(buildLog.length, 3);
expect(buildLog.min, 44);
expect(buildLog.max, 46);
buildLog.clear();
controller.jumpTo(5300.0);
await tester.pump();
expect(find.text('Item 52'), findsNothing);
expect(find.text('Item 53'), findsOneWidget);
expect(find.text('Item 58'), findsOneWidget);
expect(find.text('Item 59'), findsNothing);
expect(
sliverLayoutDimensions,
const SliverLayoutDimensions(
scrollOffset: 5300.0,
precedingScrollExtent: 0.0,
viewportMainAxisExtent: 600.0,
crossAxisExtent: 800.0,
)
);
// Only newly entered cached area items need to be loaded.
expect(buildLog.length, 6);
expect(buildLog.min, 56);
expect(buildLog.max, 61);
});
testWidgets('itemExtent, prototypeItem and itemExtentBuilder conflicts test', (WidgetTester tester) async {
Object? error;
try {
await tester.pumpWidget(
ListView.builder(
itemExtentBuilder: (int index, SliverLayoutDimensions dimensions) {
return 100.0;
},
itemExtent: 100.0,
itemBuilder: (BuildContext context, int index) {
return Text('Item $index');
},
),
);
} catch (e) {
error = e;
}
expect(error, isNotNull);
error = null;
try {
await tester.pumpWidget(
ListView.builder(
itemExtentBuilder: (int index, SliverLayoutDimensions dimensions) {
return 100.0;
},
prototypeItem: Container(),
itemBuilder: (BuildContext context, int index) {
return Text('Item $index');
},
),
);
} catch (e) {
error = e;
}
expect(error, isNotNull);
error = null;
try {
await tester.pumpWidget(
ListView.builder(
itemExtent: 100.0,
prototypeItem: Container(),
itemBuilder: (BuildContext context, int index) {
return Text('Item $index');
},
),
);
} catch (e) {
error = e;
}
expect(error, isNotNull);
});
}
| flutter/packages/flutter/test/widgets/list_view_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/list_view_test.dart",
"repo_id": "flutter",
"token_count": 13433
} | 691 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
void main() {
testWidgets('runApp uses deprecated pipelineOwner and renderView', (WidgetTester tester) async {
runApp(const SizedBox());
final RenderObject renderObject = tester.renderObject(find.byType(SizedBox));
RenderObject parent = renderObject;
while (parent.parent != null) {
parent = parent.parent!;
}
expect(parent, isA<RenderView>());
expect(parent, equals(tester.binding.renderView));
expect(renderObject.owner, equals(tester.binding.pipelineOwner));
});
testWidgets('can manually attach RootWidget to build owner', (WidgetTester tester) async {
expect(find.byType(ColoredBox), findsNothing);
final RootWidget rootWidget = RootWidget(
child: View(
view: FakeFlutterView(tester.view),
child: const ColoredBox(color: Colors.orange),
),
);
tester.binding.attachToBuildOwner(rootWidget);
await tester.pump();
expect(find.byType(ColoredBox), findsOneWidget);
expect(tester.binding.rootElement!.widget, equals(rootWidget));
expect(tester.element(find.byType(ColoredBox)).owner, equals(tester.binding.buildOwner));
});
testWidgets('runApp throws if given a View',
experimentalLeakTesting: LeakTesting.settings.withIgnoredAll(), // The test leaks by design because of exception.
(WidgetTester tester) async {
runApp(
View(
view: FakeFlutterView(tester.view),
child: const SizedBox.shrink(),
),
);
expect(
tester.takeException(),
isFlutterError.having(
(FlutterError e) => e.message,
'message',
contains('passing it to "runWidget" instead of "runApp"'),
),
);
});
testWidgets('runWidget throws if not given a View', (WidgetTester tester) async {
runWidget(const SizedBox.shrink());
expect(
tester.takeException(),
isFlutterError.having(
(FlutterError e) => e.message,
'message',
contains('Try wrapping your widget in a View widget'),
),
);
});
testWidgets('runWidget does not throw if given a View', (WidgetTester tester) async {
runWidget(
View(
view: FakeFlutterView(tester.view),
child: const SizedBox.shrink(),
),
);
expect(find.byType(View), findsOne);
});
testWidgets('can call runWidget with an empty ViewCollection', (WidgetTester tester) async {
runWidget(const ViewCollection(views: <Widget>[]));
expect(find.byType(ViewCollection), findsOne);
});
}
class FakeFlutterView extends TestFlutterView {
FakeFlutterView(TestFlutterView view) : super(view: view, display: view.display, platformDispatcher: view.platformDispatcher);
}
| flutter/packages/flutter/test/widgets/multi_view_binding_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/multi_view_binding_test.dart",
"repo_id": "flutter",
"token_count": 1093
} | 692 |
// 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:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
void main() {
testWidgets('Opacity', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
// Opacity 1.0: Semantics and painting
await tester.pumpWidget(
const Opacity(
opacity: 1.0,
child: Text('a', textDirection: TextDirection.rtl),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0),
label: 'a',
textDirection: TextDirection.rtl,
),
],
),
));
expect(find.byType(Opacity), paints..paragraph());
// Opacity 0.0: Nothing
await tester.pumpWidget(
const Opacity(
opacity: 0.0,
child: Text('a', textDirection: TextDirection.rtl),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(),
));
expect(find.byType(Opacity), paintsNothing);
// Opacity 0.0 with semantics: Just semantics
await tester.pumpWidget(
const Opacity(
opacity: 0.0,
alwaysIncludeSemantics: true,
child: Text('a', textDirection: TextDirection.rtl),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0),
label: 'a',
textDirection: TextDirection.rtl,
),
],
),
));
expect(find.byType(Opacity), paintsNothing);
// Opacity 0.0 without semantics: Nothing
await tester.pumpWidget(
const Opacity(
opacity: 0.0,
child: Text('a', textDirection: TextDirection.rtl),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(),
));
expect(find.byType(Opacity), paintsNothing);
// Opacity 0.1: Semantics and painting
await tester.pumpWidget(
const Opacity(
opacity: 0.1,
child: Text('a', textDirection: TextDirection.rtl),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0),
label: 'a',
textDirection: TextDirection.rtl,
),
],
),
));
expect(find.byType(Opacity), paints..paragraph());
// Opacity 0.1 without semantics: Still has semantics and painting
await tester.pumpWidget(
const Opacity(
opacity: 0.1,
child: Text('a', textDirection: TextDirection.rtl),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0),
label: 'a',
textDirection: TextDirection.rtl,
),
],
),
));
expect(find.byType(Opacity), paints..paragraph());
// Opacity 0.1 with semantics: Semantics and painting
await tester.pumpWidget(
const Opacity(
opacity: 0.1,
alwaysIncludeSemantics: true,
child: Text('a', textDirection: TextDirection.rtl),
),
);
expect(semantics, hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
id: 1,
rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0),
label: 'a',
textDirection: TextDirection.rtl,
),
],
),
));
expect(find.byType(Opacity), paints..paragraph());
semantics.dispose();
});
testWidgets('offset is correctly handled in Opacity', (WidgetTester tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
child: RepaintBoundary(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: List<Widget>.generate(10, (int index) {
return Opacity(
opacity: 0.5,
child: Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
color: Colors.blue,
height: 50,
),
),
);
}),
),
),
),
),
),
);
await expectLater(
find.byType(RepaintBoundary).first,
matchesGoldenFile('opacity_test.offset.png'),
);
});
testWidgets('empty opacity does not crash', (WidgetTester tester) async {
await tester.pumpWidget(
RepaintBoundary(child: Opacity(opacity: 0.5, child: Container())),
);
final Element element = find.byType(RepaintBoundary).first.evaluate().single;
// The following line will send the layer to engine and cause crash if an
// empty opacity layer is sent.
final OffsetLayer offsetLayer = element.renderObject!.debugLayer! as OffsetLayer;
final ui.Image image = await offsetLayer.toImage(const Rect.fromLTRB(0.0, 0.0, 1.0, 1.0));
image.dispose();
}, skip: isBrowser); // https://github.com/flutter/flutter/issues/49857
testWidgets('Child shows up in the right spot when opacity is disabled', (WidgetTester tester) async {
debugDisableOpacityLayers = true;
final GlobalKey key = GlobalKey();
await tester.pumpWidget(
RepaintBoundary(
key: key,
child: Directionality(
textDirection: TextDirection.ltr,
child: Stack(
children: <Widget>[
Positioned(
top: 40,
left: 140,
child: Opacity(
opacity: .5,
child: Container(height: 100, width: 100, color: Colors.red),
),
),
],
),
),
),
);
await expectLater(
find.byKey(key),
matchesGoldenFile('opacity_disabled_with_child.png'),
);
debugDisableOpacityLayers = false;
});
}
| flutter/packages/flutter/test/widgets/opacity_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/opacity_test.dart",
"repo_id": "flutter",
"token_count": 3174
} | 693 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('Placeholder', (WidgetTester tester) async {
await tester.pumpWidget(const Placeholder());
expect(tester.renderObject<RenderBox>(find.byType(Placeholder)).size, const Size(800.0, 600.0));
await tester.pumpWidget(const Center(child: Placeholder()));
expect(tester.renderObject<RenderBox>(find.byType(Placeholder)).size, const Size(800.0, 600.0));
await tester.pumpWidget(const Stack(textDirection: TextDirection.ltr, children: <Widget>[Positioned(top: 0.0, bottom: 0.0, child: Placeholder())]));
expect(tester.renderObject<RenderBox>(find.byType(Placeholder)).size, const Size(400.0, 600.0));
await tester.pumpWidget(const Stack(textDirection: TextDirection.ltr, children: <Widget>[Positioned(left: 0.0, right: 0.0, child: Placeholder())]));
expect(tester.renderObject<RenderBox>(find.byType(Placeholder)).size, const Size(800.0, 400.0));
await tester.pumpWidget(const Stack(textDirection: TextDirection.ltr, children: <Widget>[Positioned(top: 0.0, child: Placeholder(fallbackWidth: 200.0, fallbackHeight: 300.0))]));
expect(tester.renderObject<RenderBox>(find.byType(Placeholder)).size, const Size(200.0, 300.0));
});
testWidgets('Placeholder color', (WidgetTester tester) async {
await tester.pumpWidget(const Placeholder());
expect(tester.renderObject(find.byType(Placeholder)), paints..path(color: const Color(0xFF455A64)));
await tester.pumpWidget(const Placeholder(color: Color(0xFF00FF00)));
expect(tester.renderObject(find.byType(Placeholder)), paints..path(color: const Color(0xFF00FF00)));
});
testWidgets('Placeholder stroke width', (WidgetTester tester) async {
await tester.pumpWidget(const Placeholder());
expect(tester.renderObject(find.byType(Placeholder)), paints..path(strokeWidth: 2.0));
await tester.pumpWidget(const Placeholder(strokeWidth: 10.0));
expect(tester.renderObject(find.byType(Placeholder)), paints..path(strokeWidth: 10.0));
});
testWidgets('Placeholder child widget', (WidgetTester tester) async {
await tester.pumpWidget(const Placeholder());
expect(find.text('Label'), findsNothing);
await tester.pumpWidget(const MaterialApp(home: Placeholder(child: Text('Label'))));
expect(find.text('Label'), findsOneWidget);
});
}
| flutter/packages/flutter/test/widgets/placeholder_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/placeholder_test.dart",
"repo_id": "flutter",
"token_count": 856
} | 694 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
List<Widget> children(int n) {
return List<Widget>.generate(n, (int i) {
return SizedBox(height: 100.0, child: Text('$i'));
});
}
void main() {
testWidgets('Scrolling with list view changes, leaving the overscroll', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(MaterialApp(home: ListView(controller: controller, children: children(30))));
final double thirty = controller.position.maxScrollExtent;
controller.jumpTo(thirty);
await tester.pump();
controller.jumpTo(thirty + 100.0); // past the end
await tester.pump();
await tester.pumpWidget(MaterialApp(home: ListView(controller: controller, children: children(31))));
expect(controller.position.pixels, thirty + 100.0); // has the same position, but no longer overscrolled
expect(await tester.pumpAndSettle(), 1); // doesn't have ballistic animation...
expect(controller.position.pixels, thirty + 100.0); // and ends up at the end
});
testWidgets('Scrolling with list view changes, remaining overscrolled', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(MaterialApp(home: ListView(controller: controller, children: children(30))));
final double thirty = controller.position.maxScrollExtent;
controller.jumpTo(thirty);
await tester.pump();
controller.jumpTo(thirty + 200.0); // past the end
await tester.pump();
await tester.pumpWidget(MaterialApp(home: ListView(controller: controller, children: children(31))));
expect(controller.position.pixels, thirty + 200.0); // has the same position, still overscrolled
expect(await tester.pumpAndSettle(), 8); // now it goes ballistic...
expect(controller.position.pixels, thirty + 100.0); // and ends up at the end
});
testWidgets('Ability to keep a PageView at the end manually (issue 62209)', (WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: PageView62209()));
expect(find.text('Page 1'), findsOneWidget);
expect(find.text('Page 100'), findsNothing);
await tester.drag(find.byType(PageView62209), const Offset(-800.0, 0.0));
await tester.pump();
expect(find.text('Page 1'), findsNothing);
expect(find.text('Page 2'), findsOneWidget);
expect(find.text('Page 100'), findsNothing);
await tester.drag(find.byType(PageView62209), const Offset(-800.0, 0.0));
await tester.pump();
expect(find.text('Page 1'), findsNothing);
expect(find.text('Page 3'), findsOneWidget);
expect(find.text('Page 100'), findsNothing);
await tester.drag(find.byType(PageView62209), const Offset(-800.0, 0.0));
await tester.pump();
expect(find.text('Page 1'), findsNothing);
expect(find.text('Page 4'), findsOneWidget);
expect(find.text('Page 100'), findsNothing);
await tester.drag(find.byType(PageView62209), const Offset(-800.0, 0.0));
await tester.pump();
expect(find.text('Page 1'), findsNothing);
expect(find.text('Page 5'), findsOneWidget);
expect(find.text('Page 100'), findsNothing);
await tester.drag(find.byType(PageView62209), const Offset(-800.0, 0.0));
await tester.pump();
expect(find.text('Page 1'), findsNothing);
expect(find.text('Page 5'), findsNothing);
expect(find.text('Page 100'), findsOneWidget);
await tester.tap(find.byType(TextButton)); // 6
await tester.pump();
expect(find.text('Page 1'), findsNothing);
expect(find.text('Page 6'), findsNothing);
expect(find.text('Page 5'), findsNothing);
expect(find.text('Page 100'), findsOneWidget);
await tester.tap(find.byType(TextButton)); // 7
await tester.pump();
expect(find.text('Page 1'), findsNothing);
expect(find.text('Page 6'), findsNothing);
expect(find.text('Page 7'), findsNothing);
expect(find.text('Page 5'), findsNothing);
expect(find.text('Page 100'), findsOneWidget);
await tester.drag(find.byType(PageView62209), const Offset(800.0, 0.0));
await tester.pump();
expect(find.text('Page 1'), findsNothing);
expect(find.text('Page 5'), findsOneWidget);
expect(find.text('Page 100'), findsNothing);
await tester.drag(find.byType(PageView62209), const Offset(800.0, 0.0));
await tester.pump();
expect(find.text('Page 1'), findsNothing);
expect(find.text('Page 4'), findsOneWidget);
expect(find.text('Page 5'), findsNothing);
expect(find.text('Page 100'), findsNothing);
await tester.tap(find.byType(TextButton)); // 8
await tester.pump();
expect(find.text('Page 1'), findsNothing);
expect(find.text('Page 8'), findsNothing);
expect(find.text('Page 4'), findsOneWidget);
expect(find.text('Page 5'), findsNothing);
expect(find.text('Page 100'), findsNothing);
await tester.drag(find.byType(PageView62209), const Offset(800.0, 0.0));
await tester.pump();
expect(find.text('Page 3'), findsOneWidget);
await tester.drag(find.byType(PageView62209), const Offset(800.0, 0.0));
await tester.pump();
expect(find.text('Page 2'), findsOneWidget);
await tester.drag(find.byType(PageView62209), const Offset(800.0, 0.0));
await tester.pump();
expect(find.text('Page 6'), findsOneWidget);
await tester.drag(find.byType(PageView62209), const Offset(800.0, 0.0));
await tester.pump();
expect(find.text('Page 7'), findsOneWidget);
await tester.drag(find.byType(PageView62209), const Offset(800.0, 0.0));
await tester.pump();
expect(find.text('Page 8'), findsOneWidget);
await tester.drag(find.byType(PageView62209), const Offset(800.0, 0.0));
await tester.pump();
expect(find.text('Page 1'), findsOneWidget);
await tester.tap(find.byType(TextButton)); // 9
await tester.pump();
expect(find.text('Page 1'), findsOneWidget);
expect(find.text('Page 9'), findsNothing);
await tester.drag(find.byType(PageView62209), const Offset(-800.0, 0.0));
await tester.pump();
expect(find.text('Page 9'), findsOneWidget);
});
testWidgets('Pointer is not ignored during trackpad scrolling.', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
int? lastTapped;
int? lastHovered;
await tester.pumpWidget(MaterialApp(
home: ListView(
controller: controller,
children: List<Widget>.generate(30, (int i) {
return SizedBox(height: 100.0, child: MouseRegion(
onHover: (PointerHoverEvent event) {
lastHovered = i;
},
child: GestureDetector(
onTap: () {
lastTapped = i;
},
child: Text('$i')
)
));
})
)
));
final TestGesture touchGesture = await tester.createGesture(kind: PointerDeviceKind.touch); // ignore: avoid_redundant_argument_values
// Try mouse hovering while scrolling by touch
await touchGesture.down(tester.getCenter(find.byType(ListView)));
await tester.pump();
await touchGesture.moveBy(const Offset(0, 200));
await tester.pump();
final TestGesture hoverGesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await hoverGesture.addPointer(
location: tester.getCenter(find.text('3'))
);
await hoverGesture.moveBy(const Offset(1, 1));
await hoverGesture.removePointer(
location: tester.getCenter(find.text('3'))
);
await tester.pumpAndSettle();
expect(controller.position.activity?.shouldIgnorePointer, isTrue); // Pointer is ignored for touch scrolling.
expect(lastHovered, isNull);
await touchGesture.up();
await tester.pump();
// Try mouse clicking during inertia after scrolling by touch
await tester.fling(find.byType(ListView), const Offset(0, -200), 1000);
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
expect(controller.position.activity?.shouldIgnorePointer, isTrue); // Pointer is ignored following touch scrolling.
await tester.tap(find.text('3'), warnIfMissed: false);
expect(lastTapped, isNull);
await tester.pumpAndSettle();
controller.jumpTo(0);
await tester.pump();
final TestGesture trackpadGesture = await tester.createGesture(kind: PointerDeviceKind.trackpad);
// Try mouse hovering while scrolling with a trackpad
await trackpadGesture.panZoomStart(tester.getCenter(find.byType(ListView)));
await tester.pump();
await trackpadGesture.panZoomUpdate(tester.getCenter(find.byType(ListView)), pan: const Offset(0, 200));
await tester.pump();
await hoverGesture.addPointer(
location: tester.getCenter(find.text('3'))
);
await hoverGesture.moveBy(const Offset(1, 1));
await hoverGesture.removePointer(
location: tester.getCenter(find.text('3'))
);
await tester.pumpAndSettle();
expect(controller.position.activity?.shouldIgnorePointer, isFalse); // Pointer is not ignored for trackpad scrolling.
expect(lastHovered, equals(3));
await trackpadGesture.panZoomEnd();
await tester.pump();
// Try mouse clicking during inertia after scrolling with a trackpad
await tester.trackpadFling(find.byType(ListView), const Offset(0, -200), 1000);
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
expect(controller.position.activity?.shouldIgnorePointer, isFalse); // Pointer is not ignored following trackpad scrolling.
await tester.tap(find.text('3'));
expect(lastTapped, equals(3));
await tester.pumpAndSettle();
});
test('$ScrollActivity dispatches memory events', () async {
await expectLater(
await memoryEvents(
() => _ScrollActivity(_ScrollActivityDelegate()).dispose(),
_ScrollActivity,
),
areCreateAndDispose,
);
});
test('$ScrollDragController dispatches memory events', () async {
await expectLater(
await memoryEvents(
() => ScrollDragController(
delegate: _ScrollActivityDelegate(),
details: DragStartDetails(),
).dispose(),
ScrollDragController,
),
areCreateAndDispose,
);
});
}
class PageView62209 extends StatefulWidget {
const PageView62209({super.key});
@override
State<PageView62209> createState() => _PageView62209State();
}
class _PageView62209State extends State<PageView62209> {
int _nextPageNum = 1;
final List<Carousel62209Page> _pages = <Carousel62209Page>[];
@override
void initState() {
super.initState();
for (int i = 0; i < 5; i++) {
_pages.add(Carousel62209Page(
key: Key('$_nextPageNum'),
number: _nextPageNum++,
));
}
_pages.add(const Carousel62209Page(number: 100));
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: <Widget>[
Expanded(child: Carousel62209(pages: _pages)),
TextButton(
child: const Text('ADD PAGE'),
onPressed: () {
setState(() {
_pages.insert(
1,
Carousel62209Page(
key: Key('$_nextPageNum'),
number: _nextPageNum++,
),
);
});
},
),
],
),
);
}
}
class Carousel62209Page extends StatelessWidget {
const Carousel62209Page({required this.number, super.key});
final int number;
@override
Widget build(BuildContext context) {
return Center(child: Text('Page $number'));
}
}
class Carousel62209 extends StatefulWidget {
const Carousel62209({super.key, required this.pages});
final List<Carousel62209Page> pages;
@override
State<Carousel62209> createState() => _Carousel62209State();
}
class _Carousel62209State extends State<Carousel62209> {
// page variables
late PageController _pageController;
int _currentPage = 0;
// controls updates outside of user interaction
late List<Carousel62209Page> _pages;
bool _jumpingToPage = false;
@override
void initState() {
super.initState();
_pages = widget.pages.toList();
_pageController = PageController(keepPage: false);
}
@override
void didUpdateWidget(Carousel62209 oldWidget) {
super.didUpdateWidget(oldWidget);
if (!_jumpingToPage) {
int newPage = -1;
for (int i = 0; i < widget.pages.length; i++) {
if (widget.pages[i].number == _pages[_currentPage].number) {
newPage = i;
}
}
if (newPage == _currentPage) {
_pages = widget.pages.toList();
} else {
_jumpingToPage = true;
SchedulerBinding.instance.addPostFrameCallback((_) {
if (mounted) {
setState(() {
_pages = widget.pages.toList();
_currentPage = newPage;
_pageController.jumpToPage(_currentPage);
SchedulerBinding.instance.addPostFrameCallback((_) {
_jumpingToPage = false;
});
});
}
});
}
}
}
@override
void dispose() {
_pageController.dispose();
super.dispose();
}
bool _handleScrollNotification(ScrollNotification notification) {
if (notification is ScrollUpdateNotification) {
final int page = _pageController.page!.round();
if (!_jumpingToPage && _currentPage != page) {
_currentPage = page;
}
}
return true;
}
@override
Widget build(BuildContext context) {
return NotificationListener<ScrollNotification>(
onNotification: _handleScrollNotification,
child: PageView.builder(
controller: _pageController,
itemCount: _pages.length,
itemBuilder: (BuildContext context, int index) {
return _pages[index];
},
),
);
}
}
class _ScrollActivity extends ScrollActivity {
_ScrollActivity(super.delegate);
@override
bool get isScrolling => false;
@override
bool get shouldIgnorePointer => true;
@override
double get velocity => 0.0;
}
class _ScrollActivityDelegate extends ScrollActivityDelegate {
@override
void applyUserOffset(double delta) {}
@override
AxisDirection get axisDirection => AxisDirection.down;
@override
void goBallistic(double velocity) {}
@override
void goIdle() {}
@override
double setPixels(double pixels) => 0.0;
}
| flutter/packages/flutter/test/widgets/scroll_activity_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/scroll_activity_test.dart",
"repo_id": "flutter",
"token_count": 5672
} | 695 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('Can dispose ScrollPosition when hasPixels is false', () {
final ScrollPosition position = ScrollPositionWithSingleContext(
initialPixels: null,
keepScrollOffset: false,
physics: const AlwaysScrollableScrollPhysics(),
context: ScrollableState(),
);
expect(position.hasPixels, false);
position.dispose(); // Should not throw/assert.
});
testWidgets('scrollable in hidden overlay does not crash when unhidden', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/44269.
final TabController controller = TabController(vsync: const TestVSync(), length: 1);
addTearDown(controller.dispose);
final OverlayEntry entry1 = OverlayEntry(
maintainState: true,
opaque: true,
builder: (BuildContext context) {
return TabBar(
isScrollable: true,
controller: controller,
tabs: const <Tab>[
Tab(text: 'Main'),
],
);
},
);
addTearDown(() {entry1.remove(); entry1.dispose();});
final OverlayEntry entry2 = OverlayEntry(
maintainState: true,
opaque: true,
builder: (BuildContext context) {
return const Text('number2');
},
);
addTearDown(() { entry2.dispose();});
await tester.pumpWidget(
MaterialApp(
home: Material(
child: Overlay(
initialEntries: <OverlayEntry>[
entry1,
entry2,
],
),
),
),
);
entry2.remove();
await tester.pump();
expect(tester.takeException(), isNull);
});
}
| flutter/packages/flutter/test/widgets/scrollable_in_overlay_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/scrollable_in_overlay_test.dart",
"repo_id": "flutter",
"token_count": 758
} | 696 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@TestOn('!chrome')
library;
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:leak_tracker_flutter_testing/leak_tracker_flutter_testing.dart';
import 'semantics_tester.dart';
void main() {
group('generateTestSemanticsExpressionForCurrentSemanticsTree', () {
_tests();
});
}
void _tests() {
setUp(() {
debugResetSemanticsIdCounter();
});
Future<void> pumpTestWidget(WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: ListView(
children: <Widget>[
const Text('Plain text'),
Semantics(
selected: true,
checked: true,
onTap: () { },
onDecrease: () { },
value: 'test-value',
increasedValue: 'test-increasedValue',
decreasedValue: 'test-decreasedValue',
hint: 'test-hint',
textDirection: TextDirection.rtl,
child: const Text('Interactive text'),
),
],
),
));
}
// This test generates code using generateTestSemanticsExpressionForCurrentSemanticsTree
// then compares it to the code used in the 'generated code is correct' test
// below. When you update the implementation of generateTestSemanticsExpressionForCurrentSemanticsTree
// also update this code to reflect the new output.
//
// This test is flexible w.r.t. leading and trailing whitespace.
testWidgets('generates code',
// TODO(polina-c): clean up leaks, https://github.com/flutter/flutter/issues/134787 [leaks-to-clean]
experimentalLeakTesting: LeakTesting.settings.withIgnoredAll(),
(WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await pumpTestWidget(tester);
final String code = semantics
.generateTestSemanticsExpressionForCurrentSemanticsTree(DebugSemanticsDumpOrder.inverseHitTest)
.split('\n')
.map<String>((String line) => line.trim())
.join('\n')
.trim();
File? findThisTestFile(Directory directory) {
for (final FileSystemEntity entity in directory.listSync()) {
if (entity is Directory) {
final File? childSearch = findThisTestFile(entity);
if (childSearch != null) {
return childSearch;
}
} else if (entity is File && entity.path.endsWith('semantics_tester_generate_test_semantics_expression_for_current_semantics_tree_test.dart')) {
return entity;
}
}
return null;
}
final File thisTestFile = findThisTestFile(Directory.current)!;
expect(thisTestFile, isNotNull);
String expectedCode = thisTestFile.readAsStringSync();
expectedCode = expectedCode.substring(
expectedCode.indexOf('v' * 12) + 12,
expectedCode.indexOf('^' * 12) - 3,
)
.split('\n')
.map<String>((String line) => line.trim())
.join('\n')
.trim();
semantics.dispose();
expect('$code,', expectedCode);
});
testWidgets('generated code is correct', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await pumpTestWidget(tester);
expect(
semantics,
hasSemantics(
// The code below delimited by "v" and "^" characters is generated by
// generateTestSemanticsExpressionForCurrentSemanticsTree function.
// You must update it when changing the output generated by
// generateTestSemanticsExpressionForCurrentSemanticsTree. Otherwise,
// the test 'generates code', defined above, will fail.
// vvvvvvvvvvvv
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
id: 1,
textDirection: TextDirection.ltr,
children: <TestSemantics>[
TestSemantics(
id: 2,
children: <TestSemantics>[
TestSemantics(
id: 3,
flags: <SemanticsFlag>[SemanticsFlag.scopesRoute],
children: <TestSemantics>[
TestSemantics(
id: 4,
children: <TestSemantics>[
TestSemantics(
id: 7,
flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling],
children: <TestSemantics>[
TestSemantics(
id: 5,
tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')],
label: 'Plain text',
textDirection: TextDirection.ltr,
),
TestSemantics(
id: 6,
tags: <SemanticsTag>[const SemanticsTag('RenderViewport.twoPane')],
flags: <SemanticsFlag>[SemanticsFlag.hasCheckedState, SemanticsFlag.isChecked, SemanticsFlag.isSelected],
actions: <SemanticsAction>[SemanticsAction.tap, SemanticsAction.decrease],
label: '\u202aInteractive text\u202c',
value: 'test-value',
increasedValue: 'test-increasedValue',
decreasedValue: 'test-decreasedValue',
hint: 'test-hint',
textDirection: TextDirection.rtl,
),
],
),
],
),
],
),
],
),
],
),
],
),
// ^^^^^^^^^^^^
ignoreRect: true,
ignoreTransform: true,
ignoreId: true,
),
);
semantics.dispose();
});
}
| flutter/packages/flutter/test/widgets/semantics_tester_generate_test_semantics_expression_for_current_semantics_tree_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/semantics_tester_generate_test_semantics_expression_for_current_semantics_tree_test.dart",
"repo_id": "flutter",
"token_count": 3098
} | 697 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import '../rendering/rendering_tester.dart' show TestClipPaintingContext;
import 'semantics_tester.dart';
class TestScrollPosition extends ScrollPositionWithSingleContext {
TestScrollPosition({
required super.physics,
required ScrollContext state,
double super.initialPixels,
super.oldPosition,
}) : super(
context: state,
);
}
class TestScrollController extends ScrollController {
@override
ScrollPosition createScrollPosition(ScrollPhysics physics, ScrollContext context, ScrollPosition? oldPosition) {
return TestScrollPosition(
physics: physics,
state: context,
initialPixels: initialScrollOffset,
oldPosition: oldPosition,
);
}
}
Widget primaryScrollControllerBoilerplate({ required Widget child, required ScrollController controller }) {
return Directionality(
textDirection: TextDirection.ltr,
child: MediaQuery(
data: const MediaQueryData(),
child: PrimaryScrollController(
controller: controller,
child: child,
),
),
);
}
void main() {
testWidgets('SingleChildScrollView overflow and clipRect test', (WidgetTester tester) async {
// the test widowSize is Size(800.0, 600.0)
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: SingleChildScrollView(
child: Container(height: 600.0),
),
),
);
// 1st, check that the render object has received the default clip behavior.
final dynamic renderObject = tester.allRenderObjects.where((RenderObject o) => o.runtimeType.toString() == '_RenderSingleChildViewport').first;
expect(renderObject.clipBehavior, equals(Clip.hardEdge)); // ignore: avoid_dynamic_calls
// 2nd, height == widow.height test: check that the painting context does not call pushClipRect .
TestClipPaintingContext context = TestClipPaintingContext();
renderObject.paint(context, Offset.zero); // ignore: avoid_dynamic_calls
expect(context.clipBehavior, equals(Clip.none));
// 3rd, height overflow test: check that the painting context call pushClipRect.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: SingleChildScrollView(
child: Container(height: 600.1),
),
),
);
renderObject.paint(context, Offset.zero); // ignore: avoid_dynamic_calls
expect(context.clipBehavior, equals(Clip.hardEdge));
// 4th, width == widow.width test: check that the painting context do not call pushClipRect.
context = TestClipPaintingContext();
expect(context.clipBehavior, equals(Clip.none)); // initial value
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Container(width: 800.0),
),
),
);
renderObject.paint(context, Offset.zero); // ignore: avoid_dynamic_calls
expect(context.clipBehavior, equals(Clip.none));
// 5th, width overflow test: check that the painting context call pushClipRect.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Container(width: 800.1),
),
),
);
renderObject.paint(context, Offset.zero); // ignore: avoid_dynamic_calls
expect(context.clipBehavior, equals(Clip.hardEdge));
});
testWidgets('SingleChildScrollView respects clipBehavior', (WidgetTester tester) async {
await tester.pumpWidget(SingleChildScrollView(child: Container(height: 2000.0)));
// 1st, check that the render object has received the default clip behavior.
final dynamic renderObject = tester.allRenderObjects.where((RenderObject o) => o.runtimeType.toString() == '_RenderSingleChildViewport').first;
expect(renderObject.clipBehavior, equals(Clip.hardEdge)); // ignore: avoid_dynamic_calls
// 2nd, check that the painting context has received the default clip behavior.
final TestClipPaintingContext context = TestClipPaintingContext();
renderObject.paint(context, Offset.zero); // ignore: avoid_dynamic_calls
expect(context.clipBehavior, equals(Clip.hardEdge));
// 3rd, check that the underlying Scrollable has the same clipBehavior
// Regression test for https://github.com/flutter/flutter/issues/133330
Finder scrollable = find.byWidgetPredicate((Widget widget) => widget is Scrollable);
expect(
(tester.widget(scrollable) as Scrollable).clipBehavior,
Clip.hardEdge,
);
// 4th, pump a new widget to check that the render object can update its clip behavior.
await tester.pumpWidget(SingleChildScrollView(clipBehavior: Clip.antiAlias, child: Container(height: 2000.0)));
expect(renderObject.clipBehavior, equals(Clip.antiAlias)); // ignore: avoid_dynamic_calls
// 5th, check that a non-default clip behavior can be sent to the painting context.
renderObject.paint(context, Offset.zero); // ignore: avoid_dynamic_calls
expect(context.clipBehavior, equals(Clip.antiAlias));
// 6th, check that the underlying Scrollable has the same clipBehavior
// Regression test for https://github.com/flutter/flutter/issues/133330
scrollable = find.byWidgetPredicate((Widget widget) => widget is Scrollable);
expect(
(tester.widget(scrollable) as Scrollable).clipBehavior,
Clip.antiAlias,
);
});
testWidgets('SingleChildScrollView control test', (WidgetTester tester) async {
await tester.pumpWidget(SingleChildScrollView(
child: Container(
height: 2000.0,
color: const Color(0xFF00FF00),
),
));
final RenderBox box = tester.renderObject(find.byType(Container));
expect(box.localToGlobal(Offset.zero), equals(Offset.zero));
await tester.drag(find.byType(SingleChildScrollView), const Offset(-200.0, -200.0));
expect(box.localToGlobal(Offset.zero), equals(const Offset(0.0, -200.0)));
});
testWidgets('Changing controllers changes scroll position', (WidgetTester tester) async {
final TestScrollController controller = TestScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(SingleChildScrollView(
child: Container(
height: 2000.0,
color: const Color(0xFF00FF00),
),
));
await tester.pumpWidget(SingleChildScrollView(
controller: controller,
child: Container(
height: 2000.0,
color: const Color(0xFF00FF00),
),
));
final ScrollableState scrollable = tester.state(find.byType(Scrollable));
expect(scrollable.position, isA<TestScrollPosition>());
});
testWidgets('Sets PrimaryScrollController when primary', (WidgetTester tester) async {
final ScrollController primaryScrollController = ScrollController();
addTearDown(primaryScrollController.dispose);
await tester.pumpWidget(PrimaryScrollController(
controller: primaryScrollController,
child: SingleChildScrollView(
primary: true,
child: Container(
height: 2000.0,
color: const Color(0xFF00FF00),
),
),
));
final Scrollable scrollable = tester.widget(find.byType(Scrollable));
expect(scrollable.controller, primaryScrollController);
});
testWidgets('Changing scroll controller inside dirty layout builder does not assert', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(Center(
child: SizedBox(
width: 750.0,
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return SingleChildScrollView(
child: Container(
height: 2000.0,
color: const Color(0xFF00FF00),
),
);
},
),
),
));
await tester.pumpWidget(Center(
child: SizedBox(
width: 700.0,
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return SingleChildScrollView(
controller: controller,
child: Container(
height: 2000.0,
color: const Color(0xFF00FF00),
),
);
},
),
),
));
});
testWidgets('Vertical SingleChildScrollViews are not primary by default', (WidgetTester tester) async {
const SingleChildScrollView view = SingleChildScrollView();
expect(view.primary, isNull);
});
testWidgets('Horizontal SingleChildScrollViews are not primary by default', (WidgetTester tester) async {
const SingleChildScrollView view = SingleChildScrollView(scrollDirection: Axis.horizontal);
expect(view.primary, isNull);
});
testWidgets('SingleChildScrollViews with controllers are not primary by default', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
final SingleChildScrollView view = SingleChildScrollView(
controller: controller,
);
expect(view.primary, isNull);
});
testWidgets('Vertical SingleChildScrollViews use PrimaryScrollController by default on mobile', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(primaryScrollControllerBoilerplate(
child: const SingleChildScrollView(),
controller: controller,
));
expect(controller.hasClients, isTrue);
}, variant: TargetPlatformVariant.mobile());
testWidgets("Vertical SingleChildScrollViews don't use PrimaryScrollController by default on desktop", (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(primaryScrollControllerBoilerplate(
child: const SingleChildScrollView(),
controller: controller,
));
expect(controller.hasClients, isFalse);
}, variant: TargetPlatformVariant.desktop());
testWidgets('Nested scrollables have a null PrimaryScrollController', (WidgetTester tester) async {
const Key innerKey = Key('inner');
final ScrollController primaryScrollController = ScrollController();
addTearDown(primaryScrollController.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: PrimaryScrollController(
controller: primaryScrollController,
child: SingleChildScrollView(
primary: true,
child: Container(
constraints: const BoxConstraints(maxHeight: 200.0),
child: ListView(key: innerKey, primary: true),
),
),
),
),
);
final Scrollable innerScrollable = tester.widget(
find.descendant(
of: find.byKey(innerKey),
matching: find.byType(Scrollable),
),
);
expect(innerScrollable.controller, isNull);
});
testWidgets('SingleChildScrollView semantics', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: SingleChildScrollView(
controller: controller,
child: Column(
children: List<Widget>.generate(30, (int i) {
return SizedBox(
height: 200.0,
child: Text('Tile $i'),
);
}),
),
),
),
);
List<TestSemantics> generateSemanticsChildren({int startHidden = -1, int endHidden = 30}) {
final List<TestSemantics> children = <TestSemantics>[];
for (int index = 0; index < 30; index += 1) {
final bool isHidden = index <= startHidden || index >= endHidden;
children.add(TestSemantics(
label: 'Tile $index',
textDirection: TextDirection.ltr,
flags: isHidden ? const <SemanticsFlag>[SemanticsFlag.isHidden] : 0,
));
}
return children;
}
expect(semantics, hasSemantics(
TestSemantics(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.hasImplicitScrolling,
],
actions: <SemanticsAction>[
SemanticsAction.scrollUp,
],
children: generateSemanticsChildren(endHidden: 3),
),
],
),
ignoreRect: true, ignoreTransform: true, ignoreId: true,
));
controller.jumpTo(3000.0);
await tester.pumpAndSettle();
expect(semantics, hasSemantics(
TestSemantics(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.hasImplicitScrolling,
],
actions: <SemanticsAction>[
SemanticsAction.scrollUp,
SemanticsAction.scrollDown,
],
children: generateSemanticsChildren(startHidden: 14, endHidden: 18),
),
],
),
ignoreRect: true, ignoreTransform: true, ignoreId: true,
));
controller.jumpTo(6000.0);
await tester.pumpAndSettle();
expect(semantics, hasSemantics(
TestSemantics(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[
SemanticsFlag.hasImplicitScrolling,
],
actions: <SemanticsAction>[
SemanticsAction.scrollDown,
],
children: generateSemanticsChildren(startHidden: 26),
),
],
),
ignoreRect: true, ignoreTransform: true, ignoreId: true,
));
semantics.dispose();
});
testWidgets('SingleChildScrollView semantics clips cover entire child vertical', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
final UniqueKey scrollView = UniqueKey();
final UniqueKey childBox = UniqueKey();
const double length = 10000;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: SingleChildScrollView(
key: scrollView,
controller: controller,
child: SizedBox(key: childBox, height: length),
),
),
);
final RenderObject scrollRenderObject = tester.renderObject(find.byKey(scrollView));
RenderAbstractViewport? viewport;
void findsRenderViewPort(RenderObject child) {
if (viewport != null) {
return;
}
if (child is RenderAbstractViewport) {
viewport = child;
return;
}
child.visitChildren(findsRenderViewPort);
}
scrollRenderObject.visitChildren(findsRenderViewPort);
expect(viewport, isNotNull);
final RenderObject childRenderObject = tester.renderObject(find.byKey(childBox));
Rect semanticsClip = viewport!.describeSemanticsClip(childRenderObject)!;
expect(semanticsClip.size.height, length);
controller.jumpTo(2000);
await tester.pump();
semanticsClip = viewport!.describeSemanticsClip(childRenderObject)!;
expect(semanticsClip.size.height, length);
});
testWidgets('SingleChildScrollView semantics clips cover entire child', (WidgetTester tester) async {
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
final UniqueKey scrollView = UniqueKey();
final UniqueKey childBox = UniqueKey();
const double length = 10000;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: SingleChildScrollView(
key: scrollView,
scrollDirection: Axis.horizontal,
controller: controller,
child: SizedBox(key: childBox, width: length),
),
),
);
final RenderObject scrollRenderObject = tester.renderObject(find.byKey(scrollView));
RenderAbstractViewport? viewport;
void findsRenderViewPort(RenderObject child) {
if (viewport != null) {
return;
}
if (child is RenderAbstractViewport) {
viewport = child;
return;
}
child.visitChildren(findsRenderViewPort);
}
scrollRenderObject.visitChildren(findsRenderViewPort);
expect(viewport, isNotNull);
final RenderObject childRenderObject = tester.renderObject(find.byKey(childBox));
Rect semanticsClip = viewport!.describeSemanticsClip(childRenderObject)!;
expect(semanticsClip.size.width, length);
controller.jumpTo(2000);
await tester.pump();
semanticsClip = viewport!.describeSemanticsClip(childRenderObject)!;
expect(semanticsClip.size.width, length);
});
testWidgets('SingleChildScrollView getOffsetToReveal - will not assert on axis mismatch', (WidgetTester tester) async {
final ScrollController controller = ScrollController(initialScrollOffset: 300.0);
addTearDown(controller.dispose);
List<Widget> children;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
width: 300.0,
child: SingleChildScrollView(
controller: controller,
child: Column(
children: children = List<Widget>.generate(20, (int i) {
return SizedBox(
height: 100.0,
width: 300.0,
child: Text('Tile $i'),
);
}),
),
),
),
),
),
);
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.byWidget(children[5]));
viewport.getOffsetToReveal(target, 0.0, axis: Axis.horizontal);
});
testWidgets('SingleChildScrollView getOffsetToReveal - down', (WidgetTester tester) async {
final ScrollController controller = ScrollController(initialScrollOffset: 300.0);
addTearDown(controller.dispose);
List<Widget> children;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
width: 300.0,
child: SingleChildScrollView(
controller: controller,
child: Column(
children: children = List<Widget>.generate(20, (int i) {
return SizedBox(
height: 100.0,
width: 300.0,
child: Text('Tile $i'),
);
}),
),
),
),
),
),
);
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.byWidget(children[5]));
RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0);
expect(revealed.offset, 500.0);
expect(revealed.rect, const Rect.fromLTWH(0.0, 0.0, 300.0, 100.0));
revealed = viewport.getOffsetToReveal(target, 1.0);
expect(revealed.offset, 400.0);
expect(revealed.rect, const Rect.fromLTWH(0.0, 100.0, 300.0, 100.0));
revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0));
expect(revealed.offset, 540.0);
expect(revealed.rect, const Rect.fromLTWH(40.0, 0.0, 10.0, 10.0));
revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0));
expect(revealed.offset, 350.0);
expect(revealed.rect, const Rect.fromLTWH(40.0, 190.0, 10.0, 10.0));
});
testWidgets('SingleChildScrollView getOffsetToReveal - up', (WidgetTester tester) async {
final ScrollController controller = ScrollController(initialScrollOffset: 300.0);
addTearDown(controller.dispose);
final List<Widget> children = List<Widget>.generate(20, (int i) {
return SizedBox(
height: 100.0,
width: 300.0,
child: Text('Tile $i'),
);
});
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
width: 300.0,
child: SingleChildScrollView(
controller: controller,
reverse: true,
child: Column(
children: children.reversed.toList(),
),
),
),
),
),
);
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.byWidget(children[5]));
RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0);
expect(revealed.offset, 500.0);
expect(revealed.rect, const Rect.fromLTWH(0.0, 100.0, 300.0, 100.0));
revealed = viewport.getOffsetToReveal(target, 1.0);
expect(revealed.offset, 400.0);
expect(revealed.rect, const Rect.fromLTWH(0.0, 0.0, 300.0, 100.0));
revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0));
expect(revealed.offset, 550.0);
expect(revealed.rect, const Rect.fromLTWH(40.0, 190.0, 10.0, 10.0));
revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0));
expect(revealed.offset, 360.0);
expect(revealed.rect, const Rect.fromLTWH(40.0, 0.0, 10.0, 10.0));
});
testWidgets('SingleChildScrollView getOffsetToReveal - right', (WidgetTester tester) async {
final ScrollController controller = ScrollController(initialScrollOffset: 300.0);
addTearDown(controller.dispose);
List<Widget> children;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 300.0,
width: 200.0,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
controller: controller,
child: Row(
children: children = List<Widget>.generate(20, (int i) {
return SizedBox(
height: 300.0,
width: 100.0,
child: Text('Tile $i'),
);
}),
),
),
),
),
),
);
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.byWidget(children[5]));
RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0);
expect(revealed.offset, 500.0);
expect(revealed.rect, const Rect.fromLTWH(0.0, 0.0, 100.0, 300.0));
revealed = viewport.getOffsetToReveal(target, 1.0);
expect(revealed.offset, 400.0);
expect(revealed.rect, const Rect.fromLTWH(100.0, 0.0, 100.0, 300.0));
revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0));
expect(revealed.offset, 540.0);
expect(revealed.rect, const Rect.fromLTWH(0.0, 40.0, 10.0, 10.0));
revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0));
expect(revealed.offset, 350.0);
expect(revealed.rect, const Rect.fromLTWH(190.0, 40.0, 10.0, 10.0));
});
testWidgets('SingleChildScrollView getOffsetToReveal - left', (WidgetTester tester) async {
final ScrollController controller = ScrollController(initialScrollOffset: 300.0);
addTearDown(controller.dispose);
final List<Widget> children = List<Widget>.generate(20, (int i) {
return SizedBox(
height: 300.0,
width: 100.0,
child: Text('Tile $i'),
);
});
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 300.0,
width: 200.0,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
reverse: true,
controller: controller,
child: Row(
children: children.reversed.toList(),
),
),
),
),
),
);
final RenderAbstractViewport viewport = tester.allRenderObjects.whereType<RenderAbstractViewport>().first;
final RenderObject target = tester.renderObject(find.byWidget(children[5]));
RevealedOffset revealed = viewport.getOffsetToReveal(target, 0.0);
expect(revealed.offset, 500.0);
expect(revealed.rect, const Rect.fromLTWH(100.0, 0.0, 100.0, 300.0));
revealed = viewport.getOffsetToReveal(target, 1.0);
expect(revealed.offset, 400.0);
expect(revealed.rect, const Rect.fromLTWH(0.0, 0.0, 100.0, 300.0));
revealed = viewport.getOffsetToReveal(target, 0.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0));
expect(revealed.offset, 550.0);
expect(revealed.rect, const Rect.fromLTWH(190.0, 40.0, 10.0, 10.0));
revealed = viewport.getOffsetToReveal(target, 1.0, rect: const Rect.fromLTWH(40.0, 40.0, 10.0, 10.0));
expect(revealed.offset, 360.0);
expect(revealed.rect, const Rect.fromLTWH(0.0, 40.0, 10.0, 10.0));
});
testWidgets('Nested SingleChildScrollView showOnScreen', (WidgetTester tester) async {
final List<List<Widget>> children = List<List<Widget>>.generate(10, (int x) {
return List<Widget>.generate(10, (int y) {
return SizedBox(
key: UniqueKey(),
height: 100.0,
width: 100.0,
);
});
});
late ScrollController controllerX;
addTearDown(() => controllerX.dispose());
late ScrollController controllerY;
addTearDown(() => controllerY.dispose());
/// Builds a gird:
///
/// <- x ->
/// 0 1 2 3 4 5 6 7 8 9
/// 0 c c c c c c c c c c
/// 1 c c c c c c c c c c
/// 2 c c c c c c c c c c
/// 3 c c c c c c c c c c y
/// 4 c c c c v v c c c c
/// 5 c c c c v v c c c c
/// 6 c c c c c c c c c c
/// 7 c c c c c c c c c c
/// 8 c c c c c c c c c c
/// 9 c c c c c c c c c c
///
/// Each c is a 100x100 container, v are containers visible in initial
/// viewport.
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
width: 200.0,
child: SingleChildScrollView(
controller: controllerY = ScrollController(initialScrollOffset: 400.0),
child: SingleChildScrollView(
controller: controllerX = ScrollController(initialScrollOffset: 400.0),
scrollDirection: Axis.horizontal,
child: Column(
children: children.map((List<Widget> widgets) {
return Row(
children: widgets,
);
}).toList(),
),
),
),
),
),
),
);
expect(controllerX.offset, 400.0);
expect(controllerY.offset, 400.0);
// Already in viewport
tester.renderObject(find.byWidget(children[4][4])).showOnScreen();
await tester.pumpAndSettle();
expect(controllerX.offset, 400.0);
expect(controllerY.offset, 400.0);
controllerX.jumpTo(400.0);
controllerY.jumpTo(400.0);
await tester.pumpAndSettle();
// Above viewport
tester.renderObject(find.byWidget(children[3][4])).showOnScreen();
await tester.pumpAndSettle();
expect(controllerX.offset, 400.0);
expect(controllerY.offset, 300.0);
controllerX.jumpTo(400.0);
controllerY.jumpTo(400.0);
await tester.pumpAndSettle();
// Below viewport
tester.renderObject(find.byWidget(children[6][4])).showOnScreen();
await tester.pumpAndSettle();
expect(controllerX.offset, 400.0);
expect(controllerY.offset, 500.0);
controllerX.jumpTo(400.0);
controllerY.jumpTo(400.0);
await tester.pumpAndSettle();
// Left of viewport
tester.renderObject(find.byWidget(children[4][3])).showOnScreen();
await tester.pumpAndSettle();
expect(controllerX.offset, 300.0);
expect(controllerY.offset, 400.0);
controllerX.jumpTo(400.0);
controllerY.jumpTo(400.0);
await tester.pumpAndSettle();
// Right of viewport
tester.renderObject(find.byWidget(children[4][6])).showOnScreen();
await tester.pumpAndSettle();
expect(controllerX.offset, 500.0);
expect(controllerY.offset, 400.0);
controllerX.jumpTo(400.0);
controllerY.jumpTo(400.0);
await tester.pumpAndSettle();
// Above and left of viewport
tester.renderObject(find.byWidget(children[3][3])).showOnScreen();
await tester.pumpAndSettle();
expect(controllerX.offset, 300.0);
expect(controllerY.offset, 300.0);
controllerX.jumpTo(400.0);
controllerY.jumpTo(400.0);
await tester.pumpAndSettle();
// Below and left of viewport
tester.renderObject(find.byWidget(children[6][3])).showOnScreen();
await tester.pumpAndSettle();
expect(controllerX.offset, 300.0);
expect(controllerY.offset, 500.0);
controllerX.jumpTo(400.0);
controllerY.jumpTo(400.0);
await tester.pumpAndSettle();
// Above and right of viewport
tester.renderObject(find.byWidget(children[3][6])).showOnScreen();
await tester.pumpAndSettle();
expect(controllerX.offset, 500.0);
expect(controllerY.offset, 300.0);
controllerX.jumpTo(400.0);
controllerY.jumpTo(400.0);
await tester.pumpAndSettle();
// Below and right of viewport
tester.renderObject(find.byWidget(children[6][6])).showOnScreen();
await tester.pumpAndSettle();
expect(controllerX.offset, 500.0);
expect(controllerY.offset, 500.0);
controllerX.jumpTo(400.0);
controllerY.jumpTo(400.0);
await tester.pumpAndSettle();
// Below and right of viewport with animations
tester.renderObject(find.byWidget(children[6][6])).showOnScreen(duration: const Duration(seconds: 2));
await tester.pump();
await tester.pump(const Duration(seconds: 1));
expect(tester.hasRunningAnimations, isTrue);
expect(controllerX.offset, greaterThan(400.0));
expect(controllerX.offset, lessThan(500.0));
expect(controllerY.offset, greaterThan(400.0));
expect(controllerY.offset, lessThan(500.0));
await tester.pumpAndSettle();
expect(controllerX.offset, 500.0);
expect(controllerY.offset, 500.0);
});
group('Nested SingleChildScrollView (same orientation) showOnScreen', () {
late List<Widget> children;
Future<void> buildNestedScroller({ required WidgetTester tester, ScrollController? inner, ScrollController? outer }) {
return tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 200.0,
width: 300.0,
child: SingleChildScrollView(
controller: outer,
child: Column(
children: <Widget>[
const SizedBox(
height: 200.0,
),
SizedBox(
height: 200.0,
width: 300.0,
child: SingleChildScrollView(
controller: inner,
child: Column(
children: children = List<Widget>.generate(10, (int i) {
return SizedBox(
height: 100.0,
width: 300.0,
child: Text('$i'),
);
}),
),
),
),
const SizedBox(
height: 200.0,
),
],
),
),
),
),
),
);
}
testWidgets('in view in inner, but not in outer', (WidgetTester tester) async {
final ScrollController inner = ScrollController();
addTearDown(inner.dispose);
final ScrollController outer = ScrollController();
addTearDown(outer.dispose);
await buildNestedScroller(
tester: tester,
inner: inner,
outer: outer,
);
expect(outer.offset, 0.0);
expect(inner.offset, 0.0);
tester.renderObject(find.byWidget(children[0])).showOnScreen();
await tester.pumpAndSettle();
expect(inner.offset, 0.0);
expect(outer.offset, 100.0);
});
testWidgets('not in view of neither inner nor outer', (WidgetTester tester) async {
final ScrollController inner = ScrollController();
addTearDown(inner.dispose);
final ScrollController outer = ScrollController();
addTearDown(outer.dispose);
await buildNestedScroller(
tester: tester,
inner: inner,
outer: outer,
);
expect(outer.offset, 0.0);
expect(inner.offset, 0.0);
tester.renderObject(find.byWidget(children[5])).showOnScreen();
await tester.pumpAndSettle();
expect(inner.offset, 400.0);
expect(outer.offset, 200.0);
});
testWidgets('in view in inner and outer', (WidgetTester tester) async {
final ScrollController inner = ScrollController(initialScrollOffset: 200.0);
addTearDown(inner.dispose);
final ScrollController outer = ScrollController(initialScrollOffset: 200.0);
addTearDown(outer.dispose);
await buildNestedScroller(
tester: tester,
inner: inner,
outer: outer,
);
expect(outer.offset, 200.0);
expect(inner.offset, 200.0);
tester.renderObject(find.byWidget(children[2])).showOnScreen();
await tester.pumpAndSettle();
expect(outer.offset, 200.0);
expect(inner.offset, 200.0);
});
testWidgets('inner shown in outer, but item not visible', (WidgetTester tester) async {
final ScrollController inner = ScrollController(initialScrollOffset: 200.0);
addTearDown(inner.dispose);
final ScrollController outer = ScrollController(initialScrollOffset: 200.0);
addTearDown(outer.dispose);
await buildNestedScroller(
tester: tester,
inner: inner,
outer: outer,
);
expect(outer.offset, 200.0);
expect(inner.offset, 200.0);
tester.renderObject(find.byWidget(children[5])).showOnScreen();
await tester.pumpAndSettle();
expect(outer.offset, 200.0);
expect(inner.offset, 400.0);
});
testWidgets('inner half shown in outer, item only visible in inner', (WidgetTester tester) async {
final ScrollController inner = ScrollController();
addTearDown(inner.dispose);
final ScrollController outer = ScrollController(initialScrollOffset: 100.0);
addTearDown(outer.dispose);
await buildNestedScroller(
tester: tester,
inner: inner,
outer: outer,
);
expect(outer.offset, 100.0);
expect(inner.offset, 0.0);
tester.renderObject(find.byWidget(children[1])).showOnScreen();
await tester.pumpAndSettle();
expect(outer.offset, 200.0);
expect(inner.offset, 0.0);
});
});
testWidgets('keyboardDismissBehavior tests', (WidgetTester tester) async {
final List<FocusNode> focusNodes = List<FocusNode>.generate(50, (int i) => FocusNode());
addTearDown(() {
for (final FocusNode node in focusNodes) {
node.dispose();
}
});
Future<void> boilerplate(ScrollViewKeyboardDismissBehavior behavior) {
return tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
padding: EdgeInsets.zero,
keyboardDismissBehavior: behavior,
child: Column(
children: focusNodes.map((FocusNode focusNode) {
return SizedBox(
height: 50,
child: TextField(focusNode: focusNode),
);
}).toList(),
),
),
),
),
);
}
// ScrollViewKeyboardDismissBehavior.onDrag dismiss keyboard on drag
await boilerplate(ScrollViewKeyboardDismissBehavior.onDrag);
Finder finder = find.byType(TextField).first;
TextField textField = tester.widget(finder);
await tester.showKeyboard(finder);
expect(textField.focusNode!.hasFocus, isTrue);
await tester.drag(finder, const Offset(0.0, -40.0));
await tester.pumpAndSettle();
expect(textField.focusNode!.hasFocus, isFalse);
// ScrollViewKeyboardDismissBehavior.manual does no dismiss the keyboard
await boilerplate(ScrollViewKeyboardDismissBehavior.manual);
finder = find.byType(TextField).first;
textField = tester.widget(finder);
await tester.showKeyboard(finder);
expect(textField.focusNode!.hasFocus, isTrue);
await tester.drag(finder, const Offset(0.0, -40.0));
await tester.pumpAndSettle();
expect(textField.focusNode!.hasFocus, isTrue);
});
}
| flutter/packages/flutter/test/widgets/single_child_scroll_view_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/single_child_scroll_view_test.dart",
"repo_id": "flutter",
"token_count": 15772
} | 698 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
void verifyPaintPosition(GlobalKey key, Offset ideal, bool visible) {
final RenderSliver target = key.currentContext!.findRenderObject()! as RenderSliver;
expect(target.parent, isA<RenderViewport>());
final SliverPhysicalParentData parentData = target.parentData! as SliverPhysicalParentData;
final Offset actual = parentData.paintOffset;
expect(actual, ideal);
final SliverGeometry geometry = target.geometry!;
expect(geometry.visible, visible);
}
void verifyActualBoxPosition(WidgetTester tester, Finder finder, int index, Rect ideal) {
final RenderBox box = tester.renderObjectList<RenderBox>(finder).elementAt(index);
final Rect rect = Rect.fromPoints(box.localToGlobal(Offset.zero), box.localToGlobal(box.size.bottomRight(Offset.zero)));
expect(rect, equals(ideal));
}
void main() {
testWidgets("Sliver appbars - floating - scroll offset doesn't change", (WidgetTester tester) async {
const double bigHeight = 1000.0;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
slivers: <Widget>[
const BigSliver(height: bigHeight),
SliverPersistentHeader(delegate: TestDelegate(), floating: true),
const BigSliver(height: bigHeight),
],
),
),
);
final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position;
final double max = bigHeight * 2.0 + TestDelegate().maxExtent - 600.0; // 600 is the height of the test viewport
assert(max < 10000.0);
expect(max, 1600.0);
expect(position.pixels, 0.0);
expect(position.minScrollExtent, 0.0);
expect(position.maxScrollExtent, max);
position.animateTo(10000.0, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 50));
expect(position.pixels, max);
expect(position.minScrollExtent, 0.0);
expect(position.maxScrollExtent, max);
});
testWidgets('Sliver appbars - floating - normal behavior works', (WidgetTester tester) async {
final TestDelegate delegate = TestDelegate();
const double bigHeight = 1000.0;
GlobalKey key1, key2, key3;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
slivers: <Widget>[
BigSliver(key: key1 = GlobalKey(), height: bigHeight),
SliverPersistentHeader(key: key2 = GlobalKey(), delegate: delegate, floating: true),
BigSliver(key: key3 = GlobalKey(), height: bigHeight),
],
),
),
);
final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position;
verifyPaintPosition(key1, Offset.zero, true);
verifyPaintPosition(key2, const Offset(0.0, 1000.0), false);
verifyPaintPosition(key3, const Offset(0.0, 1200.0), false);
position.animateTo(bigHeight - 600.0 + delegate.maxExtent, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 1000));
verifyPaintPosition(key1, Offset.zero, true);
verifyPaintPosition(key2, Offset(0.0, 600.0 - delegate.maxExtent), true);
verifyActualBoxPosition(tester, find.byType(Container), 0, Rect.fromLTWH(0.0, 600.0 - delegate.maxExtent, 800.0, delegate.maxExtent));
verifyPaintPosition(key3, const Offset(0.0, 600.0), false);
assert(delegate.maxExtent * 2.0 < 600.0); // make sure this fits on the test screen...
position.animateTo(bigHeight - 600.0 + delegate.maxExtent * 2.0, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 1000));
verifyPaintPosition(key1, Offset.zero, true);
verifyPaintPosition(key2, Offset(0.0, 600.0 - delegate.maxExtent * 2.0), true);
verifyActualBoxPosition(tester, find.byType(Container), 0, Rect.fromLTWH(0.0, 600.0 - delegate.maxExtent * 2.0, 800.0, delegate.maxExtent));
verifyPaintPosition(key3, Offset(0.0, 600.0 - delegate.maxExtent), true);
position.animateTo(bigHeight, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 1000));
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, true);
verifyActualBoxPosition(tester, find.byType(Container), 0, Rect.fromLTWH(0.0, 0.0, 800.0, delegate.maxExtent));
verifyPaintPosition(key3, Offset(0.0, delegate.maxExtent), true);
position.animateTo(bigHeight + delegate.maxExtent * 0.1, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 1000));
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, true);
verifyActualBoxPosition(tester, find.byType(Container), 0, Rect.fromLTWH(0.0, 0.0, 800.0, delegate.maxExtent * 0.9));
verifyPaintPosition(key3, Offset(0.0, delegate.maxExtent * 0.9), true);
position.animateTo(bigHeight + delegate.maxExtent * 0.5, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 1000));
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, true);
verifyActualBoxPosition(tester, find.byType(Container), 0, Rect.fromLTWH(0.0, 0.0, 800.0, delegate.maxExtent * 0.5));
verifyPaintPosition(key3, Offset(0.0, delegate.maxExtent * 0.5), true);
position.animateTo(bigHeight + delegate.maxExtent * 0.9, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 1000));
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, true);
verifyActualBoxPosition(tester, find.byType(Container), 0, Rect.fromLTWH(0.0, -delegate.maxExtent * 0.4, 800.0, delegate.maxExtent * 0.5));
verifyPaintPosition(key3, Offset(0.0, delegate.maxExtent * 0.1), true);
position.animateTo(bigHeight + delegate.maxExtent * 2.0, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 1000));
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, false);
verifyPaintPosition(key3, Offset.zero, true);
});
testWidgets('Sliver appbars - floating - no floating behavior when animating', (WidgetTester tester) async {
final TestDelegate delegate = TestDelegate();
const double bigHeight = 1000.0;
GlobalKey key1, key2, key3;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
slivers: <Widget>[
BigSliver(key: key1 = GlobalKey(), height: bigHeight),
SliverPersistentHeader(key: key2 = GlobalKey(), delegate: delegate, floating: true),
BigSliver(key: key3 = GlobalKey(), height: bigHeight),
],
),
),
);
final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position;
verifyPaintPosition(key1, Offset.zero, true);
verifyPaintPosition(key2, const Offset(0.0, 1000.0), false);
verifyPaintPosition(key3, const Offset(0.0, 1200.0), false);
position.animateTo(bigHeight + delegate.maxExtent * 2.0, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 1000));
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, false);
verifyPaintPosition(key3, Offset.zero, true);
position.animateTo(bigHeight + delegate.maxExtent * 1.9, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 1000));
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, false);
verifyPaintPosition(key3, Offset.zero, true);
});
testWidgets('Sliver appbars - floating - floating behavior when dragging down', (WidgetTester tester) async {
final TestDelegate delegate = TestDelegate();
const double bigHeight = 1000.0;
GlobalKey key1, key2, key3;
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
slivers: <Widget>[
BigSliver(key: key1 = GlobalKey(), height: bigHeight),
SliverPersistentHeader(key: key2 = GlobalKey(), delegate: delegate, floating: true),
BigSliver(key: key3 = GlobalKey(), height: bigHeight),
],
),
),
);
final ScrollPositionWithSingleContext position = tester.state<ScrollableState>(find.byType(Scrollable)).position as ScrollPositionWithSingleContext;
verifyPaintPosition(key1, Offset.zero, true);
verifyPaintPosition(key2, const Offset(0.0, 1000.0), false);
verifyPaintPosition(key3, const Offset(0.0, 1200.0), false);
position.animateTo(bigHeight + delegate.maxExtent * 2.0, curve: Curves.linear, duration: const Duration(minutes: 1));
await tester.pumpAndSettle(const Duration(milliseconds: 1000));
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, false);
verifyPaintPosition(key3, Offset.zero, true);
position.animateTo(bigHeight + delegate.maxExtent * 1.9, curve: Curves.linear, duration: const Duration(minutes: 1));
position.updateUserScrollDirection(ScrollDirection.forward);
await tester.pumpAndSettle(const Duration(milliseconds: 1000));
verifyPaintPosition(key1, Offset.zero, false);
verifyPaintPosition(key2, Offset.zero, true);
verifyActualBoxPosition(tester, find.byType(Container), 0, Rect.fromLTWH(0.0, -delegate.maxExtent * 0.4, 800.0, delegate.maxExtent * 0.5));
verifyPaintPosition(key3, Offset.zero, true);
});
testWidgets('Sliver appbars - floating - overscroll gap is below header', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: CustomScrollView(
physics: const BouncingScrollPhysics(),
slivers: <Widget>[
SliverPersistentHeader(delegate: TestDelegate(), floating: true),
SliverList(
delegate: SliverChildListDelegate(<Widget>[
const SizedBox(
height: 300.0,
child: Text('X'),
),
]),
),
],
),
),
);
expect(tester.getTopLeft(find.byType(Container)), Offset.zero);
expect(tester.getTopLeft(find.text('X')), const Offset(0.0, 200.0));
final ScrollPosition position = tester.state<ScrollableState>(find.byType(Scrollable)).position;
position.jumpTo(-50.0);
await tester.pump();
expect(tester.getTopLeft(find.byType(Container)), Offset.zero);
expect(tester.getTopLeft(find.text('X')), const Offset(0.0, 250.0));
});
group('Pointer scrolled floating', () {
Widget buildTest(Widget sliver) {
return MaterialApp(
home: CustomScrollView(
slivers: <Widget>[
sliver,
SliverFixedExtentList(
itemExtent: 50.0,
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) => Text('Item $index'),
childCount: 30,
)
),
],
),
);
}
void verifyGeometry({
required GlobalKey key,
required bool visible,
required double paintExtent
}) {
final RenderSliver target = key.currentContext!.findRenderObject()! as RenderSliver;
final SliverGeometry geometry = target.geometry!;
expect(geometry.visible, visible);
expect(geometry.paintExtent, paintExtent);
}
testWidgets('SliverAppBar', (WidgetTester tester) async {
final GlobalKey appBarKey = GlobalKey();
await tester.pumpWidget(buildTest(SliverAppBar(
key: appBarKey,
floating: true,
title: const Text('Test Title'),
)));
expect(find.text('Test Title'), findsOneWidget);
expect(find.text('Item 1'), findsOneWidget);
expect(find.text('Item 5'), findsOneWidget);
expect(
tester.renderObject<RenderBox>(find.byType(AppBar)).size.height,
56.0,
);
verifyGeometry(key: appBarKey, visible: true, paintExtent: 56.0);
// Pointer scroll the app bar away, we will scroll back less to validate the
// app bar floats back in.
final Offset point1 = tester.getCenter(find.text('Item 5'));
final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse);
testPointer.hover(point1);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 300.0)));
await tester.pump();
expect(find.text('Test Title'), findsNothing);
expect(find.text('Item 1'), findsNothing);
expect(find.text('Item 5'), findsOneWidget);
verifyGeometry(key: appBarKey, paintExtent: 0.0, visible: false);
// Scroll back to float in appbar
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -50.0)));
await tester.pump();
expect(find.text('Test Title'), findsOneWidget);
expect(find.text('Item 1'), findsNothing);
expect(find.text('Item 5'), findsOneWidget);
expect(
tester.renderObject<RenderBox>(find.byType(AppBar)).size.height,
56.0,
);
verifyGeometry(key: appBarKey, paintExtent: 50.0, visible: true);
// Float the rest of the way in.
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -250.0)));
await tester.pump();
expect(find.text('Test Title'), findsOneWidget);
expect(find.text('Item 1'), findsOneWidget);
expect(find.text('Item 5'), findsOneWidget);
expect(
tester.renderObject<RenderBox>(find.byType(AppBar)).size.height,
56.0,
);
verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true);
});
testWidgets('SliverPersistentHeader', (WidgetTester tester) async {
final GlobalKey headerKey = GlobalKey();
await tester.pumpWidget(buildTest(SliverPersistentHeader(
key: headerKey,
floating: true,
delegate: HeaderDelegate(),
)));
expect(find.text('Test Title'), findsOneWidget);
expect(find.text('Item 1'), findsOneWidget);
expect(find.text('Item 5'), findsOneWidget);
verifyGeometry(key: headerKey, visible: true, paintExtent: 56.0);
// Pointer scroll the app bar away, we will scroll back less to validate the
// app bar floats back in.
final Offset point1 = tester.getCenter(find.text('Item 5'));
final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse);
testPointer.hover(point1);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 300.0)));
await tester.pump();
expect(find.text('Test Title'), findsNothing);
expect(find.text('Item 1'), findsNothing);
expect(find.text('Item 5'), findsOneWidget);
verifyGeometry(key: headerKey, paintExtent: 0.0, visible: false);
// Scroll back to float in appbar
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -50.0)));
await tester.pump();
expect(find.text('Test Title'), findsOneWidget);
expect(find.text('Item 1'), findsNothing);
expect(find.text('Item 5'), findsOneWidget);
verifyGeometry(key: headerKey, paintExtent: 50.0, visible: true);
// Float the rest of the way in.
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -250.0)));
await tester.pump();
expect(find.text('Test Title'), findsOneWidget);
expect(find.text('Item 1'), findsOneWidget);
expect(find.text('Item 5'), findsOneWidget);
verifyGeometry(key: headerKey, paintExtent: 56.0, visible: true);
});
testWidgets('and snapping SliverAppBar', (WidgetTester tester) async {
final GlobalKey appBarKey = GlobalKey();
await tester.pumpWidget(buildTest(SliverAppBar(
key: appBarKey,
floating: true,
snap: true,
title: const Text('Test Title'),
)));
expect(find.text('Test Title'), findsOneWidget);
expect(find.text('Item 1'), findsOneWidget);
expect(find.text('Item 5'), findsOneWidget);
expect(
tester.renderObject<RenderBox>(find.byType(AppBar)).size.height,
56.0,
);
verifyGeometry(key: appBarKey, visible: true, paintExtent: 56.0);
// Pointer scroll the app bar away, we will scroll back less to validate the
// app bar floats back in and then snaps to full size.
final Offset point1 = tester.getCenter(find.text('Item 5'));
final TestPointer testPointer = TestPointer(1, ui.PointerDeviceKind.mouse);
testPointer.hover(point1);
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 300.0)));
await tester.pump();
expect(find.text('Test Title'), findsNothing);
expect(find.text('Item 1'), findsNothing);
expect(find.text('Item 5'), findsOneWidget);
verifyGeometry(key: appBarKey, paintExtent: 0.0, visible: false);
// Scroll back to float in appbar
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, -30.0)));
await tester.pump();
expect(find.text('Test Title'), findsOneWidget);
expect(find.text('Item 1'), findsNothing);
expect(find.text('Item 5'), findsOneWidget);
expect(
tester.renderObject<RenderBox>(find.byType(AppBar)).size.height,
56.0,
);
verifyGeometry(key: appBarKey, paintExtent: 30.0, visible: true);
await tester.pumpAndSettle();
// The snap animation should have completed and the app bar should be
// fully expanded.
expect(find.text('Test Title'), findsOneWidget);
expect(find.text('Item 1'), findsNothing);
expect(find.text('Item 5'), findsOneWidget);
expect(
tester.renderObject<RenderBox>(find.byType(AppBar)).size.height,
56.0,
);
verifyGeometry(key: appBarKey, paintExtent: 56.0, visible: true);
// Float back out a bit and trigger snap close animation.
await tester.sendEventToBinding(testPointer.scroll(const Offset(0.0, 50.0)));
await tester.pump();
expect(find.text('Test Title'), findsOneWidget);
expect(find.text('Item 1'), findsNothing);
expect(find.text('Item 5'), findsOneWidget);
expect(
tester.renderObject<RenderBox>(find.byType(AppBar)).size.height,
56.0,
);
verifyGeometry(key: appBarKey, paintExtent: 6.0, visible: true);
await tester.pumpAndSettle();
// The snap animation should have completed and the app bar should no
// longer be visible.
expect(find.text('Test Title'), findsNothing);
expect(find.text('Item 1'), findsNothing);
expect(find.text('Item 5'), findsOneWidget);
expect(
find.byType(AppBar),
findsNothing,
);
verifyGeometry(key: appBarKey, paintExtent: 0.0, visible: false);
});
});
}
class HeaderDelegate extends SliverPersistentHeaderDelegate {
@override
Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
return Container(
height: 56,
color: Colors.red,
child: const Text('Test Title'),
);
}
@override
double get maxExtent => 56;
@override
double get minExtent => 56;
@override
bool shouldRebuild(SliverPersistentHeaderDelegate oldDelegate) => false;
}
class TestDelegate extends SliverPersistentHeaderDelegate {
@override
double get maxExtent => 200.0;
@override
double get minExtent => 100.0;
@override
Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
return Container(constraints: BoxConstraints(minHeight: minExtent, maxHeight: maxExtent));
}
@override
bool shouldRebuild(TestDelegate oldDelegate) => false;
}
class RenderBigSliver extends RenderSliver {
RenderBigSliver(double height) : _height = height;
double get height => _height;
double _height;
set height(double value) {
if (value == _height) {
return;
}
_height = value;
markNeedsLayout();
}
double get paintExtent => (height - constraints.scrollOffset).clamp(0.0, constraints.remainingPaintExtent);
@override
void performLayout() {
geometry = SliverGeometry(
scrollExtent: height,
paintExtent: paintExtent,
maxPaintExtent: height,
);
}
}
class BigSliver extends LeafRenderObjectWidget {
const BigSliver({ super.key, required this.height });
final double height;
@override
RenderBigSliver createRenderObject(BuildContext context) {
return RenderBigSliver(height);
}
@override
void updateRenderObject(BuildContext context, RenderBigSliver renderObject) {
renderObject.height = height;
}
}
| flutter/packages/flutter/test/widgets/slivers_appbar_floating_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/slivers_appbar_floating_test.dart",
"repo_id": "flutter",
"token_count": 8124
} | 699 |
// 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';
class Foo extends StatefulWidget {
const Foo({ super.key });
@override
FooState createState() => FooState();
}
class FooState extends State<Foo> {
final ScrollController scrollController = ScrollController();
@override
void dispose() {
scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return ScrollConfiguration(
behavior: const FooScrollBehavior(),
child: ListView(
controller: scrollController,
children: <Widget>[
GestureDetector(
onTap: () {
setState(() { /* this is needed to trigger the original bug this is regression-testing */ });
scrollController.animateTo(200.0, duration: const Duration(milliseconds: 500), curve: Curves.linear);
},
child: const DecoratedBox(
decoration: BoxDecoration(color: Color(0x00000000)),
child: SizedBox(
height: 200.0,
),
),
),
const DecoratedBox(
decoration: BoxDecoration(color: Color(0x00000000)),
child: SizedBox(
height: 200.0,
),
),
const DecoratedBox(
decoration: BoxDecoration(color: Color(0x00000000)),
child: SizedBox(
height: 200.0,
),
),
const DecoratedBox(
decoration: BoxDecoration(color: Color(0x00000000)),
child: SizedBox(
height: 200.0,
),
),
const DecoratedBox(
decoration: BoxDecoration(color: Color(0x00000000)),
child: SizedBox(
height: 200.0,
),
),
const DecoratedBox(
decoration: BoxDecoration(color: Color(0x00000000)),
child: SizedBox(
height: 200.0,
),
),
],
),
);
},
);
}
}
class FooScrollBehavior extends ScrollBehavior {
const FooScrollBehavior();
@override
bool shouldNotify(FooScrollBehavior old) => true;
}
void main() {
testWidgets('Can animate scroll after setState', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Foo(),
),
);
expect(tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels, 0.0);
await tester.tap(find.byType(GestureDetector).first);
await tester.pumpAndSettle();
expect(tester.state<ScrollableState>(find.byType(Scrollable)).position.pixels, 200.0);
});
}
| flutter/packages/flutter/test/widgets/state_setting_in_scrollables_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/state_setting_in_scrollables_test.dart",
"repo_id": "flutter",
"token_count": 1522
} | 700 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:ui' as ui;
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'semantics_tester.dart';
void main() {
testWidgets('Text respects media query', (WidgetTester tester) async {
await tester.pumpWidget(MediaQuery.withClampedTextScaling(
minScaleFactor: 1.3,
maxScaleFactor: 1.3,
child: const Center(
child: Text('Hello', textDirection: TextDirection.ltr),
),
));
RichText text = tester.firstWidget(find.byType(RichText));
expect(text, isNotNull);
expect(text.textScaler, const TextScaler.linear(1.3));
await tester.pumpWidget(const Center(
child: Text('Hello', textDirection: TextDirection.ltr),
));
text = tester.firstWidget(find.byType(RichText));
expect(text, isNotNull);
expect(text.textScaler, TextScaler.noScaling);
});
testWidgets('Text respects textScaleFactor with default font size', (WidgetTester tester) async {
await tester.pumpWidget(
const Center(child: Text('Hello', textDirection: TextDirection.ltr)),
);
RichText text = tester.firstWidget(find.byType(RichText));
expect(text, isNotNull);
expect(text.textScaler, TextScaler.noScaling);
final Size baseSize = tester.getSize(find.byType(RichText));
expect(baseSize.width, equals(70.0));
expect(baseSize.height, equals(14.0));
await tester.pumpWidget(const Center(
child: Text(
'Hello',
textScaleFactor: 1.5,
textDirection: TextDirection.ltr,
),
));
text = tester.firstWidget(find.byType(RichText));
expect(text, isNotNull);
expect(text.textScaler, const TextScaler.linear(1.5));
final Size largeSize = tester.getSize(find.byType(RichText));
expect(largeSize.width, 105.0);
expect(largeSize.height, equals(21.0));
});
testWidgets('Text respects textScaleFactor with explicit font size', (WidgetTester tester) async {
await tester.pumpWidget(const Center(
child: Text(
'Hello',
style: TextStyle(fontSize: 20.0),
textDirection: TextDirection.ltr,
),
));
RichText text = tester.firstWidget(find.byType(RichText));
expect(text, isNotNull);
expect(text.textScaler, TextScaler.noScaling);
final Size baseSize = tester.getSize(find.byType(RichText));
expect(baseSize.width, equals(100.0));
expect(baseSize.height, equals(20.0));
await tester.pumpWidget(const Center(
child: Text(
'Hello',
style: TextStyle(fontSize: 20.0),
textScaleFactor: 1.3,
textDirection: TextDirection.ltr,
),
));
text = tester.firstWidget(find.byType(RichText));
expect(text, isNotNull);
expect(text.textScaler, const TextScaler.linear(1.3));
final Size largeSize = tester.getSize(find.byType(RichText));
expect(largeSize.width, 130.0);
expect(largeSize.height, equals(26.0));
});
testWidgets("Text throws a nice error message if there's no Directionality", (WidgetTester tester) async {
await tester.pumpWidget(const Text('Hello'));
final String message = tester.takeException().toString();
expect(message, contains('Directionality'));
expect(message, contains(' Text '));
});
testWidgets('Text can be created from TextSpans and uses defaultTextStyle', (WidgetTester tester) async {
await tester.pumpWidget(
const DefaultTextStyle(
style: TextStyle(
fontSize: 20.0,
),
child: Text.rich(
TextSpan(
text: 'Hello',
children: <TextSpan>[
TextSpan(
text: ' beautiful ',
style: TextStyle(fontStyle: FontStyle.italic),
),
TextSpan(
text: 'world',
style: TextStyle(fontWeight: FontWeight.bold),
),
],
),
textDirection: TextDirection.ltr,
),
),
);
final RichText text = tester.firstWidget(find.byType(RichText));
expect(text, isNotNull);
expect(text.text.style!.fontSize, 20.0);
});
testWidgets('inline widgets works with ellipsis', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/35869
const TextStyle textStyle = TextStyle();
await tester.pumpWidget(
Text.rich(
TextSpan(
children: <InlineSpan>[
const TextSpan(
text: 'a very very very very very very very very very very long line',
),
WidgetSpan(
child: SizedBox(
width: 20,
height: 40,
child: Card(
child: RichText(
text: const TextSpan(text: 'widget should be truncated'),
textDirection: TextDirection.rtl,
),
),
),
),
],
style: textStyle,
),
textDirection: TextDirection.ltr,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
);
expect(tester.takeException(), null);
});
testWidgets('inline widgets hitTest works with ellipsis', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/68559
const TextStyle textStyle = TextStyle();
await tester.pumpWidget(
Text.rich(
TextSpan(
children: <InlineSpan>[
const TextSpan(
text: 'a very very very very very very very very very very long line',
),
WidgetSpan(
child: SizedBox(
width: 20,
height: 40,
child: Card(
child: RichText(
text: const TextSpan(text: 'widget should be truncated'),
textDirection: TextDirection.rtl,
),
),
),
),
],
style: textStyle,
),
textDirection: TextDirection.ltr,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
);
await tester.tap(find.byType(Text));
expect(tester.takeException(), null);
});
testWidgets('inline widgets works with textScaleFactor', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/59316
final UniqueKey key = UniqueKey();
double textScaleFactor = 1.0;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
appBar: AppBar(title: const Text('title')),
body: Center(
child: Text.rich(
TextSpan(
children: <InlineSpan>[
WidgetSpan(
child: RichText(
text: const TextSpan(text: 'widget should be truncated'),
textDirection: TextDirection.ltr,
),
),
],
),
key: key,
textDirection: TextDirection.ltr,
textScaleFactor: textScaleFactor,
),
),
),
),
);
RenderBox renderText = tester.renderObject(find.byKey(key));
final double singleLineHeight = renderText.size.height;
// Now, increases the text scale factor by 5 times.
textScaleFactor = textScaleFactor * 5;
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
appBar: AppBar(title: const Text('title')),
body: Center(
child: Text.rich(
TextSpan(
children: <InlineSpan>[
WidgetSpan(
child: RichText(
text: const TextSpan(text: 'widget should be truncated'),
textDirection: TextDirection.ltr,
),
),
],
),
key: key,
textDirection: TextDirection.ltr,
textScaleFactor: textScaleFactor,
),
),
),
),
);
renderText = tester.renderObject(find.byKey(key));
// The RichText in the widget span should wrap into three lines.
expect(renderText.size.height, singleLineHeight * textScaleFactor * 3);
});
testWidgets("Inline widgets' scaled sizes are constrained", (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/130588
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 502.5454545454545,
child: Text.rich(WidgetSpan(child: Row()), textScaleFactor: 0.95),
),
),
),
);
expect(tester.takeException(), isNull);
});
testWidgets('semanticsLabel can override text label', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
await tester.pumpWidget(
const Text(
r'$$',
semanticsLabel: 'Double dollars',
textDirection: TextDirection.ltr,
),
);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
label: 'Double dollars',
textDirection: TextDirection.ltr,
),
],
);
expect(
semantics,
hasSemantics(
expectedSemantics,
ignoreTransform: true,
ignoreId: true,
ignoreRect: true,
),
);
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Text(r'$$', semanticsLabel: 'Double dollars'),
),
);
expect(
semantics,
hasSemantics(
expectedSemantics,
ignoreTransform: true,
ignoreId: true,
ignoreRect: true,
),
);
semantics.dispose();
});
testWidgets('semantics label is in order when uses widget span', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Text.rich(
TextSpan(
children: <InlineSpan>[
const TextSpan(text: 'before '),
WidgetSpan(
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
child: Semantics(label: 'foo'),
),
const TextSpan(text: ' after'),
],
),
),
),
);
expect(
tester.getSemantics(find.byType(Text)),
matchesSemantics(label: 'before \nfoo\n after'),
);
// If the Paragraph is not dirty it should use the cache correctly.
final RenderObject parent = tester.renderObject<RenderObject>(find.byType(Directionality));
parent.markNeedsSemanticsUpdate();
await tester.pumpAndSettle();
expect(
tester.getSemantics(find.byType(Text)),
matchesSemantics(label: 'before \nfoo\n after'),
);
});
testWidgets('semantics can handle some widget spans without semantics', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Text.rich(
TextSpan(
children: <InlineSpan>[
const TextSpan(text: 'before '),
const WidgetSpan(
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
child: SizedBox(width: 10.0),
),
const TextSpan(text: ' mid'),
WidgetSpan(
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
child: Semantics(label: 'foo'),
),
const TextSpan(text: ' after'),
const WidgetSpan(
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
child: SizedBox(width: 10.0),
),
],
),
),
),
);
expect(tester.getSemantics(find.byType(Text)),
matchesSemantics(label: 'before \n mid\nfoo\n after'));
// If the Paragraph is not dirty it should use the cache correctly.
final RenderObject parent = tester.renderObject<RenderObject>(find.byType(Directionality));
parent.markNeedsSemanticsUpdate();
await tester.pumpAndSettle();
expect(tester.getSemantics(find.byType(Text)),
matchesSemantics(label: 'before \n mid\nfoo\n after'));
});
testWidgets('semantics can handle all widget spans without semantics', (WidgetTester tester) async {
await tester.pumpWidget(
const Directionality(
textDirection: TextDirection.ltr,
child: Text.rich(
TextSpan(
children: <InlineSpan>[
TextSpan(text: 'before '),
WidgetSpan(
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
child: SizedBox(width: 10.0),
),
TextSpan(text: ' mid'),
WidgetSpan(
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
child: SizedBox(width: 10.0),
),
TextSpan(text: ' after'),
WidgetSpan(
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
child: SizedBox(width: 10.0),
),
],
),
),
),
);
expect(tester.getSemantics(find.byType(Text)),
matchesSemantics(label: 'before \n mid\n after'));
// If the Paragraph is not dirty it should use the cache correctly.
final RenderObject parent = tester.renderObject<RenderObject>(find.byType(Directionality));
parent.markNeedsSemanticsUpdate();
await tester.pumpAndSettle();
expect(tester.getSemantics(find.byType(Text)),
matchesSemantics(label: 'before \n mid\n after'));
});
testWidgets('semantics can handle widget spans with explicit semantics node', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Text.rich(
TextSpan(
children: <InlineSpan>[
const TextSpan(text: 'before '),
WidgetSpan(
alignment: PlaceholderAlignment.baseline,
baseline: TextBaseline.alphabetic,
child: Semantics(label: 'inner', container: true),
),
const TextSpan(text: ' after'),
],
),
),
),
);
expect(
tester.getSemantics(find.byType(Text)),
matchesSemantics(label: 'before \n after', children: <Matcher>[matchesSemantics(label: 'inner')]),
);
// If the Paragraph is not dirty it should use the cache correctly.
final RenderObject parent = tester.renderObject<RenderObject>(find.byType(Directionality));
parent.markNeedsSemanticsUpdate();
await tester.pumpAndSettle();
expect(
tester.getSemantics(find.byType(Text)),
matchesSemantics(label: 'before \n after', children: <Matcher>[matchesSemantics(label: 'inner')]),
);
});
testWidgets('semanticsLabel can be shorter than text', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final TapGestureRecognizer recognizer = TapGestureRecognizer();
addTearDown(recognizer.dispose);
await tester.pumpWidget(Directionality(
textDirection: TextDirection.ltr,
child: RichText(
text: TextSpan(
children: <InlineSpan>[
const TextSpan(
text: 'Some Text',
semanticsLabel: '',
),
TextSpan(
text: 'Clickable',
recognizer: recognizer..onTap = () { },
),
],
),
),
));
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'Clickable',
actions: <SemanticsAction>[SemanticsAction.tap],
flags: <SemanticsFlag>[SemanticsFlag.isLink],
textDirection: TextDirection.ltr,
),
],
),
],
);
expect(
semantics,
hasSemantics(
expectedSemantics,
ignoreTransform: true,
ignoreId: true,
ignoreRect: true,
),
);
semantics.dispose();
});
testWidgets('recognizers split semantic node', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
const TextStyle textStyle = TextStyle();
final TapGestureRecognizer recognizer = TapGestureRecognizer();
addTearDown(recognizer.dispose);
await tester.pumpWidget(
Text.rich(
TextSpan(
children: <TextSpan>[
const TextSpan(text: 'hello '),
TextSpan(
text: 'world',
recognizer: recognizer..onTap = () { },
),
const TextSpan(text: ' this is a '),
const TextSpan(text: 'cat-astrophe'),
],
style: textStyle,
),
textDirection: TextDirection.ltr,
),
);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
children: <TestSemantics>[
TestSemantics(
label: 'hello ',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'world',
textDirection: TextDirection.ltr,
actions: <SemanticsAction>[SemanticsAction.tap],
flags: <SemanticsFlag>[SemanticsFlag.isLink],
),
TestSemantics(
label: ' this is a cat-astrophe',
textDirection: TextDirection.ltr,
),
],
),
],
);
expect(
semantics,
hasSemantics(
expectedSemantics,
ignoreTransform: true,
ignoreId: true,
ignoreRect: true,
),
);
semantics.dispose();
});
testWidgets('semantic nodes of offscreen recognizers are marked hidden', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/100395.
final SemanticsTester semantics = SemanticsTester(tester);
const TextStyle textStyle = TextStyle(fontSize: 200);
const String onScreenText = 'onscreen\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n';
const String offScreenText = 'off screen';
final ScrollController controller = ScrollController();
addTearDown(controller.dispose);
final TapGestureRecognizer recognizer = TapGestureRecognizer();
addTearDown(recognizer.dispose);
await tester.pumpWidget(
SingleChildScrollView(
controller: controller,
child: Text.rich(
TextSpan(
children: <TextSpan>[
const TextSpan(text: onScreenText),
TextSpan(
text: offScreenText,
recognizer: recognizer..onTap = () { },
),
],
style: textStyle,
),
textDirection: TextDirection.ltr,
),
),
);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
flags: <SemanticsFlag>[SemanticsFlag.hasImplicitScrolling],
actions: <SemanticsAction>[SemanticsAction.scrollUp],
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(
label: onScreenText,
textDirection: TextDirection.ltr,
),
TestSemantics(
label: offScreenText,
textDirection: TextDirection.ltr,
actions: <SemanticsAction>[SemanticsAction.tap],
flags: <SemanticsFlag>[SemanticsFlag.isLink, SemanticsFlag.isHidden],
),
],
),
],
),
],
);
expect(
semantics,
hasSemantics(
expectedSemantics,
ignoreTransform: true,
ignoreId: true,
ignoreRect: true,
),
);
// Test show on screen.
expect(controller.offset, 0.0);
tester.binding.pipelineOwner.semanticsOwner!.performAction(4, SemanticsAction.showOnScreen);
await tester.pumpAndSettle();
expect(controller.offset != 0.0, isTrue);
semantics.dispose();
});
testWidgets('recognizers split semantic node when TextSpan overflows', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
const TextStyle textStyle = TextStyle();
final TapGestureRecognizer recognizer = TapGestureRecognizer();
addTearDown(recognizer.dispose);
await tester.pumpWidget(
SizedBox(
height: 10,
child: Text.rich(
TextSpan(
children: <TextSpan>[
const TextSpan(text: '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n'),
TextSpan(
text: 'world',
recognizer: recognizer..onTap = () { },
),
],
style: textStyle,
),
textDirection: TextDirection.ltr,
),
),
);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
children: <TestSemantics>[
TestSemantics(
label: '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'world',
textDirection: TextDirection.ltr,
actions: <SemanticsAction>[SemanticsAction.tap],
flags: <SemanticsFlag>[SemanticsFlag.isLink],
),
],
),
],
);
expect(
semantics,
hasSemantics(
expectedSemantics,
ignoreTransform: true,
ignoreId: true,
ignoreRect: true,
),
);
semantics.dispose();
});
testWidgets('recognizers split semantic nodes with text span labels', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
const TextStyle textStyle = TextStyle();
final TapGestureRecognizer recognizer = TapGestureRecognizer();
addTearDown(recognizer.dispose);
await tester.pumpWidget(
Text.rich(
TextSpan(
children: <TextSpan>[
const TextSpan(text: 'hello '),
TextSpan(
text: 'world',
recognizer: recognizer..onTap = () { },
),
const TextSpan(text: ' this is a '),
const TextSpan(
text: 'cat-astrophe',
semanticsLabel: 'regrettable event',
),
],
style: textStyle,
),
textDirection: TextDirection.ltr,
),
);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
children: <TestSemantics>[
TestSemantics(
label: 'hello ',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'world',
textDirection: TextDirection.ltr,
actions: <SemanticsAction>[SemanticsAction.tap],
flags: <SemanticsFlag>[SemanticsFlag.isLink],
),
TestSemantics(
label: ' this is a regrettable event',
textDirection: TextDirection.ltr,
),
],
),
],
);
expect(
semantics,
hasSemantics(
expectedSemantics,
ignoreTransform: true,
ignoreId: true,
ignoreRect: true,
),
);
semantics.dispose();
});
testWidgets('recognizers split semantic node - bidi', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
const TextStyle textStyle = TextStyle();
final LongPressGestureRecognizer recognizer1 = LongPressGestureRecognizer();
addTearDown(recognizer1.dispose);
final TapGestureRecognizer recognizer2 = TapGestureRecognizer();
addTearDown(recognizer2.dispose);
await tester.pumpWidget(
RichText(
text: TextSpan(
style: textStyle,
children: <TextSpan>[
const TextSpan(text: 'hello world${Unicode.RLE}${Unicode.RLO} '),
TextSpan(
text: 'BOY',
recognizer: recognizer1..onLongPress = () { },
),
const TextSpan(text: ' HOW DO${Unicode.PDF} you ${Unicode.RLO} DO '),
TextSpan(
text: 'SIR',
recognizer: recognizer2..onTap = () { },
),
const TextSpan(text: '${Unicode.PDF}${Unicode.PDF} good bye'),
],
),
textDirection: TextDirection.ltr,
),
);
// The expected visual order of the text is:
// hello world RIS OD you OD WOH YOB good bye
// There are five unique text areas, they are, in visual order but
// showing the logical text:
// [hello world][SIR][HOW DO you DO][BOY][good bye]
// The direction of each varies based on the first bit of that area.
// The presence of the bidi formatting characters in the text is a
// bit dubious, but that's what we do currently, and it's not really
// clear what the perfect behavior would be...
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0),
children: <TestSemantics>[
TestSemantics(
rect: const Rect.fromLTRB(-4.0, -4.0, 480.0, 18.0),
label: 'hello world${Unicode.RLE}${Unicode.RLO} ',
textDirection: TextDirection.ltr,
),
TestSemantics(
rect: const Rect.fromLTRB(416.0, -4.0, 466.0, 18.0),
label: 'BOY',
textDirection: TextDirection.rtl,
actions: <SemanticsAction>[SemanticsAction.longPress],
),
TestSemantics(
rect: const Rect.fromLTRB(192.0, -4.0, 424.0, 18.0),
label: ' HOW DO${Unicode.PDF} you ${Unicode.RLO} DO ',
textDirection: TextDirection.rtl,
),
TestSemantics(
rect: const Rect.fromLTRB(150.0, -4.0, 200.0, 18.0),
label: 'SIR',
textDirection: TextDirection.rtl,
actions: <SemanticsAction>[SemanticsAction.tap],
flags: <SemanticsFlag>[SemanticsFlag.isLink],
),
TestSemantics(
rect: const Rect.fromLTRB(472.0, -4.0, 606.0, 18.0),
label: '${Unicode.PDF}${Unicode.PDF} good bye',
textDirection: TextDirection.rtl,
),
],
),
],
);
expect(
semantics,
hasSemantics(
expectedSemantics,
ignoreTransform: true,
ignoreId: true,
),
);
semantics.dispose();
}, skip: isBrowser); // https://github.com/flutter/flutter/issues/62945
testWidgets('TapGesture recognizers contribute link semantics', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
const TextStyle textStyle = TextStyle();
final TapGestureRecognizer recognizer = TapGestureRecognizer();
addTearDown(recognizer.dispose);
await tester.pumpWidget(
Text.rich(
TextSpan(
children: <TextSpan>[
TextSpan(
text: 'click me',
recognizer: recognizer..onTap = () { },
),
],
style: textStyle,
),
textDirection: TextDirection.ltr,
),
);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
children: <TestSemantics>[
TestSemantics(
label: 'click me',
textDirection: TextDirection.ltr,
actions: <SemanticsAction>[SemanticsAction.tap],
flags: <SemanticsFlag>[SemanticsFlag.isLink],
),
],
),
],
);
expect(semantics, hasSemantics(
expectedSemantics,
ignoreTransform: true,
ignoreId: true,
ignoreRect: true,
));
semantics.dispose();
});
testWidgets('inline widgets generate semantic nodes', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
const TextStyle textStyle = TextStyle();
final TapGestureRecognizer recognizer = TapGestureRecognizer();
addTearDown(recognizer.dispose);
await tester.pumpWidget(
Text.rich(
TextSpan(
children: <InlineSpan>[
const TextSpan(text: 'a '),
TextSpan(
text: 'pebble',
recognizer: recognizer..onTap = () { },
),
const TextSpan(text: ' in the '),
WidgetSpan(
child: SizedBox(
width: 20,
height: 40,
child: Card(
child: RichText(
text: const TextSpan(text: 'INTERRUPTION'),
textDirection: TextDirection.rtl,
),
),
),
),
const TextSpan(text: 'sky'),
],
style: textStyle,
),
textDirection: TextDirection.ltr,
),
);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
children: <TestSemantics>[
TestSemantics(
label: 'a ',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'pebble',
textDirection: TextDirection.ltr,
actions: <SemanticsAction>[SemanticsAction.tap],
flags: <SemanticsFlag>[SemanticsFlag.isLink],
),
TestSemantics(
label: ' in the ',
textDirection: TextDirection.ltr,
),
TestSemantics(
label: 'INTERRUPTION',
textDirection: TextDirection.rtl,
),
TestSemantics(
label: 'sky',
textDirection: TextDirection.ltr,
),
],
),
],
);
expect(
semantics,
hasSemantics(
expectedSemantics,
ignoreTransform: true,
ignoreId: true,
ignoreRect: true,
),
);
semantics.dispose();
}, skip: isBrowser); // https://github.com/flutter/flutter/issues/62945
testWidgets('inline widgets semantic nodes scale', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
const TextStyle textStyle = TextStyle();
final TapGestureRecognizer recognizer = TapGestureRecognizer();
addTearDown(recognizer.dispose);
await tester.pumpWidget(
Text.rich(
TextSpan(
children: <InlineSpan>[
const TextSpan(text: 'a '),
TextSpan(
text: 'pebble',
recognizer: recognizer..onTap = () { },
),
const TextSpan(text: ' in the '),
WidgetSpan(
child: SizedBox(
width: 20,
height: 40,
child: Card(
child: RichText(
text: const TextSpan(text: 'INTERRUPTION'),
textDirection: TextDirection.rtl,
),
),
),
),
const TextSpan(text: 'sky'),
],
style: textStyle,
),
textDirection: TextDirection.ltr,
textScaleFactor: 2,
),
);
final TestSemantics expectedSemantics = TestSemantics.root(
children: <TestSemantics>[
TestSemantics.rootChild(
rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0),
children: <TestSemantics>[
TestSemantics(
label: 'a ',
textDirection: TextDirection.ltr,
rect: const Rect.fromLTRB(-4.0, 48.0, 60.0, 84.0),
),
TestSemantics(
label: 'pebble',
textDirection: TextDirection.ltr,
actions: <SemanticsAction>[SemanticsAction.tap],
flags: <SemanticsFlag>[SemanticsFlag.isLink],
rect: const Rect.fromLTRB(52.0, 48.0, 228.0, 84.0),
),
TestSemantics(
label: ' in the ',
textDirection: TextDirection.ltr,
rect: const Rect.fromLTRB(220.0, 48.0, 452.0, 84.0),
),
TestSemantics(
label: 'INTERRUPTION',
textDirection: TextDirection.rtl,
rect: const Rect.fromLTRB(0.0, 0.0, 20.0, 40.0),
),
TestSemantics(
label: 'sky',
textDirection: TextDirection.ltr,
rect: const Rect.fromLTRB(484.0, 48.0, 576.0, 84.0),
),
],
),
],
);
expect(
semantics,
hasSemantics(
expectedSemantics,
ignoreTransform: true,
ignoreId: true,
),
);
semantics.dispose();
}, skip: isBrowser); // https://github.com/flutter/flutter/issues/62945
testWidgets('receives fontFamilyFallback and package from root ThemeData', (WidgetTester tester) async {
const String fontFamily = 'fontFamily';
const String package = 'package_name';
final List<String> fontFamilyFallback = <String>['font', 'family', 'fallback'];
await tester.pumpWidget(
MaterialApp(
theme: ThemeData(
fontFamily: fontFamily,
fontFamilyFallback: fontFamilyFallback,
package: package,
primarySwatch: Colors.blue,
),
home: const Scaffold(
body: Center(
child: Text(
'foo',
),
),
),
),
);
expect(find.byType(RichText), findsOneWidget);
final RichText richText = tester.widget(find.byType(RichText));
final InlineSpan text = richText.text;
final TextStyle? style = text.style;
expect(style?.fontFamily, equals('packages/$package/$fontFamily'));
for (int i = 0; i < fontFamilyFallback.length; i++) {
final String fallback = fontFamilyFallback[i];
expect(style?.fontFamilyFallback?[i], equals('packages/$package/$fallback'));
}
});
testWidgets('Overflow is clipping correctly - short text with overflow: clip', (WidgetTester tester) async {
await _pumpTextWidget(
tester: tester,
overflow: TextOverflow.clip,
text: 'Hi',
);
expect(find.byType(Text), isNot(paints..clipRect()));
});
testWidgets('Overflow is clipping correctly - long text with overflow: ellipsis', (WidgetTester tester) async {
await _pumpTextWidget(
tester: tester,
overflow: TextOverflow.ellipsis,
text: 'a long long long long text, should be clip',
);
expect(
find.byType(Text),
paints..clipRect(rect: const Rect.fromLTWH(0, 0, 50, 50)),
);
}, skip: isBrowser); // https://github.com/flutter/flutter/issues/87878
testWidgets('Overflow is clipping correctly - short text with overflow: ellipsis', (WidgetTester tester) async {
await _pumpTextWidget(
tester: tester,
overflow: TextOverflow.ellipsis,
text: 'Hi',
);
expect(find.byType(Text), isNot(paints..clipRect()));
});
testWidgets('Overflow is clipping correctly - long text with overflow: fade', (WidgetTester tester) async {
await _pumpTextWidget(
tester: tester,
overflow: TextOverflow.fade,
text: 'a long long long long text, should be clip',
);
expect(
find.byType(Text),
paints..clipRect(rect: const Rect.fromLTWH(0, 0, 50, 50)),
);
});
testWidgets('Overflow is clipping correctly - short text with overflow: fade', (WidgetTester tester) async {
await _pumpTextWidget(
tester: tester,
overflow: TextOverflow.fade,
text: 'Hi',
);
expect(find.byType(Text), isNot(paints..clipRect()));
});
testWidgets('Overflow is clipping correctly - long text with overflow: visible', (WidgetTester tester) async {
await _pumpTextWidget(
tester: tester,
overflow: TextOverflow.visible,
text: 'a long long long long text, should be clip',
);
expect(find.byType(Text), isNot(paints..clipRect()));
});
testWidgets('Overflow is clipping correctly - short text with overflow: visible', (WidgetTester tester) async {
await _pumpTextWidget(
tester: tester,
overflow: TextOverflow.visible,
text: 'Hi',
);
expect(find.byType(Text), isNot(paints..clipRect()));
});
testWidgets('textWidthBasis affects the width of a Text widget', (WidgetTester tester) async {
Future<void> createText(TextWidthBasis textWidthBasis) {
return tester.pumpWidget(
MaterialApp(
theme: ThemeData(useMaterial3: false),
home: Scaffold(
body: Center(
// Each word takes up more than a half of a line. Together they
// wrap onto two lines, but leave a lot of extra space.
child: Text(
'twowordsthateachtakeupmorethanhalfof alineoftextsothattheywrapwithlotsofextraspace',
textDirection: TextDirection.ltr,
textWidthBasis: textWidthBasis,
),
),
),
),
);
}
const double fontHeight = 14.0;
const double screenWidth = 800.0;
// When textWidthBasis is parent, takes up full screen width.
await createText(TextWidthBasis.parent);
final Size textSizeParent = tester.getSize(find.byType(Text));
expect(textSizeParent.width, equals(screenWidth));
expect(textSizeParent.height, equals(fontHeight * 2));
// When textWidthBasis is longestLine, sets the width to as small as
// possible for the two lines.
await createText(TextWidthBasis.longestLine);
final Size textSizeLongestLine = tester.getSize(find.byType(Text));
expect(textSizeLongestLine.width, equals(630.0));
expect(textSizeLongestLine.height, equals(fontHeight * 2));
}, skip: isBrowser); // https://github.com/flutter/flutter/issues/44020
testWidgets('textWidthBasis with textAlign still obeys parent alignment', (WidgetTester tester) async {
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
'LEFT ALIGNED, PARENT',
textAlign: TextAlign.left,
textWidthBasis: TextWidthBasis.parent,
),
Text(
'RIGHT ALIGNED, PARENT',
textAlign: TextAlign.right,
textWidthBasis: TextWidthBasis.parent,
),
Text(
'LEFT ALIGNED, LONGEST LINE',
textAlign: TextAlign.left,
textWidthBasis: TextWidthBasis.longestLine,
),
Text(
'RIGHT ALIGNED, LONGEST LINE',
textAlign: TextAlign.right,
textWidthBasis: TextWidthBasis.longestLine,
),
],
),
),
),
),
);
// All Texts have the same horizontal alignment.
final double offsetX = tester.getTopLeft(find.text('LEFT ALIGNED, PARENT')).dx;
expect(tester.getTopLeft(find.text('RIGHT ALIGNED, PARENT')).dx, equals(offsetX));
expect(tester.getTopLeft(find.text('LEFT ALIGNED, LONGEST LINE')).dx, equals(offsetX));
expect(tester.getTopLeft(find.text('RIGHT ALIGNED, LONGEST LINE')).dx, equals(offsetX));
// All Texts are less than or equal to the width of the Column.
final double width = tester.getSize(find.byType(Column)).width;
expect(tester.getSize(find.text('LEFT ALIGNED, PARENT')).width, lessThan(width));
expect(tester.getSize(find.text('RIGHT ALIGNED, PARENT')).width, lessThan(width));
expect(tester.getSize(find.text('LEFT ALIGNED, LONGEST LINE')).width, lessThan(width));
expect(tester.getSize(find.text('RIGHT ALIGNED, LONGEST LINE')).width, equals(width));
}, skip: isBrowser); // https://github.com/flutter/flutter/issues/44020
testWidgets(
'textWidthBasis.longestLine confines the width of the paragraph '
'when given loose constraints',
(WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/62550.
await tester.pumpWidget(
Center(
child: SizedBox(
width: 400,
child: Center(
child: RichText(
// 400 is not wide enough for this string. The part after the
// whitespace is going to be broken into a 2nd line.
text: const TextSpan(text: 'fwefwefwewfefewfwe fwfwfwefweabcdefghijklmnopqrstuvwxyz'),
textWidthBasis: TextWidthBasis.longestLine,
textDirection: TextDirection.rtl,
),
),
),
),
);
expect(find.byType(RichText), paints..something((Symbol method, List<dynamic> arguments) {
if (method != #drawParagraph) {
return false;
}
final ui.Paragraph paragraph = arguments[0] as ui.Paragraph;
final Offset offset = arguments[1] as Offset;
final List<ui.LineMetrics> lines = paragraph.computeLineMetrics();
for (final ui.LineMetrics line in lines) {
if (line.left + offset.dx + line.width >= 400) {
throw 'line $line is greater than the max width constraints';
}
}
return true;
}));
},
skip: isBrowser, // https://github.com/flutter/flutter/issues/44020
);
testWidgets('Paragraph.getBoxesForRange returns nothing when selection range is zero length', (WidgetTester tester) async {
final ui.ParagraphBuilder builder = ui.ParagraphBuilder(ui.ParagraphStyle());
builder.addText('hello');
final ui.Paragraph paragraph = builder.build();
paragraph.layout(const ui.ParagraphConstraints(width: 1000));
expect(paragraph.getBoxesForRange(2, 2), isEmpty);
paragraph.dispose();
});
// Regression test for https://github.com/flutter/flutter/issues/65818
testWidgets('WidgetSpans with no semantic information are elided from semantics', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final TapGestureRecognizer recognizer = TapGestureRecognizer();
addTearDown(recognizer.dispose);
// Without the fix for this bug the pump widget will throw a RangeError.
await tester.pumpWidget(
RichText(
textDirection: TextDirection.ltr,
text: TextSpan(children: <InlineSpan>[
const WidgetSpan(child: SizedBox.shrink()),
TextSpan(
text: 'HELLO',
style: const TextStyle(color: Colors.black),
recognizer: recognizer..onTap = () {},
),
]),
),
);
expect(semantics, hasSemantics(TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
id: 1,
rect: const Rect.fromLTRB(0.0, 0.0, 800.0, 600.0),
transform: Matrix4(
3.0,0.0,0.0,0.0,
0.0,3.0,0.0,0.0,
0.0,0.0,1.0,0.0,
0.0,0.0,0.0,1.0,
),
children: <TestSemantics>[
TestSemantics(
rect: const Rect.fromLTRB(-4.0, -4.0, 74.0, 18.0),
id: 2,
label: 'HELLO',
actions: <SemanticsAction>[
SemanticsAction.tap,
],
flags: <SemanticsFlag>[
SemanticsFlag.isLink,
],
),
],
),
],
)));
semantics.dispose();
}, skip: isBrowser); // https://github.com/flutter/flutter/issues/87877
// Regression test for https://github.com/flutter/flutter/issues/69787
testWidgets('WidgetSpans with no semantic information are elided from semantics - case 2', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final TapGestureRecognizer recognizer = TapGestureRecognizer();
addTearDown(recognizer.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: RichText(
text: TextSpan(children: <InlineSpan>[
const WidgetSpan(child: SizedBox.shrink()),
const WidgetSpan(child: Text('included')),
TextSpan(
text: 'HELLO',
style: const TextStyle(color: Colors.black),
recognizer: recognizer..onTap = () {},
),
const WidgetSpan(child: Text('included2')),
]),
),
),
);
expect(
semantics,
hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(label: 'included'),
TestSemantics(
label: 'HELLO',
actions: <SemanticsAction>[
SemanticsAction.tap,
],
flags: <SemanticsFlag>[
SemanticsFlag.isLink,
],
),
TestSemantics(label: 'included2'),
],
),
],
),
ignoreId: true,
ignoreRect: true,
ignoreTransform: true,
),
);
semantics.dispose();
}, skip: isBrowser); // https://github.com/flutter/flutter/issues/87877
// Regression test for https://github.com/flutter/flutter/issues/69787
testWidgets('WidgetSpans with no semantic information are elided from semantics - case 3', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final TapGestureRecognizer recognizer = TapGestureRecognizer();
addTearDown(recognizer.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: RichText(
text: TextSpan(children: <InlineSpan>[
const WidgetSpan(child: SizedBox.shrink()),
WidgetSpan(
child: Row(
children: <Widget>[
Semantics(
container: true,
child: const Text('foo'),
),
Semantics(
container: true,
child: const Text('bar'),
),
],
),
),
TextSpan(
text: 'HELLO',
style: const TextStyle(color: Colors.black),
recognizer: recognizer..onTap = () {},
),
]),
),
),
);
expect(
semantics,
hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(label: 'foo'),
TestSemantics(label: 'bar'),
TestSemantics(
label: 'HELLO',
actions: <SemanticsAction>[
SemanticsAction.tap,
],
flags: <SemanticsFlag>[
SemanticsFlag.isLink,
],
),
],
),
],
),
ignoreId: true,
ignoreRect: true,
ignoreTransform: true,
),
);
semantics.dispose();
}, skip: isBrowser); // https://github.com/flutter/flutter/issues/87877
// Regression test for https://github.com/flutter/flutter/issues/69787
testWidgets('WidgetSpans with no semantic information are elided from semantics - case 4', (WidgetTester tester) async {
final SemanticsTester semantics = SemanticsTester(tester);
final TapGestureRecognizer recognizer = TapGestureRecognizer();
addTearDown(recognizer.dispose);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: ClipRect(
child: Container(
color: Colors.green,
height: 100,
width: 100,
child: OverflowBox(
alignment: Alignment.topLeft,
maxWidth: double.infinity,
child: RichText(
text: TextSpan(
children: <InlineSpan>[
const WidgetSpan(
child: Icon(
Icons.edit,
size: 16,
semanticLabel: 'not clipped',
),
),
TextSpan(
text: 'next WS is clipped',
recognizer: recognizer..onTap = () { },
),
const WidgetSpan(
child: Icon(
Icons.edit,
size: 16,
semanticLabel: 'clipped',
),
),
],
),
),
),
),
),
),
),
);
expect(
semantics,
hasSemantics(
TestSemantics.root(
children: <TestSemantics>[
TestSemantics(
children: <TestSemantics>[
TestSemantics(label: 'not clipped'),
TestSemantics(
label: 'next WS is clipped',
flags: <SemanticsFlag>[SemanticsFlag.isLink],
actions: <SemanticsAction>[SemanticsAction.tap],
),
],
),
],
),
ignoreId: true,
ignoreRect: true,
ignoreTransform: true,
),
);
semantics.dispose();
}, skip: isBrowser); // https://github.com/flutter/flutter/issues/87877
testWidgets('RenderParagraph intrinsic width', (WidgetTester tester) async {
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
height: 100,
child: IntrinsicWidth(
child: RichText(
text: const TextSpan(
style: TextStyle(fontSize: 16, height: 1),
children: <InlineSpan>[
TextSpan(text: 'S '),
WidgetSpan(
alignment: PlaceholderAlignment.top,
child: Wrap(
direction: Axis.vertical,
children: <Widget>[
SizedBox(width: 200, height: 100),
SizedBox(width: 200, height: 30),
],
),
),
TextSpan(text: ' E'),
],
),
),
),
),
),
),
);
expect(tester.getSize(find.byType(RichText)).width, 200 + 4 * 16.0);
final RenderParagraph paragraph = tester.renderObject<RenderParagraph>(find.byType(RichText));
// The inline spans are rendered on one (horizontal) line, the sum of the widths is the max intrinsic width.
expect(paragraph.getMaxIntrinsicWidth(0.0), 200 + 4 * 16.0);
// The inline spans are rendered in one vertical run, the widest one determines the min intrinsic width.
expect(paragraph.getMinIntrinsicWidth(0.0), 200);
});
testWidgets('can compute intrinsic width and height for widget span with text scaling', (WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/59316
const Key textKey = Key('RichText');
Widget textWithNestedInlineSpans({ required double textScaleFactor, required double screenWidth }) {
return Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: OverflowBox(
alignment: Alignment.topLeft,
maxWidth: screenWidth,
child: RichText(
key: textKey,
textScaleFactor: textScaleFactor,
text: const TextSpan(children: <InlineSpan>[
WidgetSpan(child: Text('one two')),
]),
),
),
),
);
}
// The render object is going to be reused across widget tree rebuilds.
late final RenderParagraph outerParagraph = tester.renderObject(find.byKey(textKey));
await tester.pumpWidget(textWithNestedInlineSpans(textScaleFactor: 1.0, screenWidth: 100.0));
expect(
outerParagraph.getMaxIntrinsicHeight(100.0),
14.0,
reason: 'singleLineHeight = 14.0',
);
await tester.pumpWidget(textWithNestedInlineSpans(textScaleFactor: 2.0, screenWidth: 100.0));
expect(
outerParagraph.getMinIntrinsicHeight(100.0),
14.0 * 2.0 * 2,
reason: 'intrinsicHeight = singleLineHeight * textScaleFactor * two lines.',
);
await tester.pumpWidget(textWithNestedInlineSpans(textScaleFactor: 1.0, screenWidth: 1000.0));
expect(
outerParagraph.getMaxIntrinsicWidth(1000.0),
14.0 * 7,
reason: 'intrinsic width = 14.0 * 7',
);
await tester.pumpWidget(textWithNestedInlineSpans(textScaleFactor: 2.0, screenWidth: 1000.0));
expect(
outerParagraph.getMaxIntrinsicWidth(1000.0),
14.0 * 2.0 * 7,
reason: 'intrinsic width = glyph advance * textScaleFactor * num of glyphs',
);
});
testWidgets('Text uses TextStyle.overflow', (WidgetTester tester) async {
const TextOverflow overflow = TextOverflow.fade;
await tester.pumpWidget(const Text(
'Hello World',
textDirection: TextDirection.ltr,
style: TextStyle(overflow: overflow),
));
final RichText richText = tester.firstWidget(find.byType(RichText));
expect(richText.overflow, overflow);
expect(richText.text.style!.overflow, overflow);
});
testWidgets(
'Text can be hit-tested without layout or paint being called in a frame',
(WidgetTester tester) async {
// Regression test for https://github.com/flutter/flutter/issues/85108.
await tester.pumpWidget(
const Opacity(
opacity: 1.0,
child: Text(
'Hello World',
textDirection: TextDirection.ltr,
style: TextStyle(color: Color(0xFF123456)),
),
),
);
// The color changed and the opacity is set to 0:
// * 0 opacity will prevent RenderParagraph.paint from being called.
// * Only changing the color will prevent RenderParagraph.performLayout
// from being called.
// The underlying TextPainter should not evict its layout cache in this
// case, for hit-testing.
await tester.pumpWidget(
const Opacity(
opacity: 0.0,
child: Text(
'Hello World',
textDirection: TextDirection.ltr,
style: TextStyle(color: Color(0x87654321)),
),
),
);
await tester.tap(find.text('Hello World'));
expect(tester.takeException(), isNull);
});
testWidgets('Mouse hovering over selectable Text uses SystemMouseCursor.text', (WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(
home: SelectionArea(
child: Text('Flutter'),
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.byType(Text)));
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.text);
});
testWidgets('Mouse hovering over selectable Text uses default selection style mouse cursor', (WidgetTester tester) async {
await tester.pumpWidget(MaterialApp(
home: SelectionArea(
child: DefaultSelectionStyle.merge(
mouseCursor: SystemMouseCursors.click,
child: const Text('Flutter'),
),
),
));
final TestGesture gesture = await tester.createGesture(kind: PointerDeviceKind.mouse, pointer: 1);
await gesture.addPointer(location: tester.getCenter(find.byType(Text)));
await tester.pump();
expect(RendererBinding.instance.mouseTracker.debugDeviceActiveCursor(1), SystemMouseCursors.click);
});
}
Future<void> _pumpTextWidget({
required WidgetTester tester,
required String text,
required TextOverflow overflow,
}) {
return tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Center(
child: SizedBox(
width: 50.0,
height: 50.0,
child: Text(
text,
overflow: overflow,
),
),
),
),
);
}
| flutter/packages/flutter/test/widgets/text_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/text_test.dart",
"repo_id": "flutter",
"token_count": 27727
} | 701 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
late SpyStringValueNotifier valueListenable;
late Widget textBuilderUnderTest;
Widget builderForValueListenable(
ValueListenable<String?> valueListenable,
) {
return Directionality(
textDirection: TextDirection.ltr,
child: ValueListenableBuilder<String?>(
valueListenable: valueListenable,
builder: (BuildContext context, String? value, Widget? child) {
if (value == null) {
return const Placeholder();
}
return Text(value);
},
),
);
}
setUp(() {
valueListenable = SpyStringValueNotifier(null);
textBuilderUnderTest = builderForValueListenable(valueListenable);
});
tearDown(() {
valueListenable.dispose();
});
testWidgets('Null value is ok', (WidgetTester tester) async {
await tester.pumpWidget(textBuilderUnderTest);
expect(find.byType(Placeholder), findsOneWidget);
});
testWidgets('Widget builds with initial value', (WidgetTester tester) async {
final SpyStringValueNotifier valueListenable = SpyStringValueNotifier('Bachman');
addTearDown(valueListenable.dispose);
await tester.pumpWidget(builderForValueListenable(valueListenable));
expect(find.text('Bachman'), findsOneWidget);
});
testWidgets('Widget updates when value changes', (WidgetTester tester) async {
await tester.pumpWidget(textBuilderUnderTest);
valueListenable.value = 'Gilfoyle';
await tester.pump();
expect(find.text('Gilfoyle'), findsOneWidget);
valueListenable.value = 'Dinesh';
await tester.pump();
expect(find.text('Gilfoyle'), findsNothing);
expect(find.text('Dinesh'), findsOneWidget);
});
testWidgets('Can change listenable', (WidgetTester tester) async {
await tester.pumpWidget(textBuilderUnderTest);
valueListenable.value = 'Gilfoyle';
await tester.pump();
expect(find.text('Gilfoyle'), findsOneWidget);
final SpyStringValueNotifier differentListenable = SpyStringValueNotifier('Hendricks');
addTearDown(differentListenable.dispose);
await tester.pumpWidget(builderForValueListenable(differentListenable));
expect(find.text('Gilfoyle'), findsNothing);
expect(find.text('Hendricks'), findsOneWidget);
});
testWidgets('Stops listening to old listenable after changing listenable', (WidgetTester tester) async {
await tester.pumpWidget(textBuilderUnderTest);
valueListenable.value = 'Gilfoyle';
await tester.pump();
expect(find.text('Gilfoyle'), findsOneWidget);
final SpyStringValueNotifier differentListenable = SpyStringValueNotifier('Hendricks');
addTearDown(differentListenable.dispose);
await tester.pumpWidget(builderForValueListenable(differentListenable));
expect(find.text('Gilfoyle'), findsNothing);
expect(find.text('Hendricks'), findsOneWidget);
// Change value of the (now) disconnected listenable.
valueListenable.value = 'Big Head';
expect(find.text('Gilfoyle'), findsNothing);
expect(find.text('Big Head'), findsNothing);
expect(find.text('Hendricks'), findsOneWidget);
});
testWidgets('Self-cleans when removed', (WidgetTester tester) async {
await tester.pumpWidget(textBuilderUnderTest);
valueListenable.value = 'Gilfoyle';
await tester.pump();
expect(find.text('Gilfoyle'), findsOneWidget);
await tester.pumpWidget(const Placeholder());
expect(find.text('Gilfoyle'), findsNothing);
expect(valueListenable.hasListeners, false);
});
}
class SpyStringValueNotifier extends ValueNotifier<String?> {
SpyStringValueNotifier(super.initialValue);
/// Override for test visibility only.
@override
bool get hasListeners => super.hasListeners;
}
| flutter/packages/flutter/test/widgets/value_listenable_builder_test.dart/0 | {
"file_path": "flutter/packages/flutter/test/widgets/value_listenable_builder_test.dart",
"repo_id": "flutter",
"token_count": 1338
} | 702 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:flutter/material.dart';
void main() {
// Changes made in https://github.com/flutter/flutter/pull/48547
var textTheme = TextTheme(
displayLarge: displayStyle4,
displayMedium: displayStyle3,
displaySmall: displayStyle2,
headlineMedium: displayStyle1,
headlineSmall: headlineStyle,
titleLarge: titleStyle,
titleMedium: subheadStyle,
bodyLarge: body2Style,
bodyMedium: body1Style,
bodySmall: captionStyle,
labelLarge: buttonStyle,
titleSmall: subtitleStyle,
labelSmall: overlineStyle,
);
var errorTextTheme = TextTheme(error: '');
// Changes made in https://github.com/flutter/flutter/pull/48547
var copiedTextTheme = TextTheme.copyWith(
displayLarge: displayStyle4,
displayMedium: displayStyle3,
displaySmall: displayStyle2,
headlineMedium: displayStyle1,
headlineSmall: headlineStyle,
titleLarge: titleStyle,
titleMedium: subheadStyle,
bodyLarge: body2Style,
bodyMedium: body1Style,
bodySmall: captionStyle,
labelLarge: buttonStyle,
titleSmall: subtitleStyle,
labelSmall: overlineStyle,
);
var errorCopiedTextTheme = TextTheme.copyWith(error: '');
// Changes made in https://github.com/flutter/flutter/pull/48547
var style;
style = textTheme.displayLarge;
style = textTheme.displayMedium;
style = textTheme.displaySmall;
style = textTheme.headlineMedium;
style = textTheme.headlineSmall;
style = textTheme.titleLarge;
style = textTheme.titleMedium;
style = textTheme.bodyLarge;
style = textTheme.bodyMedium;
style = textTheme.bodySmall;
style = textTheme.labelLarge;
style = textTheme.titleSmall;
style = textTheme.labelSmall;
// Changes made in https://github.com/flutter/flutter/pull/109817
var anotherTextTheme = TextTheme(
displayLarge: headline1Style,
displayMedium: headline2Style,
displaySmall: headline3Style,
headlineMedium: headline4Style,
headlineSmall: headline5Style,
titleLarge: headline6Style,
titleMedium: subtitle1Style,
titleSmall: subtitle2Style,
bodyLarge: bodyText1Style,
bodyMedium: bodyText2Style,
bodySmall: captionStyle,
labelLarge: buttonStyle,
labelSmall: overlineStyle,
);
var anotherErrorTextTheme = TextTheme(error: '');
// Changes made in https://github.com/flutter/flutter/pull/109817
var anotherCopiedTextTheme = TextTheme.copyWith(
displayLarge: headline1Style,
displayMedium: headline2Style,
displaySmall: headline3Style,
headlineMedium: headline4Style,
headlineSmall: headline5Style,
titleLarge: headline6Style,
titleMedium: subtitle1Style,
titleSmall: subtitle2Style,
bodyLarge: bodyText1Style,
bodyMedium: bodyText2Style,
bodySmall: captionStyle,
labelLarge: buttonStyle,
labelSmall: overlineStyle,
);
var anotherErrorCopiedTextTheme = TextTheme.copyWith(error: '');
// Changes made in https://github.com/flutter/flutter/pull/109817
var style;
style = textTheme.displayLarge;
style = textTheme.displayMedium;
style = textTheme.displaySmall;
style = textTheme.headlineMedium;
style = textTheme.headlineSmall;
style = textTheme.titleLarge;
style = textTheme.titleMedium;
style = textTheme.titleSmall;
style = textTheme.bodyLarge;
style = textTheme.bodyMedium;
style = textTheme.bodySmall;
style = textTheme.labelLarge;
style = textTheme.labelSmall;
}
| flutter/packages/flutter/test_fixes/material/text_theme.dart.expect/0 | {
"file_path": "flutter/packages/flutter/test_fixes/material/text_theme.dart.expect",
"repo_id": "flutter",
"token_count": 1161
} | 703 |
name: flutter_test_private
description: Tests private interfaces of the flutter
environment:
sdk: '>=3.2.0-0 <4.0.0'
dependencies:
# To update these, use "flutter update-packages --force-upgrade".
#
# For detailed instructions, refer to:
# https://github.com/flutter/flutter/wiki/Updating-dependencies-in-Flutter
meta: 1.12.0
path: 1.9.0
process: 5.0.2
process_runner: 4.2.0
args: 2.4.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
async: 2.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
collection: 1.18.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
file: 7.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
platform: 3.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
# PUBSPEC CHECKSUM: bbb2
| flutter/packages/flutter/test_private/pubspec.yaml/0 | {
"file_path": "flutter/packages/flutter/test_private/pubspec.yaml",
"repo_id": "flutter",
"token_count": 332
} | 704 |
# 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.
# For details regarding the *Flutter Fix* feature, see
# https://flutter.dev/docs/development/tools/flutter-fix
# Please add new fixes to the top of the file, separated by one blank line
# from other fixes. In a comment, include a link to the PR where the change
# requiring the fix was made.
# Every fix must be tested. See the
# flutter/packages/flutter_driver/test_fixes/README.md file for instructions
# on testing these data driven fixes.
# For documentation about this file format, see
# https://dart.dev/go/data-driven-fixes.
version: 1
transforms:
# Changes made in https://github.com/flutter/flutter/pull/82939
- title: 'Migrate to setSemantics'
date: 2024-01-10
element:
uris: [ 'flutter_driver.dart' ]
method: 'enableAccessibility'
inClass: 'FlutterDriver'
changes:
- kind: 'rename'
newName: 'setSemantics'
- kind: 'addParameter'
index: 0
name: 'enabled'
style: 'required_positional'
argumentValue:
expression: 'true'
# Changes made in https://github.com/flutter/flutter/pull/79310
- title: 'Migrate to writeTimelineToFile'
date: 2024-01-10
element:
uris: [ 'flutter_driver.dart' ]
method: 'writeSummaryToFile'
inClass: 'TimelineSummary'
changes:
- kind: 'rename'
newName: 'writeTimelineToFile'
| flutter/packages/flutter_driver/lib/fix_data/fix_flutter_driver/fix_data.yaml/0 | {
"file_path": "flutter/packages/flutter_driver/lib/fix_data/fix_flutter_driver/fix_data.yaml",
"repo_id": "flutter",
"token_count": 487
} | 705 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'message.dart';
/// A Flutter Driver command that requests a string representation of the render tree.
class GetRenderTree extends Command {
/// Create a command to request a string representation of the render tree.
const GetRenderTree({ super.timeout });
/// Deserializes this command from the value generated by [serialize].
GetRenderTree.deserialize(super.json) : super.deserialize();
@override
String get kind => 'get_render_tree';
}
/// A string representation of the render tree, the result of a
/// [FlutterDriver.getRenderTree] method.
class RenderTree extends Result {
/// Creates a [RenderTree] object with the given string representation.
const RenderTree(this.tree);
/// String representation of the render tree.
final String? tree;
/// Deserializes the result from JSON.
static RenderTree fromJson(Map<String, dynamic> json) {
return RenderTree(json['tree'] as String);
}
@override
Map<String, dynamic> toJson() => <String, dynamic>{
'tree': tree,
};
}
| flutter/packages/flutter_driver/lib/src/common/render_tree.dart/0 | {
"file_path": "flutter/packages/flutter_driver/lib/src/common/render_tree.dart",
"repo_id": "flutter",
"token_count": 325
} | 706 |
// 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 'percentile_utils.dart';
import 'timeline.dart';
/// Key for SceneDisplayLag timeline events.
const String kSceneDisplayLagEvent = 'SceneDisplayLag';
const String _kVsyncTransitionsMissed = 'vsync_transitions_missed';
/// Summarizes [TimelineEvents]s corresponding to [kSceneDisplayLagEvent] events.
///
/// A sample event (some fields have been omitted for brevity):
/// ```json
/// {
/// "name": "SceneDisplayLag",
/// "ts": 408920509340,
/// "ph": "b", (this can be 'b' or 'e' for begin or end)
/// "args": {
/// "frame_target_time": "408920509340458",
/// "current_frame_target_time": "408920542689291",
/// "vsync_transitions_missed": "2"
/// }
/// },
/// ```
///
/// `vsync_transitions_missed` corresponds to the elapsed number of frame budget
/// durations between when the frame was scheduled to be displayed, i.e, the
/// `frame_target_time` and the next vsync pulse timestamp, i.e, the
/// `current_frame_target_time`.
class SceneDisplayLagSummarizer {
/// Creates a SceneDisplayLagSummarizer given the timeline events.
SceneDisplayLagSummarizer(this.sceneDisplayLagEvents) {
for (final TimelineEvent event in sceneDisplayLagEvents) {
assert(event.name == kSceneDisplayLagEvent);
}
}
/// The scene display lag events.
final List<TimelineEvent> sceneDisplayLagEvents;
/// Computes the average of the `vsync_transitions_missed` over the lag events.
double computeAverageVsyncTransitionsMissed() {
if (sceneDisplayLagEvents.isEmpty) {
return 0;
}
final double total = sceneDisplayLagEvents
.map(_getVsyncTransitionsMissed)
.reduce((double a, double b) => a + b);
return total / sceneDisplayLagEvents.length;
}
/// The [percentile]-th percentile `vsync_transitions_missed` over the lag events.
double computePercentileVsyncTransitionsMissed(double percentile) {
if (sceneDisplayLagEvents.isEmpty) {
return 0;
}
final List<double> doubles =
sceneDisplayLagEvents.map(_getVsyncTransitionsMissed).toList();
return findPercentile(doubles, percentile);
}
double _getVsyncTransitionsMissed(TimelineEvent e) {
assert(e.name == kSceneDisplayLagEvent);
assert(e.arguments!.containsKey(_kVsyncTransitionsMissed));
final dynamic transitionsMissed = e.arguments![_kVsyncTransitionsMissed];
assert(transitionsMissed is String);
return double.parse(transitionsMissed as String);
}
}
| flutter/packages/flutter_driver/lib/src/driver/scene_display_lag_summarizer.dart/0 | {
"file_path": "flutter/packages/flutter_driver/lib/src/driver/scene_display_lag_summarizer.dart",
"repo_id": "flutter",
"token_count": 905
} | 707 |
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:fake_async/fake_async.dart';
import 'package:flutter_driver/src/common/error.dart';
import 'package:flutter_driver/src/common/health.dart';
import 'package:flutter_driver/src/common/layer_tree.dart';
import 'package:flutter_driver/src/common/text_input_action.dart';
import 'package:flutter_driver/src/common/wait.dart';
import 'package:flutter_driver/src/driver/driver.dart';
import 'package:flutter_driver/src/driver/timeline.dart';
import 'package:vm_service/vm_service.dart' as vms;
import '../../common.dart';
/// Magical timeout value that's different from the default.
const Duration _kTestTimeout = Duration(milliseconds: 1234);
const String _kSerializedTestTimeout = '1234';
const String _kWebScriptPrefix = r"window.$flutterDriver('";
const String _kWebScriptSuffix = "')";
void main() {
final List<String> log = <String>[];
driverLog = (String source, String message) {
log.add('$source: $message');
};
group('VMServiceFlutterDriver with logCommunicationToFile', () {
late FakeVmService fakeClient;
late FakeVM fakeVM;
late vms.Isolate fakeIsolate;
late VMServiceFlutterDriver driver;
late File logFile;
setUp(() {
fakeIsolate = createFakeIsolate();
fakeVM = FakeVM(fakeIsolate);
fakeClient = FakeVmService(fakeVM);
fakeClient.responses['waitFor'] = makeFakeResponse(<String, dynamic>{'status':'ok'});
});
tearDown(() {
if (logFile.existsSync()) {
logFile.deleteSync();
}
});
group('logCommunicationToFile', () {
test('logCommunicationToFile = true', () async {
driver = VMServiceFlutterDriver.connectedTo(fakeClient, fakeIsolate);
logFile = File(driver.logFilePathName);
await driver.waitFor(find.byTooltip('foo'), timeout: _kTestTimeout);
final bool exists = logFile.existsSync();
expect(exists, true, reason: 'Not found ${logFile.path}');
final String commandLog = await logFile.readAsString();
const String waitForCommandLog = '>>> {command: waitFor, timeout: $_kSerializedTestTimeout, finderType: ByTooltipMessage, text: foo}';
const String responseLog = '<<< {isError: false, response: {status: ok}}';
expect(commandLog.contains(waitForCommandLog), true, reason: '$commandLog not contains $waitForCommandLog');
expect(commandLog.contains(responseLog), true, reason: '$commandLog not contains $responseLog');
});
test('logCommunicationToFile = false', () async {
driver = VMServiceFlutterDriver.connectedTo(fakeClient, fakeIsolate, logCommunicationToFile: false);
logFile = File(driver.logFilePathName);
// clear log file if left in filetree from previous run
if (logFile.existsSync()) {
logFile.deleteSync();
}
await driver.waitFor(find.byTooltip('foo'), timeout: _kTestTimeout);
final bool exists = logFile.existsSync();
expect(exists, false, reason: 'because ${logFile.path} exists');
});
test('logFilePathName was set when a new driver was created', () {
driver = VMServiceFlutterDriver.connectedTo(fakeClient, fakeIsolate);
logFile = File(driver.logFilePathName);
expect(logFile.path, endsWith('.log'));
});
});
});
group('VMServiceFlutterDriver with printCommunication', () {
late FakeVmService fakeClient;
late FakeVM fakeVM;
late vms.Isolate fakeIsolate;
late VMServiceFlutterDriver driver;
setUp(() async {
log.clear();
fakeIsolate = createFakeIsolate();
fakeVM = FakeVM(fakeIsolate);
fakeClient = FakeVmService(fakeVM);
fakeClient.responses['waitFor'] = makeFakeResponse(<String, dynamic>{'status':'ok'});
});
test('printCommunication = true', () async {
driver = VMServiceFlutterDriver.connectedTo(fakeClient, fakeIsolate, printCommunication: true);
await driver.waitFor(find.byTooltip('foo'), timeout: _kTestTimeout);
expect(log, <String>[
'VMServiceFlutterDriver: >>> {command: waitFor, timeout: $_kSerializedTestTimeout, finderType: ByTooltipMessage, text: foo}',
'VMServiceFlutterDriver: <<< {isError: false, response: {status: ok}}',
]);
});
test('printCommunication = false', () async {
driver = VMServiceFlutterDriver.connectedTo(fakeClient, fakeIsolate);
await driver.waitFor(find.byTooltip('foo'), timeout: _kTestTimeout);
expect(log, <String>[]);
});
});
group('VMServiceFlutterDriver.connect', () {
late FakeVmService fakeClient;
late FakeVM fakeVM;
late vms.Isolate fakeIsolate;
void expectLogContains(String message) {
expect(log, anyElement(contains(message)));
}
setUp(() {
log.clear();
fakeIsolate = createFakeIsolate();
fakeVM = FakeVM(fakeIsolate);
fakeClient = FakeVmService(fakeVM);
vmServiceConnectFunction = (String url, Map<String, dynamic>? headers) async {
return fakeClient;
};
fakeClient.responses['get_health'] = makeFakeResponse(<String, dynamic>{'status': 'ok'});
});
tearDown(() async {
restoreVmServiceConnectFunction();
});
test('Retries while Dart VM service is not available', () async {
// This test case will test the real implementation of `_waitAndConnect`.
restoreVmServiceConnectFunction();
// The actual behavior is to retry indefinitely until the Dart VM service
// becomes available. `.timeout` is used here to exit the infinite loop,
// expecting that no other types of error are thrown during the process.
expect(
vmServiceConnectFunction('http://foo.bar', <String, dynamic>{})
.timeout(const Duration(seconds: 1)),
throwsA(isA<TimeoutException>()),
);
});
test('throws after retries if no isolate', () async {
fakeVM.numberOfTriesBeforeResolvingIsolate = 10000;
FakeAsync().run((FakeAsync time) {
FlutterDriver.connect(dartVmServiceUrl: '');
time.elapse(kUnusuallyLongTimeout);
});
expect(log, <String>[
'VMServiceFlutterDriver: Connecting to Flutter application at ',
'VMServiceFlutterDriver: The root isolate is taking an unusually long time to start.',
]);
});
test('Retries connections if isolate is not available', () async {
fakeIsolate.pauseEvent = vms.Event(kind: vms.EventKind.kPauseStart, timestamp: 0);
fakeVM.numberOfTriesBeforeResolvingIsolate = 5;
final FlutterDriver driver = await FlutterDriver.connect(dartVmServiceUrl: '');
expect(driver, isNotNull);
expect(
fakeClient.connectionLog,
<String>[
'getIsolate',
'setFlag pause_isolates_on_start false',
'resume',
'streamListen Isolate',
'getIsolate',
'onIsolateEvent',
'streamCancel Isolate',
],
);
});
test('Refreshes isolate if it is not started for long time', () async {
fakeIsolate.pauseEvent = vms.Event(kind: vms.EventKind.kNone, timestamp: 0);
fakeClient.onGetIsolate = changeIsolateEventAfter(
5,
vms.Event(kind: vms.EventKind.kPauseStart, timestamp: 1),
);
final FlutterDriver driver = await FlutterDriver.connect(dartVmServiceUrl: '');
expect(driver, isNotNull);
expect(
fakeClient.connectionLog,
<String>[
'getIsolate',
'getIsolate',
'getIsolate',
'getIsolate',
'getIsolate',
'setFlag pause_isolates_on_start false',
'resume',
'streamListen Isolate',
'getIsolate',
'onIsolateEvent',
'streamCancel Isolate',
],
);
});
test('Connects to isolate number', () async {
fakeIsolate.pauseEvent = vms.Event(kind: vms.EventKind.kPauseStart, timestamp: 0);
final FlutterDriver driver = await FlutterDriver.connect(dartVmServiceUrl: '', isolateNumber: int.parse(fakeIsolate.number!));
expect(driver, isNotNull);
expect(
fakeClient.connectionLog,
<String>[
'getIsolate',
'setFlag pause_isolates_on_start false',
'resume',
'streamListen Isolate',
'getIsolate',
'onIsolateEvent',
'streamCancel Isolate',
],
);
});
test('connects to isolate paused at start', () async {
fakeIsolate.pauseEvent = vms.Event(kind: vms.EventKind.kPauseStart, timestamp: 0);
final FlutterDriver driver = await FlutterDriver.connect(dartVmServiceUrl: '');
expect(driver, isNotNull);
expectLogContains('Isolate is paused at start');
expect(
fakeClient.connectionLog,
<String>[
'getIsolate',
'setFlag pause_isolates_on_start false',
'resume',
'streamListen Isolate',
'getIsolate',
'onIsolateEvent',
'streamCancel Isolate',
],
);
});
test('ignores setFlag failure', () async {
fakeIsolate.pauseEvent = vms.Event(kind: vms.EventKind.kPauseStart, timestamp: 0);
fakeClient.failOnSetFlag = true;
final FlutterDriver driver = await FlutterDriver.connect(dartVmServiceUrl: '');
expectLogContains('Failed to set pause_isolates_on_start=false, proceeding. '
'Error: Exception: setFlag failed');
expect(driver, isNotNull);
});
test('connects to isolate paused mid-flight', () async {
fakeIsolate.pauseEvent = vms.Event(kind: vms.EventKind.kPauseBreakpoint, timestamp: 0);
final FlutterDriver driver = await FlutterDriver.connect(dartVmServiceUrl: '');
expect(driver, isNotNull);
expectLogContains('Isolate is paused mid-flight');
});
test('connects to isolate paused mid-flight after request', () async {
fakeIsolate.pauseEvent = vms.Event(kind: vms.EventKind.kPausePostRequest, timestamp: 0);
final FlutterDriver driver = await FlutterDriver.connect(dartVmServiceUrl: '');
expect(driver, isNotNull);
expectLogContains('Isolate is paused mid-flight');
});
// This test simulates a situation when we believe that the isolate is
// currently paused, but something else (e.g. a debugger) resumes it before
// we do. There's no need to fail as we should be able to drive the app
// just fine.
test('connects despite losing the race to resume isolate', () async {
fakeIsolate.pauseEvent = vms.Event(kind: vms.EventKind.kPauseBreakpoint, timestamp: 0);
fakeClient.failOnResumeWith101 = true;
final FlutterDriver driver = await FlutterDriver.connect(dartVmServiceUrl: '');
expect(driver, isNotNull);
expectLogContains('Attempted to resume an already resumed isolate');
});
test('connects to unpaused isolate', () async {
fakeIsolate.pauseEvent = vms.Event(kind: vms.EventKind.kResume, timestamp: 0);
final FlutterDriver driver = await FlutterDriver.connect(dartVmServiceUrl: '');
expect(driver, isNotNull);
expectLogContains('Isolate is not paused. Assuming application is ready.');
});
test('connects to unpaused when onExtensionAdded does not contain the '
'driver extension', () async {
fakeIsolate.pauseEvent = vms.Event(kind: vms.EventKind.kResume, timestamp: 0);
fakeIsolate.extensionRPCs!.add('ext.flutter.driver');
final FlutterDriver driver = await FlutterDriver.connect(dartVmServiceUrl: '');
expect(driver, isNotNull);
expectLogContains('Isolate is not paused. Assuming application is ready.');
});
});
group('VMServiceFlutterDriver', () {
late FakeVmService fakeClient;
late FakeVM fakeVM;
late vms.Isolate fakeIsolate;
late VMServiceFlutterDriver driver;
setUp(() {
fakeIsolate = createFakeIsolate();
fakeVM = FakeVM(fakeIsolate);
fakeClient = FakeVmService(fakeVM);
driver = VMServiceFlutterDriver.connectedTo(fakeClient, fakeIsolate);
fakeClient.responses['tap'] = makeFakeResponse(<String, dynamic>{});
});
test('checks the health of the driver extension', () async {
fakeClient.responses['get_health'] = makeFakeResponse(<String, dynamic>{'status': 'ok'});
final Health result = await driver.checkHealth();
expect(result.status, HealthStatus.ok);
});
test('closes connection', () async {
await driver.close();
expect(fakeClient.connectionLog.last, 'dispose');
});
group('ByValueKey', () {
test('restricts value types', () async {
expect(() => find.byValueKey(null), throwsDriverError);
});
test('finds by ValueKey', () async {
await driver.tap(find.byValueKey('foo'), timeout: _kTestTimeout);
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: tap, timeout: $_kSerializedTestTimeout, finderType: ByValueKey, keyValueString: foo, keyValueType: String}',
]);
});
});
group('BySemanticsLabel', () {
test('finds by Semantic label using String', () async {
await driver.tap(find.bySemanticsLabel('foo'), timeout: _kTestTimeout);
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: tap, timeout: $_kSerializedTestTimeout, finderType: BySemanticsLabel, label: foo}',
]);
});
test('finds by Semantic label using RegExp', () async {
await driver.tap(find.bySemanticsLabel(RegExp('^foo')), timeout: _kTestTimeout);
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: tap, timeout: $_kSerializedTestTimeout, finderType: BySemanticsLabel, label: ^foo, isRegExp: true}',
]);
});
});
group('tap', () {
test('sends the tap command', () async {
await driver.tap(find.text('foo'), timeout: _kTestTimeout);
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: tap, timeout: $_kSerializedTestTimeout, finderType: ByText, text: foo}',
]);
});
});
group('getText', () {
test('sends the getText command', () async {
fakeClient.responses['get_text'] = makeFakeResponse(<String, dynamic>{'text': 'hello'});
final String result = await driver.getText(find.byValueKey(123), timeout: _kTestTimeout);
expect(result, 'hello');
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: get_text, timeout: $_kSerializedTestTimeout, finderType: ByValueKey, keyValueString: 123, keyValueType: int}',
]);
});
});
group('sendTextInputAction', () {
test('sends the SendTextInputAction command with action done', () async {
fakeClient.responses['send_text_input_action'] = makeFakeResponse(<String, dynamic>{});
await driver.sendTextInputAction(TextInputAction.done, timeout: _kTestTimeout);
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: send_text_input_action, timeout: $_kSerializedTestTimeout, action: done}',
]);
});
});
group('getLayerTree', () {
test('sends the getLayerTree command', () async {
fakeClient.responses['get_layer_tree'] = makeFakeResponse(<String, String>{
'tree': 'hello',
});
final LayerTree result = await driver.getLayerTree(timeout: _kTestTimeout);
final LayerTree referenceTree = LayerTree.fromJson(<String, String>{
'tree': 'hello',
});
expect(result.tree, referenceTree.tree);
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: get_layer_tree, timeout: $_kSerializedTestTimeout}',
]);
});
});
group('waitFor', () {
test('sends the waitFor command', () async {
fakeClient.responses['waitFor'] = makeFakeResponse(<String, dynamic>{});
await driver.waitFor(find.byTooltip('foo'), timeout: _kTestTimeout);
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: waitFor, timeout: $_kSerializedTestTimeout, finderType: ByTooltipMessage, text: foo}',
]);
});
});
group('getWidgetDiagnostics', () {
test('sends the getWidgetDiagnostics command', () async {
fakeClient.responses['get_diagnostics_tree'] = makeFakeResponse(<String, dynamic>{});
await driver.getWidgetDiagnostics(find.byTooltip('foo'), timeout: _kTestTimeout);
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: get_diagnostics_tree, timeout: $_kSerializedTestTimeout, finderType: ByTooltipMessage, text: foo, subtreeDepth: 0, includeProperties: true, diagnosticsType: widget}',
]);
});
});
group('getRenderObjectDiagnostics', () {
test('sends the getRenderObjectDiagnostics command', () async {
fakeClient.responses['get_diagnostics_tree'] = makeFakeResponse(<String, dynamic>{});
await driver.getRenderObjectDiagnostics(find.byTooltip('foo'), timeout: _kTestTimeout);
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: get_diagnostics_tree, timeout: $_kSerializedTestTimeout, finderType: ByTooltipMessage, text: foo, subtreeDepth: 0, includeProperties: true, diagnosticsType: renderObject}',
]);
});
});
group('waitForCondition', () {
test('sends the wait for NoPendingFrameCondition command', () async {
fakeClient.responses['waitForCondition'] = makeFakeResponse(<String, dynamic>{});
await driver.waitForCondition(const NoPendingFrame(), timeout: _kTestTimeout);
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: waitForCondition, timeout: $_kSerializedTestTimeout, conditionName: NoPendingFrameCondition}',
]);
});
test('sends the wait for NoPendingPlatformMessages command', () async {
fakeClient.responses['waitForCondition'] = makeFakeResponse(<String, dynamic>{});
await driver.waitForCondition(const NoPendingPlatformMessages(), timeout: _kTestTimeout);
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: waitForCondition, timeout: $_kSerializedTestTimeout, conditionName: NoPendingPlatformMessagesCondition}',
]);
});
test('sends the waitForCondition of combined conditions command', () async {
fakeClient.responses['waitForCondition'] = makeFakeResponse(<String, dynamic>{});
const SerializableWaitCondition combinedCondition =
CombinedCondition(<SerializableWaitCondition>[NoPendingFrame(), NoTransientCallbacks()]);
await driver.waitForCondition(combinedCondition, timeout: _kTestTimeout);
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: waitForCondition, timeout: $_kSerializedTestTimeout, conditionName: CombinedCondition, conditions: [{"conditionName":"NoPendingFrameCondition"},{"conditionName":"NoTransientCallbacksCondition"}]}',
]);
});
});
group('waitUntilNoTransientCallbacks', () {
test('sends the waitUntilNoTransientCallbacks command', () async {
fakeClient.responses['waitForCondition'] = makeFakeResponse(<String, dynamic>{});
await driver.waitUntilNoTransientCallbacks(timeout: _kTestTimeout);
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: waitForCondition, timeout: $_kSerializedTestTimeout, conditionName: NoTransientCallbacksCondition}',
]);
});
});
group('waitUntilFirstFrameRasterized', () {
test('sends the waitUntilFirstFrameRasterized command', () async {
fakeClient.responses['waitForCondition'] = makeFakeResponse(<String, dynamic>{});
await driver.waitUntilFirstFrameRasterized();
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: waitForCondition, conditionName: FirstFrameRasterizedCondition}',
]);
});
});
group('getOffset', () {
setUp(() {
fakeClient.responses['get_offset'] = makeFakeResponse(<String, double>{
'dx': 11,
'dy': 12,
});
});
test('sends the getCenter command', () async {
final DriverOffset result = await driver.getCenter(find.byValueKey(123), timeout: _kTestTimeout);
expect(result, const DriverOffset(11, 12));
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: get_offset, timeout: 1234, finderType: ByValueKey, keyValueString: 123, keyValueType: int, offsetType: center}',
]);
});
test('sends the getTopLeft command', () async {
final DriverOffset result = await driver.getTopLeft(find.byValueKey(123), timeout: _kTestTimeout);
expect(result, const DriverOffset(11, 12));
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: get_offset, timeout: 1234, finderType: ByValueKey, keyValueString: 123, keyValueType: int, offsetType: topLeft}',
]);
});
test('sends the getTopRight command', () async {
final DriverOffset result = await driver.getTopRight(find.byValueKey(123), timeout: _kTestTimeout);
expect(result, const DriverOffset(11, 12));
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: get_offset, timeout: 1234, finderType: ByValueKey, keyValueString: 123, keyValueType: int, offsetType: topRight}',
]);
});
test('sends the getBottomLeft command', () async {
final DriverOffset result = await driver.getBottomLeft(find.byValueKey(123), timeout: _kTestTimeout);
expect(result, const DriverOffset(11, 12));
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: get_offset, timeout: 1234, finderType: ByValueKey, keyValueString: 123, keyValueType: int, offsetType: bottomLeft}',
]);
});
test('sends the getBottomRight command', () async {
final DriverOffset result = await driver.getBottomRight(find.byValueKey(123), timeout: _kTestTimeout);
expect(result, const DriverOffset(11, 12));
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: get_offset, timeout: 1234, finderType: ByValueKey, keyValueString: 123, keyValueType: int, offsetType: bottomRight}',
]);
});
});
group('clearTimeline', () {
test('clears timeline', () async {
await driver.clearTimeline();
expect(fakeClient.connectionLog, contains('clearVMTimeline'));
});
});
group('traceAction', () {
test('without clearing timeline', () async {
final Timeline timeline = await driver.traceAction(() async {
fakeClient.connectionLog.add('action');
}, retainPriorEvents: true);
expect(fakeClient.connectionLog, const <String>[
'setVMTimelineFlags [all]',
'action',
'getFlagList',
'setVMTimelineFlags []',
'getVMTimeline null null',
]);
expect(timeline.events!.single.name, 'test event');
});
test('with clearing timeline', () async {
final Timeline timeline = await driver.traceAction(() async {
fakeClient.connectionLog.add('action');
});
expect(fakeClient.connectionLog, const <String>[
'clearVMTimeline',
'getVMTimelineMicros',
'setVMTimelineFlags [all]',
'action',
'getVMTimelineMicros',
'getFlagList',
'setVMTimelineFlags []',
'getVMTimeline 1 999999',
]);
expect(timeline.events!.single.name, 'test event');
});
test('with time interval', () async {
fakeClient.incrementMicros = true;
fakeClient.timelineResponses[1000001] = vms.Timeline.parse(<String, dynamic>{
'traceEvents': <dynamic>[
<String, dynamic>{
'name': 'test event 2',
},
],
'timeOriginMicros': 1000000,
'timeExtentMicros': 999999,
});
final Timeline timeline = await driver.traceAction(() async {
fakeClient.connectionLog.add('action');
});
expect(fakeClient.connectionLog, const <String>[
'clearVMTimeline',
'getVMTimelineMicros',
'setVMTimelineFlags [all]',
'action',
'getVMTimelineMicros',
'getFlagList',
'setVMTimelineFlags []',
'getVMTimeline 1 999999',
'getVMTimeline 1000001 999999',
]);
expect(timeline.events!.map((TimelineEvent event) => event.name), <String>[
'test event',
'test event 2',
]);
});
});
group('traceAction with timeline streams', () {
test('specify non-default timeline streams', () async {
bool actionCalled = false;
final Timeline timeline = await driver.traceAction(() async {
actionCalled = true;
},
streams: const <TimelineStream>[
TimelineStream.dart,
TimelineStream.gc,
TimelineStream.compiler,
],
retainPriorEvents: true);
expect(actionCalled, isTrue);
expect(fakeClient.connectionLog, <String>[
'setVMTimelineFlags [Dart, GC, Compiler]',
'getFlagList',
'setVMTimelineFlags []',
'getVMTimeline null null',
]);
expect(timeline.events!.single.name, 'test event');
});
});
group('sendCommand error conditions', () {
test('local default timeout', () async {
log.clear();
fakeClient.artificialExtensionDelay = Completer<void>().future;
FakeAsync().run((FakeAsync time) {
driver.waitFor(find.byTooltip('foo'));
expect(log, <String>[]);
time.elapse(kUnusuallyLongTimeout);
});
expect(log, <String>['VMServiceFlutterDriver: waitFor message is taking a long time to complete...']);
});
test('local custom timeout', () async {
log.clear();
fakeClient.artificialExtensionDelay = Completer<void>().future;
FakeAsync().run((FakeAsync time) {
final Duration customTimeout = kUnusuallyLongTimeout - const Duration(seconds: 1);
driver.waitFor(find.byTooltip('foo'), timeout: customTimeout);
expect(log, <String>[]);
time.elapse(customTimeout);
});
expect(log, <String>['VMServiceFlutterDriver: waitFor message is taking a long time to complete...']);
});
test('remote error', () async {
fakeClient.responses['waitFor'] = makeFakeResponse(<String, dynamic>{
'message': 'This is a failure',
}, isError: true);
await expectLater(
() => driver.waitFor(find.byTooltip('foo')),
throwsA(isA<DriverError>().having(
(DriverError error) => error.message,
'message',
'Error in Flutter application: {message: This is a failure}',
)),
);
});
test('uncaught remote error', () async {
fakeClient.artificialExtensionDelay = Future<void>.error(
vms.RPCError('callServiceExtension', 9999, 'test error'),
);
expect(driver.waitFor(find.byTooltip('foo')), throwsDriverError);
});
});
group('setSemantics', () {
test('can be enabled', () async {
fakeClient.responses['set_semantics'] = makeFakeResponse(<String, Object>{
'changedState': true,
});
await driver.setSemantics(true, timeout: _kTestTimeout);
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: set_semantics, timeout: $_kSerializedTestTimeout, enabled: true}',
]);
});
test('can be disabled', () async {
fakeClient.responses['set_semantics'] = makeFakeResponse(<String, Object>{
'changedState': false,
});
await driver.setSemantics(false, timeout: _kTestTimeout);
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: set_semantics, timeout: $_kSerializedTestTimeout, enabled: false}',
]);
});
});
test('VMServiceFlutterDriver does not support webDriver', () async {
expect(() => driver.webDriver, throwsUnsupportedError);
});
group('runUnsynchronized', () {
test('wrap waitFor with runUnsynchronized', () async {
fakeClient.responses['waitFor'] = makeFakeResponse(<String, dynamic>{});
fakeClient.responses['set_frame_sync'] = makeFakeResponse(<String, dynamic>{});
await driver.runUnsynchronized(() async {
await driver.waitFor(find.byTooltip('foo'), timeout: _kTestTimeout);
});
expect(fakeClient.commandLog, <String>[
'ext.flutter.driver {command: set_frame_sync, enabled: false}',
'ext.flutter.driver {command: waitFor, timeout: $_kSerializedTestTimeout, finderType: ByTooltipMessage, text: foo}',
'ext.flutter.driver {command: set_frame_sync, enabled: true}',
]);
});
});
});
group('VMServiceFlutterDriver with custom timeout', () {
late FakeVmService fakeClient;
late FakeVM fakeVM;
late vms.Isolate fakeIsolate;
late VMServiceFlutterDriver driver;
setUp(() {
fakeIsolate = createFakeIsolate();
fakeVM = FakeVM(fakeIsolate);
fakeClient = FakeVmService(fakeVM);
driver = VMServiceFlutterDriver.connectedTo(fakeClient, fakeIsolate);
fakeClient.responses['get_health'] = makeFakeResponse(<String, dynamic>{'status': 'ok'});
});
test('GetHealth has no default timeout', () async {
await driver.checkHealth();
expect(
fakeClient.commandLog,
<String>['ext.flutter.driver {command: get_health}'],
);
});
test('does not interfere with explicit timeouts', () async {
await driver.checkHealth(timeout: _kTestTimeout);
expect(
fakeClient.commandLog,
<String>['ext.flutter.driver {command: get_health, timeout: $_kSerializedTestTimeout}'],
);
});
});
group('WebFlutterDriver with logCommunicationToFile', () {
late FakeFlutterWebConnection fakeConnection;
late WebFlutterDriver driver;
late File logFile;
setUp(() {
fakeConnection = FakeFlutterWebConnection();
fakeConnection.supportsTimelineAction = true;
fakeConnection.responses['waitFor'] = jsonEncode(makeFakeResponse(<String, dynamic>{'status': 'ok'}));
});
tearDown(() {
if (logFile.existsSync()) {
logFile.deleteSync();
}
});
test('logCommunicationToFile = true', () async {
driver = WebFlutterDriver.connectedTo(fakeConnection);
logFile = File(driver.logFilePathName);
await driver.waitFor(find.byTooltip('logCommunicationToFile test'), timeout: _kTestTimeout);
final bool exists = logFile.existsSync();
expect(exists, true, reason: 'Not found ${logFile.path}');
final String commandLog = await logFile.readAsString();
const String waitForCommandLog = '>>> {command: waitFor, timeout: 1234, finderType: ByTooltipMessage, text: logCommunicationToFile test}';
const String responseLog = '<<< {isError: false, response: {status: ok}, type: Response}';
expect(commandLog, contains(waitForCommandLog), reason: '$commandLog not contains $waitForCommandLog');
expect(commandLog, contains(responseLog), reason: '$commandLog not contains $responseLog');
});
test('logCommunicationToFile = false', () async {
driver = WebFlutterDriver.connectedTo(fakeConnection, logCommunicationToFile: false);
logFile = File(driver.logFilePathName);
// clear log file if left in filetree from previous run
if (logFile.existsSync()) {
logFile.deleteSync();
}
await driver.waitFor(find.byTooltip('logCommunicationToFile test'), timeout: _kTestTimeout);
final bool exists = logFile.existsSync();
expect(exists, false, reason: 'because ${logFile.path} exists');
});
});
group('WebFlutterDriver with printCommunication', () {
late FakeFlutterWebConnection fakeConnection;
late WebFlutterDriver driver;
setUp(() {
log.clear();
fakeConnection = FakeFlutterWebConnection();
fakeConnection.supportsTimelineAction = true;
fakeConnection.responses['waitFor'] = jsonEncode(makeFakeResponse(<String, dynamic>{'status': 'ok'}));
});
test('printCommunication = true', () async {
driver = WebFlutterDriver.connectedTo(fakeConnection, printCommunication: true);
await driver.waitFor(find.byTooltip('printCommunication test'), timeout: _kTestTimeout);
expect(log, <String>[
'WebFlutterDriver: >>> {command: waitFor, timeout: 1234, finderType: ByTooltipMessage, text: printCommunication test}',
'WebFlutterDriver: <<< {isError: false, response: {status: ok}, type: Response}',
]);
});
test('printCommunication = false', () async {
driver = WebFlutterDriver.connectedTo(fakeConnection);
await driver.waitFor(find.byTooltip('printCommunication test'), timeout: _kTestTimeout);
expect(log, <String>[]);
});
});
group('WebFlutterDriver', () {
late FakeFlutterWebConnection fakeConnection;
late WebFlutterDriver driver;
setUp(() {
fakeConnection = FakeFlutterWebConnection();
fakeConnection.supportsTimelineAction = true;
driver = WebFlutterDriver.connectedTo(fakeConnection);
});
test('closes connection', () async {
await driver.close();
});
group('ByValueKey', () {
test('restricts value types', () async {
expect(() => find.byValueKey(null),
throwsDriverError);
});
test('finds by ValueKey', () async {
fakeConnection.responses['tap'] = jsonEncode(makeFakeResponse(<String, dynamic>{}));
await driver.tap(find.byValueKey('foo'), timeout: _kTestTimeout);
expect(fakeConnection.commandLog, <String>[
r'''window.$flutterDriver('{"command":"tap","timeout":"1234","finderType":"ByValueKey","keyValueString":"foo","keyValueType":"String"}') 0:00:01.234000''',
]);
});
});
group('BySemanticsLabel', () {
test('finds by Semantic label using String', () async {
fakeConnection.responses['tap'] = jsonEncode(makeFakeResponse(<String, dynamic>{}));
await driver.tap(find.bySemanticsLabel('foo'), timeout: _kTestTimeout);
expect(fakeConnection.commandLog, <String>[
r'''window.$flutterDriver('{"command":"tap","timeout":"1234","finderType":"BySemanticsLabel","label":"foo"}') 0:00:01.234000''',
]);
});
test('finds by Semantic label using RegExp', () async {
fakeConnection.responses['tap'] = jsonEncode(makeFakeResponse(<String, dynamic>{}));
await driver.tap(find.bySemanticsLabel(RegExp('^foo')), timeout: _kTestTimeout);
expect(fakeConnection.commandLog, <String>[
r'''window.$flutterDriver('{"command":"tap","timeout":"1234","finderType":"BySemanticsLabel","label":"^foo","isRegExp":"true"}') 0:00:01.234000''',
]);
});
});
group('tap', () {
test('sends the tap command', () async {
fakeConnection.responses['tap'] = jsonEncode(makeFakeResponse(<String, dynamic>{}));
await driver.tap(find.text('foo'), timeout: _kTestTimeout);
expect(fakeConnection.commandLog, <String>[
r'''window.$flutterDriver('{"command":"tap","timeout":"1234","finderType":"ByText","text":"foo"}') 0:00:01.234000''',
]);
});
});
group('getText', () {
test('sends the getText command', () async {
fakeConnection.responses['get_text'] = jsonEncode(makeFakeResponse(<String, dynamic>{'text': 'hello'}));
final String result = await driver.getText(find.byValueKey(123), timeout: _kTestTimeout);
expect(result, 'hello');
expect(fakeConnection.commandLog, <String>[
r'''window.$flutterDriver('{"command":"get_text","timeout":"1234","finderType":"ByValueKey","keyValueString":"123","keyValueType":"int"}') 0:00:01.234000''',
]);
});
});
group('waitFor', () {
test('sends the waitFor command', () async {
fakeConnection.responses['waitFor'] = jsonEncode(makeFakeResponse(<String, dynamic>{'text': 'hello'}));
await driver.waitFor(find.byTooltip('foo'), timeout: _kTestTimeout);
expect(fakeConnection.commandLog, <String>[
r'''window.$flutterDriver('{"command":"waitFor","timeout":"1234","finderType":"ByTooltipMessage","text":"foo"}') 0:00:01.234000''',
]);
});
});
group('waitForCondition', () {
setUp(() {
fakeConnection.responses['waitForCondition'] = jsonEncode(makeFakeResponse(<String, dynamic>{'text': 'hello'}));
});
test('sends the wait for NoPendingFrameCondition command', () async {
await driver.waitForCondition(const NoPendingFrame(), timeout: _kTestTimeout);
expect(fakeConnection.commandLog, <String>[
r'''window.$flutterDriver('{"command":"waitForCondition","timeout":"1234","conditionName":"NoPendingFrameCondition"}') 0:00:01.234000''',
]);
});
test('sends the wait for NoPendingPlatformMessages command', () async {
await driver.waitForCondition(const NoPendingPlatformMessages(), timeout: _kTestTimeout);
expect(fakeConnection.commandLog, <String>[
r'''window.$flutterDriver('{"command":"waitForCondition","timeout":"1234","conditionName":"NoPendingPlatformMessagesCondition"}') 0:00:01.234000''',
]);
});
test('sends the waitForCondition of combined conditions command', () async {
const SerializableWaitCondition combinedCondition = CombinedCondition(
<SerializableWaitCondition>[NoPendingFrame(), NoTransientCallbacks()],
);
await driver.waitForCondition(combinedCondition, timeout: _kTestTimeout);
expect(fakeConnection.commandLog, <String>[
r'''window.$flutterDriver('{"command":"waitForCondition","timeout":"1234","conditionName":"CombinedCondition","conditions":"[{\"conditionName\":\"NoPendingFrameCondition\"},{\"conditionName\":\"NoTransientCallbacksCondition\"}]"}') 0:00:01.234000''',
]);
});
});
group('waitUntilNoTransientCallbacks', () {
test('sends the waitUntilNoTransientCallbacks command', () async {
fakeConnection.responses['waitForCondition'] = jsonEncode(makeFakeResponse(<String, dynamic>{}));
await driver.waitUntilNoTransientCallbacks(timeout: _kTestTimeout);
expect(fakeConnection.commandLog, <String>[
r'''window.$flutterDriver('{"command":"waitForCondition","timeout":"1234","conditionName":"NoTransientCallbacksCondition"}') 0:00:01.234000''',
]);
});
});
group('getOffset', () {
setUp(() {
fakeConnection.responses['get_offset'] = jsonEncode(makeFakeResponse(<String, double>{
'dx': 11,
'dy': 12,
}));
});
test('sends the getCenter command', () async {
final DriverOffset result = await driver.getCenter(find.byValueKey(123), timeout: _kTestTimeout);
expect(result, const DriverOffset(11, 12));
expect(fakeConnection.commandLog, <String>[
r'''window.$flutterDriver('{"command":"get_offset","timeout":"1234","finderType":"ByValueKey","keyValueString":"123","keyValueType":"int","offsetType":"center"}') 0:00:01.234000''',
]);
});
test('sends the getTopLeft command', () async {
final DriverOffset result = await driver.getTopLeft(find.byValueKey(123), timeout: _kTestTimeout);
expect(result, const DriverOffset(11, 12));
expect(fakeConnection.commandLog, <String>[
r'''window.$flutterDriver('{"command":"get_offset","timeout":"1234","finderType":"ByValueKey","keyValueString":"123","keyValueType":"int","offsetType":"topLeft"}') 0:00:01.234000''',
]);
});
test('sends the getTopRight command', () async {
final DriverOffset result = await driver.getTopRight(find.byValueKey(123), timeout: _kTestTimeout);
expect(result, const DriverOffset(11, 12));
expect(fakeConnection.commandLog, <String>[
r'''window.$flutterDriver('{"command":"get_offset","timeout":"1234","finderType":"ByValueKey","keyValueString":"123","keyValueType":"int","offsetType":"topRight"}') 0:00:01.234000''',
]);
});
test('sends the getBottomLeft command', () async {
final DriverOffset result = await driver.getBottomLeft(find.byValueKey(123), timeout: _kTestTimeout);
expect(result, const DriverOffset(11, 12));
expect(fakeConnection.commandLog, <String>[
r'''window.$flutterDriver('{"command":"get_offset","timeout":"1234","finderType":"ByValueKey","keyValueString":"123","keyValueType":"int","offsetType":"bottomLeft"}') 0:00:01.234000''',
]);
});
test('sends the getBottomRight command', () async {
final DriverOffset result = await driver.getBottomRight(find.byValueKey(123), timeout: _kTestTimeout);
expect(result, const DriverOffset(11, 12));
expect(fakeConnection.commandLog, <String>[
r'''window.$flutterDriver('{"command":"get_offset","timeout":"1234","finderType":"ByValueKey","keyValueString":"123","keyValueType":"int","offsetType":"bottomRight"}') 0:00:01.234000''',
]);
});
});
test('checks the health of the driver extension', () async {
fakeConnection.responses['get_health'] = jsonEncode(makeFakeResponse(<String, dynamic>{'status': 'ok'}));
await driver.checkHealth();
expect(fakeConnection.commandLog, <String>[
r'''window.$flutterDriver('{"command":"get_health"}') null''',
]);
});
group('WebFlutterDriver Unimplemented/Unsupported error', () {
test('forceGC', () async {
expect(driver.forceGC(), throwsUnimplementedError);
});
test('getVmFlags', () async {
expect(driver.getVmFlags(), throwsUnimplementedError);
});
test('waitUntilFirstFrameRasterized', () async {
expect(driver.waitUntilFirstFrameRasterized(), throwsUnimplementedError);
});
test('appIsolate', () async {
expect(() => driver.appIsolate.extensionRPCs, throwsUnsupportedError);
});
test('serviceClient', () async {
expect(() => driver.serviceClient.getVM(), throwsUnsupportedError);
});
});
group('runUnsynchronized', () {
test('wrap waitFor with runUnsynchronized', () async {
fakeConnection.responses['waitFor'] = jsonEncode(makeFakeResponse(<String, dynamic>{'text': 'hello'}));
fakeConnection.responses['set_frame_sync'] = jsonEncode(makeFakeResponse(<String, dynamic>{}));
await driver.runUnsynchronized(() async {
await driver.waitFor(find.byTooltip('foo'), timeout: _kTestTimeout);
});
expect(fakeConnection.commandLog, <String>[
r'''window.$flutterDriver('{"command":"set_frame_sync","enabled":"false"}') null''',
r'''window.$flutterDriver('{"command":"waitFor","timeout":"1234","finderType":"ByTooltipMessage","text":"foo"}') 0:00:01.234000''',
r'''window.$flutterDriver('{"command":"set_frame_sync","enabled":"true"}') null''',
]);
});
});
});
group('WebFlutterDriver with non-chrome browser', () {
FakeFlutterWebConnection fakeConnection;
late WebFlutterDriver driver;
setUp(() {
fakeConnection = FakeFlutterWebConnection();
driver = WebFlutterDriver.connectedTo(fakeConnection);
});
test('tracing', () async {
expect(driver.traceAction(() async { return Future<dynamic>.value(); }), throwsUnsupportedError);
expect(driver.startTracing(), throwsUnsupportedError);
expect(driver.stopTracingAndDownloadTimeline(), throwsUnsupportedError);
expect(driver.clearTimeline(), throwsUnsupportedError);
});
});
}
// This function will verify the format of the script and return the actual
// script. The script will be in the following format:
// window.flutterDriver('[actual script]')
String _checkAndEncode(dynamic script) {
expect(script, isA<String>());
final String scriptString = script as String;
expect(scriptString.startsWith(_kWebScriptPrefix), isTrue);
expect(scriptString.endsWith(_kWebScriptSuffix), isTrue);
// Strip prefix and suffix
return scriptString.substring(_kWebScriptPrefix.length, script.length - 2);
}
vms.Response? makeFakeResponse(
Map<String, dynamic> response, {
bool isError = false,
}) {
return vms.Response.parse(<String, dynamic>{
'isError': isError,
'response': response,
});
}
void Function(vms.Isolate) changeIsolateEventAfter(int gets, vms.Event nextEvent) {
return (vms.Isolate i) {
gets -= 1;
if (gets == 0) {
i.pauseEvent = nextEvent;
}
};
}
class FakeFlutterWebConnection extends Fake implements FlutterWebConnection {
@override
bool supportsTimelineAction = false;
Map<String, dynamic> responses = <String, dynamic>{};
List<String> commandLog = <String>[];
@override
Future<dynamic> sendCommand(String script, Duration? duration) async {
commandLog.add('$script $duration');
final Map<String, dynamic> decoded = jsonDecode(_checkAndEncode(script)) as Map<String, dynamic>;
final dynamic response = responses[decoded['command']];
assert(response != null, 'Missing ${decoded['command']} in responses.');
return response;
}
@override
Future<void> close() async {
return;
}
}
class FakeVmService extends Fake implements vms.VmService {
FakeVmService(this.vm);
FakeVM? vm;
bool failOnSetFlag = false;
bool failOnResumeWith101 = false;
void Function(vms.Isolate)? onGetIsolate;
final List<String> connectionLog = <String>[];
@override
Future<vms.VM> getVM() async => vm!;
@override
Future<vms.Isolate> getIsolate(String isolateId) async {
connectionLog.add('getIsolate');
if (isolateId == vm!.isolate!.id) {
onGetIsolate?.call(vm!.isolate!);
return vm!.isolate!;
}
throw UnimplementedError('getIsolate called with unrecognized $isolateId');
}
@override
Future<vms.Success> resume(String isolateId, {String? step, int? frameIndex}) async {
assert(isolateId == vm!.isolate!.id);
connectionLog.add('resume');
if (failOnResumeWith101) {
throw vms.RPCError('resume', 101, '');
}
return vms.Success();
}
@override
Future<vms.Success> streamListen(String streamId) async {
connectionLog.add('streamListen $streamId');
return vms.Success();
}
@override
Future<vms.Success> streamCancel(String streamId) async {
connectionLog.add('streamCancel $streamId');
return vms.Success();
}
@override
Future<vms.Response> setFlag(String name, String value) async {
connectionLog.add('setFlag $name $value');
if (failOnSetFlag) {
throw Exception('setFlag failed');
}
return vms.Success();
}
@override
Stream<vms.Event> get onIsolateEvent async* {
connectionLog.add('onIsolateEvent');
yield vms.Event(
kind: vms.EventKind.kServiceExtensionAdded,
extensionRPC: 'ext.flutter.driver',
timestamp: 0,
);
}
List<String> commandLog = <String>[];
Map<String, vms.Response?> responses = <String, vms.Response?>{};
Future<void>? artificialExtensionDelay;
@override
Future<vms.Response> callServiceExtension(String method, {Map<dynamic, dynamic>? args, String? isolateId}) async {
commandLog.add('$method $args');
await artificialExtensionDelay;
final vms.Response? response = responses[args!['command']];
assert(response != null, 'Failed to create a response for ${args['command']}');
return response!;
}
@override
Future<vms.Success> clearVMTimeline() async {
connectionLog.add('clearVMTimeline');
return vms.Success();
}
@override
Future<vms.FlagList> getFlagList() async {
connectionLog.add('getFlagList');
return vms.FlagList(flags: <vms.Flag>[]);
}
int vmTimelineMicros = -1000000;
bool incrementMicros = false;
@override
Future<vms.Timestamp> getVMTimelineMicros() async {
connectionLog.add('getVMTimelineMicros');
if (incrementMicros || vmTimelineMicros < 0) {
vmTimelineMicros = vmTimelineMicros + 1000001;
}
return vms.Timestamp(timestamp: vmTimelineMicros);
}
@override
Future<vms.Success> setVMTimelineFlags(List<String> recordedStreams) async {
connectionLog.add('setVMTimelineFlags $recordedStreams');
return vms.Success();
}
final Map<int, vms.Timeline?> timelineResponses = <int, vms.Timeline?>{
1: vms.Timeline.parse(<String, dynamic>{
'traceEvents': <dynamic>[
<String, dynamic>{
'name': 'test event',
},
],
'timeOriginMicros': 0,
'timeExtentMicros': 999999,
}),
};
@override
Future<vms.Timeline> getVMTimeline({int? timeOriginMicros, int? timeExtentMicros}) async {
connectionLog.add('getVMTimeline $timeOriginMicros $timeExtentMicros');
final vms.Timeline? timeline = timelineResponses[timeOriginMicros ?? 1];
assert(timeline != null, 'Missing entry in timelineResponses[$timeOriginMicros]');
return timeline!;
}
@override
Future<void> dispose() async {
connectionLog.add('dispose');
}
@override
Future<void> get onDone async {}
}
class FakeVM extends Fake implements vms.VM {
FakeVM(this.isolate);
vms.Isolate? isolate;
int numberOfTriesBeforeResolvingIsolate = 0;
@override
List<vms.IsolateRef> get isolates {
numberOfTriesBeforeResolvingIsolate -= 1;
return <vms.Isolate>[
if (numberOfTriesBeforeResolvingIsolate <= 0)
isolate!,
];
}
}
vms.Isolate createFakeIsolate() => vms.Isolate(
id: '123',
number: '123',
extensionRPCs: <String>[],
);
| flutter/packages/flutter_driver/test/src/real_tests/flutter_driver_test.dart/0 | {
"file_path": "flutter/packages/flutter_driver/test/src/real_tests/flutter_driver_test.dart",
"repo_id": "flutter",
"token_count": 19098
} | 708 |
// 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 '../test/common.dart';
void main() {
// Tooling requires a single trivial test
test('it runs a test', () {
expect(true, true);
});
}
| flutter/packages/flutter_driver/test_driver/success_test.dart/0 | {
"file_path": "flutter/packages/flutter_driver/test_driver/success_test.dart",
"repo_id": "flutter",
"token_count": 95
} | 709 |
# Material and Cupertino Libraries Localizations
The `.arb` files in this directory contain localized values (primarily
strings) used by the Material and Cupertino libraries. The
`generated_material_localizations.dart` and
`generated_cupertino_localizations.dart` files combine all of the
localizations into a single Map that is linked with the rest of
flutter_localizations package.
If you're looking for information about internationalizing Flutter
apps in general, see the
[Internationalizing Flutter Apps](https://flutter.dev/tutorials/internationalization/) tutorial.
### Translations for one locale: .arb files
The Material and Cupertino libraries use
[Application Resource Bundle](https://github.com/google/app-resource-bundle/wiki/ApplicationResourceBundleSpecification)
files, which have a `.arb` extension, to store localized translations
of messages, format strings, and other values. This format is also
used by the Dart [intl](https://pub.dev/packages/intl) package.
The Material and Cupertino libraries only depend on a small subset
of the ARB format. Each .arb file contains a single JSON table that
maps from resource IDs to localized values.
Filenames contain the locale that the values have been translated
for. For example `material_de.arb` contains German translations, and
`material_ar.arb` contains Arabic translations. Files that contain
regional translations have names that include the locale's regional
suffix. For example `material_en_GB.arb` contains additional English
translations that are specific to Great Britain.
There is one language-specific .arb file for each supported locale. If
an additional file with a regional suffix is present, the regional
localizations are automatically merged with the language-specific ones.
The JSON table's keys, called resource IDs, are valid Dart variable
names. They correspond to methods from the `MaterialLocalizations` or
`CupertinoLocalizations` classes. For example:
```dart
Widget build(BuildContext context) {
return TextButton(
child: Text(
MaterialLocalizations.of(context).cancelButtonLabel,
),
);
}
```
This widget build method creates a button whose label is the local
translation of "CANCEL" which is defined for the `cancelButtonLabel`
resource ID.
Each of the language-specific .arb files contains an entry for
`cancelButtonLabel`.
### material_en.arb and cupertino_en.arb Define all of the resource IDs
All of the `material_*.arb` files whose names do not include a regional
suffix contain translations for the same set of resource IDs as
`material_en.arb`.
Similarly all of the `cupertino_*.arb` files whose names do not include
a regional suffix contain translations for the same set of resource IDs
as `cupertino_en.arb`.
For each resource ID defined for English, there is an additional resource
with an '@' prefix. These '@' resources are not used by the generated
Dart code at run time, they just exist to inform translators about how
the value will be used, and to inform the code generator about what code
to write.
```dart
"cancelButtonLabel": "CANCEL",
"@cancelButtonLabel": {
"description": "The label for cancel buttons and menu items.",
"type": "text"
},
```
### Values with Parameters, Plurals
A few of material translations contain `$variable` tokens. The
Material and Cupertino libraries replace these tokens with values at
run-time. For example:
```dart
"aboutListTileTitle": "About $applicationName",
```
The value for this resource ID is retrieved with a parameterized
method instead of a simple getter:
```dart
MaterialLocalizations.of(context).aboutListTileTitle(yourAppTitle)
```
The names of the `$variable` tokens must match the names of the
`MaterialLocalizations` method parameters.
Plurals are handled similarly, with a lookup method that includes a
quantity parameter. For example `selectedRowCountTitle` returns a
string like "1 item selected" or "no items selected".
```dart
MaterialLocalizations.of(context).selectedRowCountTitle(yourRowCount)
```
Plural translations can be provided for several quantities: 0, 1, 2,
"few", "many", "other". The variations are identified by a resource ID
suffix which must be one of "Zero", "One", "Two", "Few", "Many",
"Other". The "Other" variation is used when none of the other
quantities apply. All plural resources must include a resource with
the "Other" suffix. For example the English translations
('material_en.arb') for `selectedRowCountTitle` are:
```dart
"selectedRowCountTitleZero": "No items selected",
"selectedRowCountTitleOne": "1 item selected",
"selectedRowCountTitleOther": "$selectedRowCount items selected",
```
When defining new resources that handle pluralizations, the "One" and
the "Other" forms must, at minimum, always be defined in the source
English ARB files.
### scriptCategory and timeOfDayFormat for Material library
In `material_en.arb`, the values of these resource IDs are not
translations, they're keywords that help define an app's text theme
and time picker layout respectively.
The value of `timeOfDayFormat` defines how a time picker displayed by
[showTimePicker()](https://api.flutter.dev/flutter/material/showTimePicker.html)
formats and lays out its time controls. The value of `timeOfDayFormat`
must be a string that matches one of the formats defined by
<https://api.flutter.dev/flutter/material/TimeOfDayFormat.html>.
It is converted to an enum value because the `material_en.arb` file
has this value labeled as `"x-flutter-type": "icuShortTimePattern"`.
The value of `scriptCategory` is based on the
[Language categories reference](https://material.io/design/typography/language-support.html#language-categories-reference)
section in the Material spec. The Material theme uses the
`scriptCategory` value to lookup a localized version of the default
`TextTheme`, see
[Typography.geometryThemeFor](https://api.flutter.dev/flutter/material/Typography/geometryThemeFor.html).
### 'generated_*_localizations.dart': all of the localizations
All of the localizations are combined in a single file per library
using the gen_localizations script.
You can see what that script would generate by running:
```dart
dart dev/tools/localization/bin/gen_localizations.dart
```
Actually update the generated files with:
```dart
dart dev/tools/localization/bin/gen_localizations.dart --overwrite
```
The gen_localizations script just combines the contents of all of the
.arb files, each into a class which extends `Global*Localizations`.
The `MaterialLocalizations` and `CupertinoLocalizations`
class implementations use these to lookup localized resource values.
The gen_localizations script must be run by hand after .arb files have
been updated. The script optionally takes parameters
1. The path to this directory,
2. The file name prefix (the file name less the locale
suffix) for the .arb files in this directory.
### Special handling for the Kannada (kn) translations
Originally, the cupertino_kn.arb and material_kn.arb files contained unicode
characters that can cause current versions of Emacs on Linux to crash. There is
more information here: https://github.com/flutter/flutter/issues/36704.
Rather than risking developers' editor sessions, the strings in these arb files
(and the code generated for them) have been encoded using the appropriate
escapes for JSON and Dart. The JSON format arb files were rewritten with
dev/tools/localization/bin/encode_kn_arb_files.dart. The localizations code
generator uses generateEncodedString()
from dev/tools/localization/localizations_utils.dart.
### Support for Pashto (ps) translations
When Flutter first set up i18n for the Material library, Pashto (ps)
translations were included for the first set of Material widgets.
However, Pashto was never set up to be continuously maintained in
Flutter by Google, so material_ps.arb was never updated beyond the
initial commit.
To prevent breaking applications that rely on these original Pashto
translations, they will be kept. However, all new strings will have
the English translation until support for Pashto is provided.
See https://github.com/flutter/flutter/issues/60598.
### Translations Status, Reporting Errors
The translations (the `.arb` files) in this directory are based on the
English translations in `material_en.arb` and `cupertino_en.arb`.
Google contributes translations for all the languages supported by
this package. (Googlers, for more details see <go/flutter-l10n>.)
If you have feedback about the translations please
[file an issue on the Flutter github repo](https://github.com/flutter/flutter/issues/new?template=2_bug.yml).
### See Also
The [Internationalizing Flutter Apps](https://flutter.dev/tutorials/internationalization/)
tutorial describes how to use the internationalization APIs in an
ordinary Flutter app.
[Application Resource Bundle](https://code.google.com/p/arb/wiki/ApplicationResourceBundleSpecification)
covers the `.arb` file format used to store localized translations
of messages, format strings, and other values.
The Dart [intl](https://pub.dev/packages/intl)
package supports internationalization.
| flutter/packages/flutter_localizations/lib/src/l10n/README.md/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/README.md",
"repo_id": "flutter",
"token_count": 2363
} | 710 |
{
"datePickerHourSemanticsLabelOne": "$hour ακριβώς",
"datePickerHourSemanticsLabelOther": "$hour ακριβώς",
"datePickerMinuteSemanticsLabelOne": "1 λεπτό",
"datePickerMinuteSemanticsLabelOther": "$minute λεπτά",
"datePickerDateOrder": "dmy",
"datePickerDateTimeOrder": "date_time_dayPeriod",
"anteMeridiemAbbreviation": "π.μ.",
"postMeridiemAbbreviation": "μ.μ.",
"todayLabel": "Σήμερα",
"alertDialogLabel": "Ειδοποίηση",
"timerPickerHourLabelOne": "ώρα",
"timerPickerHourLabelOther": "ώρες",
"timerPickerMinuteLabelOne": "λεπ.",
"timerPickerMinuteLabelOther": "λεπ.",
"timerPickerSecondLabelOne": "δευτ.",
"timerPickerSecondLabelOther": "δευτ.",
"cutButtonLabel": "Αποκοπή",
"copyButtonLabel": "Αντιγραφή",
"pasteButtonLabel": "Επικόλληση",
"clearButtonLabel": "Clear",
"selectAllButtonLabel": "Επιλογή όλων",
"tabSemanticsLabel": "Καρτέλα $tabIndex από $tabCount",
"modalBarrierDismissLabel": "Παράβλεψη",
"searchTextFieldPlaceholderLabel": "Αναζήτηση",
"noSpellCheckReplacementsLabel": "Δεν βρέθηκαν αντικαταστάσεις",
"menuDismissLabel": "Παράβλεψη μενού",
"lookUpButtonLabel": "Look Up",
"searchWebButtonLabel": "Αναζήτηση στον ιστό",
"shareButtonLabel": "Κοινοποίηση…"
}
| flutter/packages/flutter_localizations/lib/src/l10n/cupertino_el.arb/0 | {
"file_path": "flutter/packages/flutter_localizations/lib/src/l10n/cupertino_el.arb",
"repo_id": "flutter",
"token_count": 623
} | 711 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.